19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCTargetOptions.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/TargetSelect.h"
35 using namespace clang;
38 class ClangAsmParserCallback :
public llvm::MCAsmParserSemaCallback {
52 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
53 AsmTokOffsets(Offsets) {
54 assert(AsmToks.size() == AsmTokOffsets.size());
57 void *LookupInlineAsmIdentifier(StringRef &LineBuf,
58 llvm::InlineAsmIdentifierInfo &Info,
59 bool IsUnevaluatedContext)
override {
62 const Token *FirstOrigToken =
nullptr;
63 findTokensForString(LineBuf, LineToks, FirstOrigToken);
65 unsigned NumConsumedToks;
67 LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
71 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
76 assert(FirstOrigToken &&
"not using original tokens?");
79 assert(FirstOrigToken[NumConsumedToks].getLocation() ==
80 LineToks[NumConsumedToks].getLocation());
81 unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
82 unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
86 unsigned TotalOffset =
87 (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
88 AsmTokOffsets[FirstIndex]);
89 LineBuf = LineBuf.substr(0, TotalOffset);
93 Info.OpDecl =
static_cast<void *
>(Result.
get());
97 StringRef LookupInlineAsmLabel(StringRef Identifier,
llvm::SourceMgr &LSM,
102 TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
106 bool LookupInlineAsmField(StringRef
Base, StringRef Member,
107 unsigned &
Offset)
override {
108 return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
112 static void DiagHandlerCallback(
const llvm::SMDiagnostic &D,
void *
Context) {
113 ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
119 const Token *&FirstOrigToken)
const {
122 assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
123 !std::less<const char *>()(AsmString.end(), Str.end()));
126 unsigned FirstCharOffset = Str.begin() - AsmString.begin();
127 const unsigned *FirstTokOffset = std::lower_bound(
128 AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
132 assert(*FirstTokOffset == FirstCharOffset);
136 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
137 FirstOrigToken = &AsmToks[FirstTokIndex];
138 unsigned LastCharOffset = Str.end() - AsmString.begin();
139 for (
unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
140 if (AsmTokOffsets[i] >= LastCharOffset)
142 TempToks.push_back(AsmToks[i]);
150 const llvm::MemoryBuffer *LBuf =
151 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
152 unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
155 const unsigned *TokOffsetPtr =
156 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(),
Offset);
157 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
158 unsigned TokOffset = *TokOffsetPtr;
164 if (TokIndex < AsmToks.size()) {
165 const Token &Tok = AsmToks[TokIndex];
172 void handleDiagnostic(
const llvm::SMDiagnostic &D) {
175 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
185 unsigned &NumLineToksConsumed,
187 bool IsUnevaluatedContext) {
188 llvm::InlineAsmIdentifierInfo &Info =
189 *(llvm::InlineAsmIdentifierInfo *)CastInfo;
195 Token EndOfStreamTok;
197 EndOfStreamTok.
setKind(EndOfStream);
198 LineToks.push_back(EndOfStreamTok);
201 LineToks.push_back(Tok);
203 PP.EnterTokenStream(LineToks,
true);
211 ParseOptionalCXXScopeSpecifier(SS,
nullptr,
false);
219 if (Tok.
is(tok::kw_this)) {
220 Result = ParseCXXThis();
228 nullptr, TemplateKWLoc, Id);
231 IsUnevaluatedContext);
236 while (Result.
isUsable() && Tok.
is(tok::period)) {
238 if (IdTok.
isNot(tok::identifier))
248 unsigned LineIndex = 0;
249 if (Tok.
is(EndOfStream)) {
250 LineIndex = LineToks.size() - 2;
252 while (LineToks[LineIndex].getLocation() != Tok.
getLocation()) {
254 assert(LineIndex < LineToks.size() - 2);
260 if (Invalid || Tok.
is(EndOfStream)) {
261 NumLineToksConsumed = LineToks.size() - 2;
264 NumLineToksConsumed = LineIndex;
269 for (
unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
272 assert(Tok.
is(EndOfStream));
288 assert(!AsmToks.empty() &&
"Didn't expect an empty AsmToks!");
291 bool isNewStatement =
true;
293 for (
unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
294 const Token &Tok = AsmToks[i];
299 isNewStatement =
true;
308 TokOffsets.push_back(Asm.size());
311 if (Tok.
is(tok::kw_asm)) {
314 PP.
Diag(AsmLoc, diag::err_asm_empty);
323 bool SpellingInvalid =
false;
324 Asm += PP.
getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
325 assert(!SpellingInvalid &&
"spelling was invalid after correct parse?");
328 isNewStatement =
false;
335 assert(TokOffsets.size() == AsmToks.size());
343 default:
return false;
346 case tok::kw_volatile:
347 case tok::kw_restrict:
348 case tok::kw___private:
349 case tok::kw___local:
350 case tok::kw___global:
351 case tok::kw___constant:
352 case tok::kw___generic:
353 case tok::kw___read_only:
354 case tok::kw___read_write:
355 case tok::kw___write_only:
362 return TokAfterAsm.
is(tok::l_paren) || TokAfterAsm.
is(tok::kw_goto) ||
386 bool SingleLineMode =
true;
387 unsigned BraceNesting = 0;
388 unsigned short savedBraceCount = BraceCount;
389 bool InAsmComment =
false;
392 unsigned NumTokensRead = 0;
394 bool SkippedStartOfLine =
false;
396 if (Tok.
is(tok::l_brace)) {
398 SingleLineMode =
false;
400 EndLoc = ConsumeBrace();
401 LBraceLocs.push_back(EndLoc);
405 std::pair<FileID, unsigned> ExpAsmLoc =
407 FID = ExpAsmLoc.first;
418 if (!InAsmComment && Tok.
is(tok::l_brace)) {
421 AsmToks.push_back(Tok);
422 EndLoc = ConsumeBrace();
424 LBraceLocs.push_back(EndLoc);
428 }
else if (!InAsmComment && Tok.
is(tok::semi)) {
431 if (!SingleLineMode) {
433 std::pair<FileID, unsigned> ExpSemiLoc =
435 FID = ExpSemiLoc.first;
438 }
else if (SingleLineMode || InAsmComment) {
441 std::pair<FileID, unsigned> ExpLoc =
443 if (ExpLoc.first != FID ||
444 SrcMgr.
getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
449 bool isAsm = Tok.
is(tok::kw_asm);
453 InAsmComment =
false;
461 }
else if (Tok.
is(tok::semi)) {
467 }
else if (!InAsmComment && Tok.
is(tok::r_brace)) {
475 if (!InAsmComment && BraceNesting && Tok.
is(tok::r_brace) &&
476 BraceCount == (savedBraceCount + BraceNesting)) {
480 if (SingleLineMode || BraceNesting > 1) {
482 AsmToks.push_back(Tok);
484 EndLoc = ConsumeBrace();
488 if (BraceNesting == 0 && !SingleLineMode)
491 LBraceLocs.pop_back();
506 if (SkippedStartOfLine)
508 AsmToks.push_back(Tok);
513 SkippedStartOfLine =
false;
516 if (BraceNesting && BraceCount != savedBraceCount) {
518 for (
unsigned i = 0; i < BraceNesting; ++i) {
519 Diag(Tok, diag::err_expected) << tok::r_brace;
520 Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
521 LBraceLocs.pop_back();
524 }
else if (NumTokensRead == 0) {
526 Diag(Tok, diag::err_expected) << tok::l_brace;
537 llvm::Triple::ArchType ArchTy = TheTriple.getArch();
538 const std::string &TT = TheTriple.getTriple();
539 const llvm::Target *TheTarget =
nullptr;
540 bool UnsupportedArch =
541 (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
542 if (UnsupportedArch) {
543 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
546 TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
548 Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
551 assert(!LBraceLocs.empty() &&
"Should have at least one location here");
555 if (!TheTarget || AsmToks.empty()) {
556 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
558 ConstraintRefs, ClobberRefs, Exprs, EndLoc);
568 std::string FeaturesStr =
571 std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
572 std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
574 std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
575 std::unique_ptr<llvm::MCObjectFileInfo> MOFI(
new llvm::MCObjectFileInfo());
576 std::unique_ptr<llvm::MCSubtargetInfo> STI(
577 TheTarget->createMCSubtargetInfo(TT, TO.
CPU, FeaturesStr));
580 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
583 std::unique_ptr<llvm::MemoryBuffer>
Buffer =
584 llvm::MemoryBuffer::getMemBuffer(AsmString,
"<MS inline asm>");
587 TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
589 std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
590 std::unique_ptr<llvm::MCAsmParser>
Parser(
591 createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
594 llvm::MCTargetOptions MCOptions;
595 std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
596 TheTarget->createMCAsmParser(*STI, *
Parser, *MII, MCOptions));
598 std::unique_ptr<llvm::MCInstPrinter> IP(
599 TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
602 Parser->setAssemblerDialect(1);
603 Parser->setTargetParser(*TargetParser.get());
604 Parser->setParsingInlineAsm(
true);
605 TargetParser->setParsingInlineAsm(
true);
607 ClangAsmParserCallback
Callback(*
this, AsmLoc, AsmString, AsmToks,
609 TargetParser->setSemaCallback(&
Callback);
610 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
615 std::string AsmStringIR;
620 NumInputs, OpExprs, Constraints, Clobbers,
626 llvm::erase_if(Clobbers, [](
const std::string &C) {
627 return C ==
"fpsw" || C ==
"mxcsr";
631 ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
634 unsigned NumExprs = NumOutputs + NumInputs;
635 ConstraintRefs.resize(NumExprs);
636 Exprs.resize(NumExprs);
637 for (
unsigned i = 0, e = NumExprs; i != e; ++i) {
638 Expr *OpExpr =
static_cast<Expr *
>(OpExprs[i].first);
643 if (OpExprs[i].second)
647 ConstraintRefs[i] = StringRef(Constraints[i]);
652 return Actions.
ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
653 NumOutputs, NumInputs, ConstraintRefs,
654 ClobberRefs, Exprs, EndLoc);
676 StmtResult Parser::ParseAsmStatement(
bool &msAsm) {
677 assert(Tok.
is(tok::kw_asm) &&
"Not an asm stmt");
682 return ParseMicrosoftAsmStatement(AsmLoc);
687 ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
691 Diag(Loc, diag::warn_asm_qualifier_ignored) <<
"const";
693 Diag(Loc, diag::warn_asm_qualifier_ignored) <<
"restrict";
696 Diag(Loc, diag::warn_asm_qualifier_ignored) <<
"_Atomic";
702 if (Tok.
is(tok::kw_goto)) {
703 Diag(Tok, diag::err_asm_goto_not_supported_yet);
708 if (Tok.
isNot(tok::l_paren)) {
709 Diag(Tok, diag::err_expected_lparen_after) <<
"asm";
716 ExprResult AsmString(ParseAsmStringLiteral());
720 if (!(
getLangOpts().GNUAsm || AsmString.isInvalid())) {
721 const auto *SL = cast<StringLiteral>(AsmString.get());
722 if (!SL->getString().trim().empty())
723 Diag(Loc, diag::err_gnu_inline_asm_disabled);
726 if (AsmString.isInvalid()) {
733 ExprVector Constraints;
737 if (Tok.
is(tok::r_paren)) {
742 Constraints, Exprs, AsmString.get(),
743 Clobbers, T.getCloseLocation());
747 bool AteExtraColon =
false;
748 if (Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
750 AteExtraColon = Tok.
is(tok::coloncolon);
753 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
757 unsigned NumOutputs = Names.size();
760 if (AteExtraColon || Tok.
is(tok::colon) || Tok.
is(tok::coloncolon)) {
763 AteExtraColon =
false;
765 AteExtraColon = Tok.
is(tok::coloncolon);
769 if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
773 assert(Names.size() == Constraints.size() &&
774 Constraints.size() == Exprs.size() &&
"Input operand size mismatch!");
776 unsigned NumInputs = Names.size() - NumOutputs;
779 if (AteExtraColon || Tok.
is(tok::colon)) {
784 if (Tok.
isNot(tok::r_paren)) {
788 if (Clobber.isInvalid())
791 Clobbers.push_back(Clobber.get());
801 AsmLoc,
false, isVolatile, NumOutputs, NumInputs, Names.data(),
802 Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
822 if (!isTokenStringLiteral() && Tok.
isNot(tok::l_square))
827 if (Tok.
is(tok::l_square)) {
831 if (Tok.
isNot(tok::identifier)) {
832 Diag(Tok, diag::err_expected) << tok::identifier;
843 Names.push_back(
nullptr);
845 ExprResult Constraint(ParseAsmStringLiteral());
846 if (Constraint.isInvalid()) {
850 Constraints.push_back(Constraint.get());
852 if (Tok.
isNot(tok::l_paren)) {
853 Diag(Tok, diag::err_expected_lparen_after) <<
"asm operand";
867 Exprs.push_back(Res.
get());
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
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
const Token & LookAhead(unsigned N)
Peeks ahead N tokens and returns that token without consuming any tokens.
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.
std::unique_ptr< llvm::MemoryBuffer > Buffer
void setFlag(TokenFlags Flag)
Set the specified flag.
Parser - This implements a parser for the C family of languages.
Options for controlling the target.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags=static_cast< SkipUntilFlags >(0))
SkipUntil - Read tokens until we get to the specified token, then consume it (unless StopBeforeMatch ...
static bool isGCCAsmStatement(const Token &TokAfterAsm)
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
bool TryConsumeToken(tok::TokenKind Expected)
One of these records is kept for each identifier that is lexed.
Token - This structure provides full information about a lexed token.
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation &TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
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.
Defines the Diagnostic-related interfaces.
Represents a C++ nested-name-specifier or a global scope specifier.
tok::TokenKind getKind() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, llvm::InlineAsmIdentifierInfo &Info, SourceLocation AsmLoc)
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, llvm::InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext)
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
MatchFinder::MatchCallback * Callback
static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc, ArrayRef< Token > AsmToks, SmallVectorImpl< unsigned > &TokOffsets, SmallString< 512 > &Asm)
Turn a sequence of our tokens back into a string that we can hand to the MC asm parser.
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.
std::string CPU
If given, the name of the target CPU to generate code for.
Stop skipping at semicolon.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl< Token > &LineToks, unsigned &NumLineToksConsumed, void *Info, bool IsUnevaluated)
Parse an identifier in an MS-style inline assembly block.
Encodes a location in the source.
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
LabelDecl - Represents the declaration of a label.
Scope * getCurScope() const
void Lex(Token &Result)
Lex the next token for this preprocessor.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
static bool isTypeQualifier(const Token &Tok)
isTypeQualifier - Return true if the current token could be the start of a type-qualifier-list.
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.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
TargetOptions & getTargetOpts() const
Retrieve the target options.
ActionResult< Stmt * > StmtResult
Captures information about "declaration specifiers".
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
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)
void clearFlag(TokenFlags Flag)
Unset the specified flag.
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