19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/MC/MCTargetOptions.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/TargetSelect.h"
34 using namespace clang;
37 class ClangAsmParserCallback :
public llvm::MCAsmParserSemaCallback {
51 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
52 AsmTokOffsets(Offsets) {
53 assert(AsmToks.size() == AsmTokOffsets.size());
56 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
57 llvm::InlineAsmIdentifierInfo &Info,
58 bool IsUnevaluatedContext)
override {
61 const Token *FirstOrigToken =
nullptr;
62 findTokensForString(LineBuf, LineToks, FirstOrigToken);
64 unsigned NumConsumedToks;
66 LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
70 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
75 assert(FirstOrigToken &&
"not using original tokens?");
78 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
79 LineToks[NumConsumedToks].getLocation());
80 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
81 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
85 unsigned TotalOffset =
86 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
87 AsmTokOffsets[FirstIndex]);
88 LineBuf = LineBuf.substr(0, TotalOffset);
92 Info.OpDecl =
static_cast<void *
>(Result.
get());
96 StringRef LookupInlineAsmLabel(StringRef Identifier,
llvm::SourceMgr &LSM,
101 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
105 bool LookupInlineAsmField(StringRef
Base, StringRef Member,
106 unsigned &
Offset)
override {
107 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
111 static void DiagHandlerCallback(
const llvm::SMDiagnostic &D,
void *
Context) {
112 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
118 const Token *&FirstOrigToken)
const {
121 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
122 !std::less<const char *>()(AsmString.end(), Str.end()));
125 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
126 const unsigned *FirstTokOffset = std::lower_bound(
127 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
131 assert(*FirstTokOffset == FirstCharOffset);
135 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
136 FirstOrigToken = &AsmToks[FirstTokIndex];
137 unsigned LastCharOffset = Str.end() - AsmString.begin();
138 for (
unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
139 if (AsmTokOffsets[i] >= LastCharOffset)
141 TempToks.push_back(AsmToks[i]);
149 const llvm::MemoryBuffer *LBuf =
150 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
151 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
154 const unsigned *TokOffsetPtr =
155 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
Offset);
156 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
157 unsigned TokOffset = *TokOffsetPtr;
163 if (TokIndex < AsmToks.size()) {
164 const Token &Tok = AsmToks[TokIndex];
171 void handleDiagnostic(
const llvm::SMDiagnostic &D) {
174 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
184 unsigned &NumLineToksConsumed,
186 bool IsUnevaluatedContext) {
187 llvm::InlineAsmIdentifierInfo &Info =
188 *(llvm::InlineAsmIdentifierInfo *)CastInfo;
194 Token EndOfStreamTok;
196 EndOfStreamTok.
setKind(EndOfStream);
197 LineToks.push_back(EndOfStreamTok);
200 LineToks.push_back(Tok);
212 ParseOptionalCXXScopeSpecifier(SS,
ParsedType(),
false);
226 unsigned LineIndex = 0;
227 if (Tok.
is(EndOfStream)) {
228 LineIndex = LineToks.size() - 2;
230 while (LineToks[LineIndex].getLocation() != Tok.
getLocation()) {
232 assert(LineIndex < LineToks.size() - 2);
238 if (Invalid || Tok.
is(EndOfStream)) {
239 NumLineToksConsumed = LineToks.size() - 2;
242 NumLineToksConsumed = LineIndex;
247 for (
unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
250 assert(Tok.
is(EndOfStream));
259 IsUnevaluatedContext);
268 assert(!AsmToks.empty() &&
"Didn't expect an empty AsmToks!");
271 bool isNewStatement =
true;
273 for (
unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
274 const Token &Tok = AsmToks[i];
279 isNewStatement =
true;
288 TokOffsets.push_back(Asm.size());
291 if (Tok.
is(tok::kw_asm)) {
294 PP.
Diag(AsmLoc, diag::err_asm_empty);
303 bool SpellingInvalid =
false;
304 Asm += PP.
getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
305 assert(!SpellingInvalid &&
"spelling was invalid after correct parse?");
308 isNewStatement =
false;
315 assert(TokOffsets.size() == AsmToks.size());
339 bool SingleLineMode =
true;
340 unsigned BraceNesting = 0;
341 unsigned short savedBraceCount = BraceCount;
342 bool InAsmComment =
false;
345 unsigned NumTokensRead = 0;
347 bool SkippedStartOfLine =
false;
349 if (Tok.
is(tok::l_brace)) {
351 SingleLineMode =
false;
353 EndLoc = ConsumeBrace();
354 LBraceLocs.push_back(EndLoc);
358 std::pair<FileID, unsigned> ExpAsmLoc =
360 FID = ExpAsmLoc.first;
371 if (!InAsmComment && Tok.
is(tok::l_brace)) {
374 EndLoc = ConsumeBrace();
376 LBraceLocs.push_back(EndLoc);
380 }
else if (!InAsmComment && Tok.
is(tok::semi)) {
383 if (!SingleLineMode) {
385 std::pair<FileID, unsigned> ExpSemiLoc =
387 FID = ExpSemiLoc.first;
390 }
else if (SingleLineMode || InAsmComment) {
393 std::pair<FileID, unsigned> ExpLoc =
395 if (ExpLoc.first != FID ||
396 SrcMgr.
getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
401 bool isAsm = Tok.
is(tok::kw_asm);
402 if (SingleLineMode && !isAsm)
405 InAsmComment =
false;
410 }
else if (!InAsmComment && Tok.
is(tok::r_brace)) {
418 if (!InAsmComment && BraceNesting && Tok.
is(tok::r_brace) &&
419 BraceCount == (savedBraceCount + BraceNesting)) {
422 EndLoc = ConsumeBrace();
426 if (BraceNesting == 0 && !SingleLineMode)
429 LBraceLocs.pop_back();
444 if (SkippedStartOfLine)
446 AsmToks.push_back(Tok);
451 SkippedStartOfLine =
false;
454 if (BraceNesting && BraceCount != savedBraceCount) {
456 for (
unsigned i = 0; i < BraceNesting; ++i) {
457 Diag(Tok, diag::err_expected) << tok::r_brace;
458 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
459 LBraceLocs.pop_back();
462 }
else if (NumTokensRead == 0) {
464 Diag(Tok, diag::err_expected) << tok::l_brace;
475 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
476 const std::string &TT = TheTriple.getTriple();
477 const llvm::Target *TheTarget =
nullptr;
478 bool UnsupportedArch =
479 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
480 if (UnsupportedArch) {
481 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
484 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
486 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
489 assert(!LBraceLocs.empty() &&
"Should have at least one location here");
493 if (!TheTarget || AsmToks.empty()) {
494 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
496 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
505 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
506 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
508 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
509 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(
new llvm::MCObjectFileInfo());
510 std::unique_ptr<llvm::MCSubtargetInfo> STI(
511 TheTarget->createMCSubtargetInfo(TT,
"",
""));
514 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
515 MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
516 llvm::CodeModel::Default, Ctx);
517 std::unique_ptr<llvm::MemoryBuffer> Buffer =
518 llvm::MemoryBuffer::getMemBuffer(AsmString,
"<MS inline asm>");
521 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
523 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
524 std::unique_ptr<llvm::MCAsmParser>
Parser(
525 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
528 llvm::MCTargetOptions MCOptions;
529 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
530 TheTarget->createMCAsmParser(*STI, *
Parser, *MII, MCOptions));
532 std::unique_ptr<llvm::MCInstPrinter> IP(
533 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
536 Parser->setAssemblerDialect(1);
537 Parser->setTargetParser(*TargetParser.get());
538 Parser->setParsingInlineAsm(
true);
539 TargetParser->setParsingInlineAsm(
true);
541 ClangAsmParserCallback
Callback(*
this, AsmLoc, AsmString, AsmToks,
543 TargetParser->setSemaCallback(&
Callback);
544 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
549 std::string AsmStringIR;
554 NumInputs, OpExprs, Constraints, Clobbers,
560 auto End = std::remove(Clobbers.begin(), Clobbers.end(),
"fpsw");
561 Clobbers.erase(
End, Clobbers.end());
564 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
567 unsigned NumExprs = NumOutputs + NumInputs;
568 ConstraintRefs.resize(NumExprs);
569 Exprs.resize(NumExprs);
570 for (
unsigned i = 0, e = NumExprs; i != e; ++i) {
571 Expr *OpExpr =
static_cast<Expr *
>(OpExprs[i].first);
576 if (OpExprs[i].second)
580 ConstraintRefs[i] = StringRef(Constraints[i]);
585 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
586 NumOutputs, NumInputs, ConstraintRefs,
587 ClobberRefs, Exprs, EndLoc);
609 StmtResult Parser::ParseAsmStatement(
bool &msAsm) {
610 assert(Tok.
is(tok::kw_asm) &&
"Not an asm stmt");
614 !isTypeQualifier()) {
616 return ParseMicrosoftAsmStatement(AsmLoc);
621 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
625 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"const";
627 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"restrict";
630 Diag(Loc, diag::w_asm_qualifier_ignored) <<
"_Atomic";
634 if (Tok.
isNot(tok::l_paren)) {
635 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
642 ExprResult AsmString(ParseAsmStringLiteral());
646 if (!(
getLangOpts().GNUAsm || AsmString.isInvalid())) {
647 const auto *SL = cast<StringLiteral>(AsmString.get());
648 if (!SL->getString().trim().empty())
649 Diag(Loc, diag::err_gnu_inline_asm_disabled);
652 if (AsmString.isInvalid()) {
659 ExprVector Constraints;
663 if (Tok.
is(tok::r_paren)) {
668 Constraints, Exprs, AsmString.get(),
669 Clobbers, T.getCloseLocation());
673 bool AteExtraColon =
false;
674 if (Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
676 AteExtraColon = Tok.
is(tok::coloncolon);
679 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
683 unsigned NumOutputs = Names.size();
686 if (AteExtraColon || Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
689 AteExtraColon =
false;
691 AteExtraColon = Tok.
is(tok::coloncolon);
695 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
699 assert(Names.size() == Constraints.size() &&
700 Constraints.size() == Exprs.size() &&
"Input operand size mismatch!");
702 unsigned NumInputs = Names.size() - NumOutputs;
705 if (AteExtraColon || Tok.
is(tok::colon)) {
710 if (Tok.
isNot(tok::r_paren)) {
714 if (Clobber.isInvalid())
717 Clobbers.push_back(Clobber.get());
727 AsmLoc,
false, isVolatile, NumOutputs, NumInputs, Names.data(),
728 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
748 if (!isTokenStringLiteral() && Tok.
isNot(tok::l_square))
753 if (Tok.
is(tok::l_square)) {
757 if (Tok.
isNot(tok::identifier)) {
758 Diag(Tok, diag::err_expected) << tok::identifier;
769 Names.push_back(
nullptr);
771 ExprResult Constraint(ParseAsmStringLiteral());
772 if (Constraint.isInvalid()) {
776 Constraints.push_back(Constraint.get());
778 if (Tok.
isNot(tok::l_paren)) {
779 Diag(Tok, diag::err_expected_lparen_after) <<
"asm operand";
793 Exprs.push_back(Res.
get());
bool isAtStartOfLine() const
SourceManager & getSourceManager() const
Defines the clang::ASTContext interface.
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
std::pair< FileID, unsigned > getDecomposedExpansionLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
StringRef getMSAsmLabel() const
const LangOptions & getLangOpts() const
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, SourceLocation RParenLoc)
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
void setFlag(TokenFlags Flag)
Set the specified flag.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
bool TryConsumeToken(tok::TokenKind Expected)
OpaquePtr< QualType > ParsedType
void setKind(tok::TokenKind K)
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ...
Represents a C++ unqualified-id that has been parsed.
const TargetInfo & getTargetInfo() const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep)
Creates clause with a list of variables VL and a linear step Step.
Represents a C++ nested-name-specifier or a global scope specifier.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, llvm::InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext)
MatchFinder::MatchCallback * Callback
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc, ArrayRef< Token > AsmToks, SmallVectorImpl< unsigned > &TokOffsets, SmallString< 512 > &Asm)
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
bool isNot(tok::TokenKind K) const
The result type of a method or function.
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, void *Info, bool IsUnevaluated)
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Scope * getCurScope() const
void EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens)
Add a "macro" context to the top of the include stack, which will cause the lexer to start returning ...
void Lex(Token &Result)
Lex the next token for this preprocessor.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
bool is(tok::TokenKind K) const
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, ParsedType ObjectType, SourceLocation &TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Defines the Diagnostic-related interfaces.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Captures information about "declaration specifiers".
SourceLocation ConsumeToken()
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult{return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
Defines the clang::TargetInfo interface.
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef< Token > AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef< StringRef > Constraints, ArrayRef< StringRef > Clobbers, ArrayRef< Expr * > Exprs, SourceLocation EndLoc)
This class handles loading and caching of source files into memory.
void startToken()
Reset all flags to cleared.
void * getPtrEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) pointer encoding for it...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo() const