ParseStmtAsm.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. //===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements parsing for GCC and Microsoft inline assembly.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "RAIIObjectsForParser.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/MC/MCAsmInfo.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCInstPrinter.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCParser/MCAsmParser.h"
  25. #include "llvm/MC/MCRegisterInfo.h"
  26. #include "llvm/MC/MCStreamer.h"
  27. #include "llvm/MC/MCSubtargetInfo.h"
  28. #include "llvm/MC/MCTargetAsmParser.h"
  29. #include "llvm/MC/MCTargetOptions.h"
  30. #include "llvm/Support/SourceMgr.h"
  31. #include "llvm/Support/TargetRegistry.h"
  32. #include "llvm/Support/TargetSelect.h"
  33. using namespace clang;
  34. #if 0 // HLSL Change - disable this block to avoid having to build/link llvmMC
  35. namespace {
  36. class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
  37. Parser &TheParser;
  38. SourceLocation AsmLoc;
  39. StringRef AsmString;
  40. /// The tokens we streamed into AsmString and handed off to MC.
  41. ArrayRef<Token> AsmToks;
  42. /// The offset of each token in AsmToks within AsmString.
  43. ArrayRef<unsigned> AsmTokOffsets;
  44. public:
  45. ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
  46. ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
  47. : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
  48. AsmTokOffsets(Offsets) {
  49. assert(AsmToks.size() == AsmTokOffsets.size());
  50. }
  51. void *LookupInlineAsmIdentifier(StringRef &LineBuf,
  52. llvm::InlineAsmIdentifierInfo &Info,
  53. bool IsUnevaluatedContext) override {
  54. // Collect the desired tokens.
  55. SmallVector<Token, 16> LineToks;
  56. const Token *FirstOrigToken = nullptr;
  57. findTokensForString(LineBuf, LineToks, FirstOrigToken);
  58. unsigned NumConsumedToks;
  59. ExprResult Result = TheParser.ParseMSAsmIdentifier(
  60. LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
  61. // If we consumed the entire line, tell MC that.
  62. // Also do this if we consumed nothing as a way of reporting failure.
  63. if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
  64. // By not modifying LineBuf, we're implicitly consuming it all.
  65. // Otherwise, consume up to the original tokens.
  66. } else {
  67. assert(FirstOrigToken && "not using original tokens?");
  68. // Since we're using original tokens, apply that offset.
  69. assert(FirstOrigToken[NumConsumedToks].getLocation() ==
  70. LineToks[NumConsumedToks].getLocation());
  71. unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
  72. unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
  73. // The total length we've consumed is the relative offset
  74. // of the last token we consumed plus its length.
  75. unsigned TotalOffset =
  76. (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
  77. AsmTokOffsets[FirstIndex]);
  78. LineBuf = LineBuf.substr(0, TotalOffset);
  79. }
  80. // Initialize the "decl" with the lookup result.
  81. Info.OpDecl = static_cast<void *>(Result.get());
  82. return Info.OpDecl;
  83. }
  84. StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
  85. llvm::SMLoc Location,
  86. bool Create) override {
  87. SourceLocation Loc = translateLocation(LSM, Location);
  88. LabelDecl *Label =
  89. TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
  90. return Label->getMSAsmLabel();
  91. }
  92. bool LookupInlineAsmField(StringRef Base, StringRef Member,
  93. unsigned &Offset) override {
  94. return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
  95. AsmLoc);
  96. }
  97. static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
  98. ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
  99. }
  100. private:
  101. /// Collect the appropriate tokens for the given string.
  102. void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
  103. const Token *&FirstOrigToken) const {
  104. // For now, assert that the string we're working with is a substring
  105. // of what we gave to MC. This lets us use the original tokens.
  106. assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
  107. !std::less<const char *>()(AsmString.end(), Str.end()));
  108. // Try to find a token whose offset matches the first token.
  109. unsigned FirstCharOffset = Str.begin() - AsmString.begin();
  110. const unsigned *FirstTokOffset = std::lower_bound(
  111. AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
  112. // For now, assert that the start of the string exactly
  113. // corresponds to the start of a token.
  114. assert(*FirstTokOffset == FirstCharOffset);
  115. // Use all the original tokens for this line. (We assume the
  116. // end of the line corresponds cleanly to a token break.)
  117. unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
  118. FirstOrigToken = &AsmToks[FirstTokIndex];
  119. unsigned LastCharOffset = Str.end() - AsmString.begin();
  120. for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
  121. if (AsmTokOffsets[i] >= LastCharOffset)
  122. break;
  123. TempToks.push_back(AsmToks[i]);
  124. }
  125. }
  126. SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
  127. // Compute an offset into the inline asm buffer.
  128. // FIXME: This isn't right if .macro is involved (but hopefully, no
  129. // real-world code does that).
  130. const llvm::MemoryBuffer *LBuf =
  131. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
  132. unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
  133. // Figure out which token that offset points into.
  134. const unsigned *TokOffsetPtr =
  135. std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
  136. unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
  137. unsigned TokOffset = *TokOffsetPtr;
  138. // If we come up with an answer which seems sane, use it; otherwise,
  139. // just point at the __asm keyword.
  140. // FIXME: Assert the answer is sane once we handle .macro correctly.
  141. SourceLocation Loc = AsmLoc;
  142. if (TokIndex < AsmToks.size()) {
  143. const Token &Tok = AsmToks[TokIndex];
  144. Loc = Tok.getLocation();
  145. Loc = Loc.getLocWithOffset(Offset - TokOffset);
  146. }
  147. return Loc;
  148. }
  149. void handleDiagnostic(const llvm::SMDiagnostic &D) {
  150. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  151. SourceLocation Loc = translateLocation(LSM, D.getLoc());
  152. TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
  153. }
  154. };
  155. }
  156. #endif // HLSL Change - disable this block to avoid having to build/link llvmMC
  157. /// Parse an identifier in an MS-style inline assembly block.
  158. ///
  159. /// \param CastInfo - a void* so that we don't have to teach Parser.h
  160. /// about the actual type.
  161. ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
  162. unsigned &NumLineToksConsumed,
  163. void *CastInfo,
  164. bool IsUnevaluatedContext) {
  165. assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change
  166. llvm::InlineAsmIdentifierInfo &Info =
  167. *(llvm::InlineAsmIdentifierInfo *)CastInfo;
  168. // Push a fake token on the end so that we don't overrun the token
  169. // stream. We use ';' because it expression-parsing should never
  170. // overrun it.
  171. const tok::TokenKind EndOfStream = tok::semi;
  172. Token EndOfStreamTok;
  173. EndOfStreamTok.startToken();
  174. EndOfStreamTok.setKind(EndOfStream);
  175. LineToks.push_back(EndOfStreamTok);
  176. // Also copy the current token over.
  177. LineToks.push_back(Tok);
  178. PP.EnterTokenStream(LineToks.begin(), LineToks.size(),
  179. /*disable macros*/ true,
  180. /*owns tokens*/ false);
  181. // Clear the current token and advance to the first token in LineToks.
  182. ConsumeAnyToken();
  183. // Parse an optional scope-specifier if we're in C++.
  184. CXXScopeSpec SS;
  185. if (getLangOpts().CPlusPlus) {
  186. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  187. }
  188. // Require an identifier here.
  189. SourceLocation TemplateKWLoc;
  190. UnqualifiedId Id;
  191. bool Invalid =
  192. ParseUnqualifiedId(SS,
  193. /*EnteringContext=*/false,
  194. /*AllowDestructorName=*/false,
  195. /*AllowConstructorName=*/false,
  196. /*ObjectType=*/ParsedType(), TemplateKWLoc, Id);
  197. // Figure out how many tokens we are into LineToks.
  198. unsigned LineIndex = 0;
  199. if (Tok.is(EndOfStream)) {
  200. LineIndex = LineToks.size() - 2;
  201. } else {
  202. while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
  203. LineIndex++;
  204. assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
  205. }
  206. }
  207. // If we've run into the poison token we inserted before, or there
  208. // was a parsing error, then claim the entire line.
  209. if (Invalid || Tok.is(EndOfStream)) {
  210. NumLineToksConsumed = LineToks.size() - 2;
  211. } else {
  212. // Otherwise, claim up to the start of the next token.
  213. NumLineToksConsumed = LineIndex;
  214. }
  215. // Finally, restore the old parsing state by consuming all the tokens we
  216. // staged before, implicitly killing off the token-lexer we pushed.
  217. for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
  218. ConsumeAnyToken();
  219. }
  220. assert(Tok.is(EndOfStream));
  221. ConsumeToken();
  222. // Leave LineToks in its original state.
  223. LineToks.pop_back();
  224. LineToks.pop_back();
  225. // Perform the lookup.
  226. return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
  227. IsUnevaluatedContext);
  228. }
  229. #if 0 // HLSL Change Start - disable this block to avoid having to build/link llvmMC
  230. /// Turn a sequence of our tokens back into a string that we can hand
  231. /// to the MC asm parser.
  232. static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
  233. ArrayRef<Token> AsmToks,
  234. SmallVectorImpl<unsigned> &TokOffsets,
  235. SmallString<512> &Asm) {
  236. assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
  237. // Is this the start of a new assembly statement?
  238. bool isNewStatement = true;
  239. for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
  240. const Token &Tok = AsmToks[i];
  241. // Start each new statement with a newline and a tab.
  242. if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
  243. Asm += "\n\t";
  244. isNewStatement = true;
  245. }
  246. // Preserve the existence of leading whitespace except at the
  247. // start of a statement.
  248. if (!isNewStatement && Tok.hasLeadingSpace())
  249. Asm += ' ';
  250. // Remember the offset of this token.
  251. TokOffsets.push_back(Asm.size());
  252. // Don't actually write '__asm' into the assembly stream.
  253. if (Tok.is(tok::kw_asm)) {
  254. // Complain about __asm at the end of the stream.
  255. if (i + 1 == e) {
  256. PP.Diag(AsmLoc, diag::err_asm_empty);
  257. return true;
  258. }
  259. continue;
  260. }
  261. // Append the spelling of the token.
  262. SmallString<32> SpellingBuffer;
  263. bool SpellingInvalid = false;
  264. Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
  265. assert(!SpellingInvalid && "spelling was invalid after correct parse?");
  266. // We are no longer at the start of a statement.
  267. isNewStatement = false;
  268. }
  269. // Ensure that the buffer is null-terminated.
  270. Asm.push_back('\0');
  271. Asm.pop_back();
  272. assert(TokOffsets.size() == AsmToks.size());
  273. return false;
  274. }
  275. #endif // HLSL Change End - disable this block to avoid having to build/link llvmMC
  276. /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
  277. /// this routine is called to collect the tokens for an MS asm statement.
  278. ///
  279. /// [MS] ms-asm-statement:
  280. /// ms-asm-block
  281. /// ms-asm-block ms-asm-statement
  282. ///
  283. /// [MS] ms-asm-block:
  284. /// '__asm' ms-asm-line '\n'
  285. /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
  286. ///
  287. /// [MS] ms-asm-instruction-block
  288. /// ms-asm-line
  289. /// ms-asm-line '\n' ms-asm-instruction-block
  290. ///
  291. StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
  292. assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change
  293. #if 1 // HLSL Change - disable this block to avoid having to build/link llvmMC
  294. return StmtResult();
  295. #else
  296. SourceManager &SrcMgr = PP.getSourceManager();
  297. SourceLocation EndLoc = AsmLoc;
  298. SmallVector<Token, 4> AsmToks;
  299. bool SingleLineMode = true;
  300. unsigned BraceNesting = 0;
  301. unsigned short savedBraceCount = BraceCount;
  302. bool InAsmComment = false;
  303. FileID FID;
  304. unsigned LineNo = 0;
  305. unsigned NumTokensRead = 0;
  306. SmallVector<SourceLocation, 4> LBraceLocs;
  307. bool SkippedStartOfLine = false;
  308. if (Tok.is(tok::l_brace)) {
  309. // Braced inline asm: consume the opening brace.
  310. SingleLineMode = false;
  311. BraceNesting = 1;
  312. EndLoc = ConsumeBrace();
  313. LBraceLocs.push_back(EndLoc);
  314. ++NumTokensRead;
  315. } else {
  316. // Single-line inline asm; compute which line it is on.
  317. std::pair<FileID, unsigned> ExpAsmLoc =
  318. SrcMgr.getDecomposedExpansionLoc(EndLoc);
  319. FID = ExpAsmLoc.first;
  320. LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
  321. LBraceLocs.push_back(SourceLocation());
  322. }
  323. SourceLocation TokLoc = Tok.getLocation();
  324. do {
  325. // If we hit EOF, we're done, period.
  326. if (isEofOrEom())
  327. break;
  328. if (!InAsmComment && Tok.is(tok::l_brace)) {
  329. // Consume the opening brace.
  330. SkippedStartOfLine = Tok.isAtStartOfLine();
  331. EndLoc = ConsumeBrace();
  332. BraceNesting++;
  333. LBraceLocs.push_back(EndLoc);
  334. TokLoc = Tok.getLocation();
  335. ++NumTokensRead;
  336. continue;
  337. } else if (!InAsmComment && Tok.is(tok::semi)) {
  338. // A semicolon in an asm is the start of a comment.
  339. InAsmComment = true;
  340. if (!SingleLineMode) {
  341. // Compute which line the comment is on.
  342. std::pair<FileID, unsigned> ExpSemiLoc =
  343. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  344. FID = ExpSemiLoc.first;
  345. LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
  346. }
  347. } else if (SingleLineMode || InAsmComment) {
  348. // If end-of-line is significant, check whether this token is on a
  349. // new line.
  350. std::pair<FileID, unsigned> ExpLoc =
  351. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  352. if (ExpLoc.first != FID ||
  353. SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
  354. // If this is a single-line __asm, we're done, except if the next
  355. // line begins with an __asm too, in which case we finish a comment
  356. // if needed and then keep processing the next line as a single
  357. // line __asm.
  358. bool isAsm = Tok.is(tok::kw_asm);
  359. if (SingleLineMode && !isAsm)
  360. break;
  361. // We're no longer in a comment.
  362. InAsmComment = false;
  363. if (isAsm) {
  364. LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
  365. SkippedStartOfLine = Tok.isAtStartOfLine();
  366. }
  367. } else if (!InAsmComment && Tok.is(tok::r_brace)) {
  368. // In MSVC mode, braces only participate in brace matching and
  369. // separating the asm statements. This is an intentional
  370. // departure from the Apple gcc behavior.
  371. if (!BraceNesting)
  372. break;
  373. }
  374. }
  375. if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
  376. BraceCount == (savedBraceCount + BraceNesting)) {
  377. // Consume the closing brace.
  378. SkippedStartOfLine = Tok.isAtStartOfLine();
  379. EndLoc = ConsumeBrace();
  380. BraceNesting--;
  381. // Finish if all of the opened braces in the inline asm section were
  382. // consumed.
  383. if (BraceNesting == 0 && !SingleLineMode)
  384. break;
  385. else {
  386. LBraceLocs.pop_back();
  387. TokLoc = Tok.getLocation();
  388. ++NumTokensRead;
  389. continue;
  390. }
  391. }
  392. // Consume the next token; make sure we don't modify the brace count etc.
  393. // if we are in a comment.
  394. EndLoc = TokLoc;
  395. if (InAsmComment)
  396. PP.Lex(Tok);
  397. else {
  398. // Set the token as the start of line if we skipped the original start
  399. // of line token in case it was a nested brace.
  400. if (SkippedStartOfLine)
  401. Tok.setFlag(Token::StartOfLine);
  402. AsmToks.push_back(Tok);
  403. ConsumeAnyToken();
  404. }
  405. TokLoc = Tok.getLocation();
  406. ++NumTokensRead;
  407. SkippedStartOfLine = false;
  408. } while (1);
  409. if (BraceNesting && BraceCount != savedBraceCount) {
  410. // __asm without closing brace (this can happen at EOF).
  411. for (unsigned i = 0; i < BraceNesting; ++i) {
  412. Diag(Tok, diag::err_expected) << tok::r_brace;
  413. Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
  414. LBraceLocs.pop_back();
  415. }
  416. return StmtError();
  417. } else if (NumTokensRead == 0) {
  418. // Empty __asm.
  419. Diag(Tok, diag::err_expected) << tok::l_brace;
  420. return StmtError();
  421. }
  422. // Okay, prepare to use MC to parse the assembly.
  423. SmallVector<StringRef, 4> ConstraintRefs;
  424. SmallVector<Expr *, 4> Exprs;
  425. SmallVector<StringRef, 4> ClobberRefs;
  426. // We need an actual supported target.
  427. const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
  428. llvm::Triple::ArchType ArchTy = TheTriple.getArch();
  429. const std::string &TT = TheTriple.getTriple();
  430. const llvm::Target *TheTarget = nullptr;
  431. bool UnsupportedArch =
  432. (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
  433. if (UnsupportedArch) {
  434. Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
  435. } else {
  436. std::string Error;
  437. TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
  438. if (!TheTarget)
  439. Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
  440. }
  441. assert(!LBraceLocs.empty() && "Should have at least one location here");
  442. // If we don't support assembly, or the assembly is empty, we don't
  443. // need to instantiate the AsmParser, etc.
  444. if (!TheTarget || AsmToks.empty()) {
  445. return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
  446. /*NumOutputs*/ 0, /*NumInputs*/ 0,
  447. ConstraintRefs, ClobberRefs, Exprs, EndLoc);
  448. }
  449. // Expand the tokens into a string buffer.
  450. SmallString<512> AsmString;
  451. SmallVector<unsigned, 8> TokOffsets;
  452. if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
  453. return StmtError();
  454. std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
  455. std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
  456. // Get the instruction descriptor.
  457. std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  458. std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
  459. std::unique_ptr<llvm::MCSubtargetInfo> STI(
  460. TheTarget->createMCSubtargetInfo(TT, "", ""));
  461. llvm::SourceMgr TempSrcMgr;
  462. llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
  463. MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
  464. llvm::CodeModel::Default, Ctx);
  465. std::unique_ptr<llvm::MemoryBuffer> Buffer =
  466. llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
  467. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  468. TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
  469. std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
  470. std::unique_ptr<llvm::MCAsmParser> Parser(
  471. createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
  472. // FIXME: init MCOptions from sanitizer flags here.
  473. llvm::MCTargetOptions MCOptions;
  474. std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
  475. TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
  476. std::unique_ptr<llvm::MCInstPrinter> IP(
  477. TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
  478. // Change to the Intel dialect.
  479. Parser->setAssemblerDialect(1);
  480. Parser->setTargetParser(*TargetParser.get());
  481. Parser->setParsingInlineAsm(true);
  482. TargetParser->setParsingInlineAsm(true);
  483. ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
  484. TokOffsets);
  485. TargetParser->setSemaCallback(&Callback);
  486. TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
  487. &Callback);
  488. unsigned NumOutputs;
  489. unsigned NumInputs;
  490. std::string AsmStringIR;
  491. SmallVector<std::pair<void *, bool>, 4> OpExprs;
  492. SmallVector<std::string, 4> Constraints;
  493. SmallVector<std::string, 4> Clobbers;
  494. if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
  495. NumInputs, OpExprs, Constraints, Clobbers,
  496. MII.get(), IP.get(), Callback))
  497. return StmtError();
  498. // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
  499. // fpsr as clobbers.
  500. auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
  501. Clobbers.erase(End, Clobbers.end());
  502. // Build the vector of clobber StringRefs.
  503. ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
  504. // Recast the void pointers and build the vector of constraint StringRefs.
  505. unsigned NumExprs = NumOutputs + NumInputs;
  506. ConstraintRefs.resize(NumExprs);
  507. Exprs.resize(NumExprs);
  508. for (unsigned i = 0, e = NumExprs; i != e; ++i) {
  509. Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
  510. if (!OpExpr)
  511. return StmtError();
  512. // Need address of variable.
  513. if (OpExprs[i].second)
  514. OpExpr =
  515. Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
  516. ConstraintRefs[i] = StringRef(Constraints[i]);
  517. Exprs[i] = OpExpr;
  518. }
  519. // FIXME: We should be passing source locations for better diagnostics.
  520. return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
  521. NumOutputs, NumInputs, ConstraintRefs,
  522. ClobberRefs, Exprs, EndLoc);
  523. #endif // HLSL Change
  524. }
  525. /// ParseAsmStatement - Parse a GNU extended asm statement.
  526. /// asm-statement:
  527. /// gnu-asm-statement
  528. /// ms-asm-statement
  529. ///
  530. /// [GNU] gnu-asm-statement:
  531. /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
  532. ///
  533. /// [GNU] asm-argument:
  534. /// asm-string-literal
  535. /// asm-string-literal ':' asm-operands[opt]
  536. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  537. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  538. /// ':' asm-clobbers
  539. ///
  540. /// [GNU] asm-clobbers:
  541. /// asm-string-literal
  542. /// asm-clobbers ',' asm-string-literal
  543. ///
  544. StmtResult Parser::ParseAsmStatement(bool &msAsm) {
  545. assert(!getLangOpts().HLSL && "no GNU assembly support in HLSL"); // HLSL Change
  546. assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
  547. SourceLocation AsmLoc = ConsumeToken();
  548. if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
  549. !isTypeQualifier()) {
  550. msAsm = true;
  551. return ParseMicrosoftAsmStatement(AsmLoc);
  552. }
  553. DeclSpec DS(AttrFactory);
  554. SourceLocation Loc = Tok.getLocation();
  555. ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
  556. // GNU asms accept, but warn, about type-qualifiers other than volatile.
  557. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  558. Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
  559. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  560. Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
  561. // FIXME: Once GCC supports _Atomic, check whether it permits it here.
  562. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  563. Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
  564. // Remember if this was a volatile asm.
  565. bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
  566. if (Tok.isNot(tok::l_paren)) {
  567. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  568. SkipUntil(tok::r_paren, StopAtSemi);
  569. return StmtError();
  570. }
  571. BalancedDelimiterTracker T(*this, tok::l_paren);
  572. T.consumeOpen();
  573. ExprResult AsmString(ParseAsmStringLiteral());
  574. // Check if GNU-style InlineAsm is disabled.
  575. // Error on anything other than empty string.
  576. if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {
  577. const auto *SL = cast<StringLiteral>(AsmString.get());
  578. if (!SL->getString().trim().empty())
  579. Diag(Loc, diag::err_gnu_inline_asm_disabled);
  580. }
  581. if (AsmString.isInvalid()) {
  582. // Consume up to and including the closing paren.
  583. T.skipToEnd();
  584. return StmtError();
  585. }
  586. SmallVector<IdentifierInfo *, 4> Names;
  587. ExprVector Constraints;
  588. ExprVector Exprs;
  589. ExprVector Clobbers;
  590. if (Tok.is(tok::r_paren)) {
  591. // We have a simple asm expression like 'asm("foo")'.
  592. T.consumeClose();
  593. return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
  594. /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
  595. Constraints, Exprs, AsmString.get(),
  596. Clobbers, T.getCloseLocation());
  597. }
  598. // Parse Outputs, if present.
  599. bool AteExtraColon = false;
  600. if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  601. // In C++ mode, parse "::" like ": :".
  602. AteExtraColon = Tok.is(tok::coloncolon);
  603. ConsumeToken();
  604. if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
  605. return StmtError();
  606. }
  607. unsigned NumOutputs = Names.size();
  608. // Parse Inputs, if present.
  609. if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  610. // In C++ mode, parse "::" like ": :".
  611. if (AteExtraColon)
  612. AteExtraColon = false;
  613. else {
  614. AteExtraColon = Tok.is(tok::coloncolon);
  615. ConsumeToken();
  616. }
  617. if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
  618. return StmtError();
  619. }
  620. assert(Names.size() == Constraints.size() &&
  621. Constraints.size() == Exprs.size() && "Input operand size mismatch!");
  622. unsigned NumInputs = Names.size() - NumOutputs;
  623. // Parse the clobbers, if present.
  624. if (AteExtraColon || Tok.is(tok::colon)) {
  625. if (!AteExtraColon)
  626. ConsumeToken();
  627. // Parse the asm-string list for clobbers if present.
  628. if (Tok.isNot(tok::r_paren)) {
  629. while (1) {
  630. ExprResult Clobber(ParseAsmStringLiteral());
  631. if (Clobber.isInvalid())
  632. break;
  633. Clobbers.push_back(Clobber.get());
  634. if (!TryConsumeToken(tok::comma))
  635. break;
  636. }
  637. }
  638. }
  639. T.consumeClose();
  640. return Actions.ActOnGCCAsmStmt(
  641. AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
  642. Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
  643. }
  644. /// ParseAsmOperands - Parse the asm-operands production as used by
  645. /// asm-statement, assuming the leading ':' token was eaten.
  646. ///
  647. /// [GNU] asm-operands:
  648. /// asm-operand
  649. /// asm-operands ',' asm-operand
  650. ///
  651. /// [GNU] asm-operand:
  652. /// asm-string-literal '(' expression ')'
  653. /// '[' identifier ']' asm-string-literal '(' expression ')'
  654. ///
  655. //
  656. // FIXME: Avoid unnecessary std::string trashing.
  657. bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
  658. SmallVectorImpl<Expr *> &Constraints,
  659. SmallVectorImpl<Expr *> &Exprs) {
  660. assert(!getLangOpts().HLSL && "no assembly support in HLSL"); // HLSL Change
  661. // 'asm-operands' isn't present?
  662. if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
  663. return false;
  664. while (1) {
  665. // Read the [id] if present.
  666. if (Tok.is(tok::l_square)) {
  667. BalancedDelimiterTracker T(*this, tok::l_square);
  668. T.consumeOpen();
  669. if (Tok.isNot(tok::identifier)) {
  670. Diag(Tok, diag::err_expected) << tok::identifier;
  671. SkipUntil(tok::r_paren, StopAtSemi);
  672. return true;
  673. }
  674. IdentifierInfo *II = Tok.getIdentifierInfo();
  675. ConsumeToken();
  676. Names.push_back(II);
  677. T.consumeClose();
  678. } else
  679. Names.push_back(nullptr);
  680. ExprResult Constraint(ParseAsmStringLiteral());
  681. if (Constraint.isInvalid()) {
  682. SkipUntil(tok::r_paren, StopAtSemi);
  683. return true;
  684. }
  685. Constraints.push_back(Constraint.get());
  686. if (Tok.isNot(tok::l_paren)) {
  687. Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
  688. SkipUntil(tok::r_paren, StopAtSemi);
  689. return true;
  690. }
  691. // Read the parenthesized expression.
  692. BalancedDelimiterTracker T(*this, tok::l_paren);
  693. T.consumeOpen();
  694. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
  695. T.consumeClose();
  696. if (Res.isInvalid()) {
  697. SkipUntil(tok::r_paren, StopAtSemi);
  698. return true;
  699. }
  700. Exprs.push_back(Res.get());
  701. // Eat the comma and continue parsing if it exists.
  702. if (!TryConsumeToken(tok::comma))
  703. return false;
  704. }
  705. }