1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This class implements the parser for assembly files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/BinaryFormat/Dwarf.h" 25 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCCodeView.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/MC/MCDirectives.h" 30 #include "llvm/MC/MCDwarf.h" 31 #include "llvm/MC/MCExpr.h" 32 #include "llvm/MC/MCInstPrinter.h" 33 #include "llvm/MC/MCInstrDesc.h" 34 #include "llvm/MC/MCInstrInfo.h" 35 #include "llvm/MC/MCObjectFileInfo.h" 36 #include "llvm/MC/MCParser/AsmCond.h" 37 #include "llvm/MC/MCParser/AsmLexer.h" 38 #include "llvm/MC/MCParser/MCAsmLexer.h" 39 #include "llvm/MC/MCParser/MCAsmParser.h" 40 #include "llvm/MC/MCParser/MCAsmParserExtension.h" 41 #include "llvm/MC/MCParser/MCAsmParserUtils.h" 42 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 43 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 44 #include "llvm/MC/MCRegisterInfo.h" 45 #include "llvm/MC/MCSection.h" 46 #include "llvm/MC/MCStreamer.h" 47 #include "llvm/MC/MCSymbol.h" 48 #include "llvm/MC/MCTargetOptions.h" 49 #include "llvm/MC/MCValue.h" 50 #include "llvm/Support/Casting.h" 51 #include "llvm/Support/CommandLine.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/MD5.h" 54 #include "llvm/Support/MathExtras.h" 55 #include "llvm/Support/MemoryBuffer.h" 56 #include "llvm/Support/SMLoc.h" 57 #include "llvm/Support/SourceMgr.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 #include <cassert> 61 #include <cctype> 62 #include <climits> 63 #include <cstddef> 64 #include <cstdint> 65 #include <deque> 66 #include <memory> 67 #include <sstream> 68 #include <string> 69 #include <tuple> 70 #include <utility> 71 #include <vector> 72 73 using namespace llvm; 74 75 extern cl::opt<unsigned> AsmMacroMaxNestingDepth; 76 77 namespace { 78 79 /// Helper types for tracking macro definitions. 80 typedef std::vector<AsmToken> MCAsmMacroArgument; 81 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments; 82 83 /// Helper class for storing information about an active macro 84 /// instantiation. 85 struct MacroInstantiation { 86 /// The location of the instantiation. 87 SMLoc InstantiationLoc; 88 89 /// The buffer where parsing should resume upon instantiation completion. 90 unsigned ExitBuffer; 91 92 /// The location where parsing should resume upon instantiation completion. 93 SMLoc ExitLoc; 94 95 /// The depth of TheCondStack at the start of the instantiation. 96 size_t CondStackDepth; 97 }; 98 99 struct ParseStatementInfo { 100 /// The parsed operands from the last parsed statement. 101 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands; 102 103 /// The opcode from the last parsed instruction. 104 unsigned Opcode = ~0U; 105 106 /// Was there an error parsing the inline assembly? 107 bool ParseError = false; 108 109 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr; 110 111 ParseStatementInfo() = delete; 112 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites) 113 : AsmRewrites(rewrites) {} 114 }; 115 116 /// The concrete assembly parser instance. 117 // Note that this is a full MCAsmParser, not an MCAsmParserExtension! 118 // It's a peer of AsmParser, not of COFFAsmParser, WasmAsmParser, etc. 119 class MasmParser : public MCAsmParser { 120 private: 121 AsmLexer Lexer; 122 MCContext &Ctx; 123 MCStreamer &Out; 124 const MCAsmInfo &MAI; 125 SourceMgr &SrcMgr; 126 SourceMgr::DiagHandlerTy SavedDiagHandler; 127 void *SavedDiagContext; 128 std::unique_ptr<MCAsmParserExtension> PlatformParser; 129 130 /// This is the current buffer index we're lexing from as managed by the 131 /// SourceMgr object. 132 unsigned CurBuffer; 133 134 AsmCond TheCondState; 135 std::vector<AsmCond> TheCondStack; 136 137 /// maps directive names to handler methods in parser 138 /// extensions. Extensions register themselves in this map by calling 139 /// addDirectiveHandler. 140 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap; 141 142 /// maps assembly-time variable names to variables 143 struct Variable { 144 StringRef Name; 145 bool Redefinable = true; 146 bool IsText = false; 147 int64_t NumericValue = 0; 148 std::string TextValue; 149 }; 150 StringMap<Variable> Variables; 151 152 /// Stack of active macro instantiations. 153 std::vector<MacroInstantiation*> ActiveMacros; 154 155 /// List of bodies of anonymous macros. 156 std::deque<MCAsmMacro> MacroLikeBodies; 157 158 /// Boolean tracking whether macro substitution is enabled. 159 unsigned MacrosEnabledFlag : 1; 160 161 /// Keeps track of how many .macro's have been instantiated. 162 unsigned NumOfMacroInstantiations; 163 164 /// The values from the last parsed cpp hash file line comment if any. 165 struct CppHashInfoTy { 166 StringRef Filename; 167 int64_t LineNumber; 168 SMLoc Loc; 169 unsigned Buf; 170 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {} 171 }; 172 CppHashInfoTy CppHashInfo; 173 174 /// The filename from the first cpp hash file line comment, if any. 175 StringRef FirstCppHashFilename; 176 177 /// List of forward directional labels for diagnosis at the end. 178 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels; 179 180 /// AssemblerDialect. ~OU means unset value and use value provided by MAI. 181 /// Defaults to 1U, meaning Intel. 182 unsigned AssemblerDialect = 1U; 183 184 /// is Darwin compatibility enabled? 185 bool IsDarwin = false; 186 187 /// Are we parsing ms-style inline assembly? 188 bool ParsingInlineAsm = false; 189 190 /// Did we already inform the user about inconsistent MD5 usage? 191 bool ReportedInconsistentMD5 = false; 192 193 // Is alt macro mode enabled. 194 bool AltMacroMode = false; 195 196 public: 197 MasmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 198 const MCAsmInfo &MAI, unsigned CB); 199 MasmParser(const MasmParser &) = delete; 200 MasmParser &operator=(const MasmParser &) = delete; 201 ~MasmParser() override; 202 203 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; 204 205 void addDirectiveHandler(StringRef Directive, 206 ExtensionDirectiveHandler Handler) override { 207 ExtensionDirectiveMap[Directive] = Handler; 208 if (DirectiveKindMap.find(Directive) == DirectiveKindMap.end()) { 209 DirectiveKindMap[Directive] = DK_HANDLER_DIRECTIVE; 210 } 211 } 212 213 void addAliasForDirective(StringRef Directive, StringRef Alias) override { 214 DirectiveKindMap[Directive] = DirectiveKindMap[Alias]; 215 } 216 217 /// @name MCAsmParser Interface 218 /// { 219 220 SourceMgr &getSourceManager() override { return SrcMgr; } 221 MCAsmLexer &getLexer() override { return Lexer; } 222 MCContext &getContext() override { return Ctx; } 223 MCStreamer &getStreamer() override { return Out; } 224 225 CodeViewContext &getCVContext() { return Ctx.getCVContext(); } 226 227 unsigned getAssemblerDialect() override { 228 if (AssemblerDialect == ~0U) 229 return MAI.getAssemblerDialect(); 230 else 231 return AssemblerDialect; 232 } 233 void setAssemblerDialect(unsigned i) override { 234 AssemblerDialect = i; 235 } 236 237 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override; 238 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override; 239 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override; 240 241 const AsmToken &Lex() override; 242 243 void setParsingInlineAsm(bool V) override { 244 ParsingInlineAsm = V; 245 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and 246 // hex integer literals. 247 Lexer.setLexMasmIntegers(V); 248 } 249 bool isParsingInlineAsm() override { return ParsingInlineAsm; } 250 251 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, 252 unsigned &NumOutputs, unsigned &NumInputs, 253 SmallVectorImpl<std::pair<void *,bool>> &OpDecls, 254 SmallVectorImpl<std::string> &Constraints, 255 SmallVectorImpl<std::string> &Clobbers, 256 const MCInstrInfo *MII, const MCInstPrinter *IP, 257 MCAsmParserSemaCallback &SI) override; 258 259 bool parseExpression(const MCExpr *&Res); 260 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 261 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; 262 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 263 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 264 SMLoc &EndLoc) override; 265 bool parseAbsoluteExpression(int64_t &Res) override; 266 267 /// Parse a floating point expression using the float \p Semantics 268 /// and set \p Res to the value. 269 bool parseRealValue(const fltSemantics &Semantics, APInt &Res); 270 271 /// Parse an identifier or string (as a quoted identifier) 272 /// and set \p Res to the identifier contents. 273 bool parseIdentifier(StringRef &Res) override; 274 void eatToEndOfStatement() override; 275 276 bool checkForValidSection() override; 277 278 /// } 279 280 private: 281 bool parseStatement(ParseStatementInfo &Info, 282 MCAsmParserSemaCallback *SI); 283 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites); 284 bool parseCppHashLineFilenameComment(SMLoc L); 285 286 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, 287 ArrayRef<MCAsmMacroParameter> Parameters); 288 bool expandMacro(raw_svector_ostream &OS, StringRef Body, 289 ArrayRef<MCAsmMacroParameter> Parameters, 290 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable, 291 SMLoc L); 292 293 /// Are macros enabled in the parser? 294 bool areMacrosEnabled() {return MacrosEnabledFlag;} 295 296 /// Control a flag in the parser that enables or disables macros. 297 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;} 298 299 /// Are we inside a macro instantiation? 300 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} 301 302 /// Handle entry to macro instantiation. 303 /// 304 /// \param M The macro. 305 /// \param NameLoc Instantiation location. 306 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); 307 308 /// Handle exit from macro instantiation. 309 void handleMacroExit(); 310 311 /// Extract AsmTokens for a macro argument. 312 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); 313 314 /// Parse all macro arguments for a given macro. 315 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); 316 317 void printMacroInstantiations(); 318 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, 319 SMRange Range = None) const { 320 ArrayRef<SMRange> Ranges(Range); 321 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); 322 } 323 static void DiagHandler(const SMDiagnostic &Diag, void *Context); 324 325 /// Should we emit DWARF describing this assembler source? (Returns false if 326 /// the source has .file directives, which means we don't want to generate 327 /// info describing the assembler source itself.) 328 bool enabledGenDwarfForAssembly(); 329 330 /// Enter the specified file. This returns true on failure. 331 bool enterIncludeFile(const std::string &Filename); 332 333 /// Process the specified file for the .incbin directive. 334 /// This returns true on failure. 335 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0, 336 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc()); 337 338 /// Reset the current lexer position to that given by \p Loc. The 339 /// current token is not set; clients should ensure Lex() is called 340 /// subsequently. 341 /// 342 /// \param InBuffer If not 0, should be the known buffer id that contains the 343 /// location. 344 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); 345 346 /// Parse up to the end of statement and a return the contents from the 347 /// current token until the end of the statement; the current token on exit 348 /// will be either the EndOfStatement or EOF. 349 StringRef parseStringToEndOfStatement() override; 350 351 /// Parse until the end of a statement or a comma is encountered, 352 /// return the contents from the current token up to the end or comma. 353 StringRef parseStringToComma(); 354 355 bool parseTextItem(std::string &Data); 356 357 unsigned getBinOpPrecedence(AsmToken::TokenKind K, 358 MCBinaryExpr::Opcode &Kind); 359 360 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); 361 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); 362 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); 363 364 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); 365 366 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName); 367 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName); 368 369 // Generic (target and platform independent) directive parsing. 370 enum DirectiveKind { 371 DK_NO_DIRECTIVE, // Placeholder 372 DK_HANDLER_DIRECTIVE, 373 DK_ASSIGN, 374 DK_EQU, 375 DK_TEXTEQU, 376 DK_ASCII, 377 DK_ASCIZ, 378 DK_STRING, 379 DK_BYTE, 380 DK_SBYTE, 381 DK_WORD, 382 DK_SWORD, 383 DK_DWORD, 384 DK_SDWORD, 385 DK_FWORD, 386 DK_QWORD, 387 DK_SQWORD, 388 DK_DB, 389 DK_DD, 390 DK_DQ, 391 DK_DW, 392 DK_REAL4, 393 DK_REAL8, 394 DK_ALIGN, 395 DK_ORG, 396 DK_ENDR, 397 DK_EXTERN, 398 DK_PUBLIC, 399 DK_COMM, 400 DK_COMMENT, 401 DK_INCLUDE, 402 DK_REPT, 403 DK_IRP, 404 DK_IRPC, 405 DK_IF, 406 DK_IFE, 407 DK_IFB, 408 DK_IFNB, 409 DK_IFDEF, 410 DK_IFNDEF, 411 DK_IFDIF, 412 DK_IFDIFI, 413 DK_IFIDN, 414 DK_IFIDNI, 415 DK_ELSEIF, 416 DK_ELSEIFE, 417 DK_ELSEIFB, 418 DK_ELSEIFNB, 419 DK_ELSEIFDEF, 420 DK_ELSEIFNDEF, 421 DK_ELSEIFDIF, 422 DK_ELSEIFDIFI, 423 DK_ELSEIFIDN, 424 DK_ELSEIFIDNI, 425 DK_ELSE, 426 DK_ENDIF, 427 DK_FILE, 428 DK_LINE, 429 DK_LOC, 430 DK_STABS, 431 DK_CV_FILE, 432 DK_CV_FUNC_ID, 433 DK_CV_INLINE_SITE_ID, 434 DK_CV_LOC, 435 DK_CV_LINETABLE, 436 DK_CV_INLINE_LINETABLE, 437 DK_CV_DEF_RANGE, 438 DK_CV_STRINGTABLE, 439 DK_CV_STRING, 440 DK_CV_FILECHECKSUMS, 441 DK_CV_FILECHECKSUM_OFFSET, 442 DK_CV_FPO_DATA, 443 DK_CFI_SECTIONS, 444 DK_CFI_STARTPROC, 445 DK_CFI_ENDPROC, 446 DK_CFI_DEF_CFA, 447 DK_CFI_DEF_CFA_OFFSET, 448 DK_CFI_ADJUST_CFA_OFFSET, 449 DK_CFI_DEF_CFA_REGISTER, 450 DK_CFI_OFFSET, 451 DK_CFI_REL_OFFSET, 452 DK_CFI_PERSONALITY, 453 DK_CFI_LSDA, 454 DK_CFI_REMEMBER_STATE, 455 DK_CFI_RESTORE_STATE, 456 DK_CFI_SAME_VALUE, 457 DK_CFI_RESTORE, 458 DK_CFI_ESCAPE, 459 DK_CFI_RETURN_COLUMN, 460 DK_CFI_SIGNAL_FRAME, 461 DK_CFI_UNDEFINED, 462 DK_CFI_REGISTER, 463 DK_CFI_WINDOW_SAVE, 464 DK_CFI_B_KEY_FRAME, 465 DK_ALTMACRO, 466 DK_NOALTMACRO, 467 DK_MACRO, 468 DK_EXITM, 469 DK_ENDM, 470 DK_PURGEM, 471 DK_ERR, 472 DK_ERRB, 473 DK_ERRNB, 474 DK_ERRDEF, 475 DK_ERRNDEF, 476 DK_ERRDIF, 477 DK_ERRDIFI, 478 DK_ERRIDN, 479 DK_ERRIDNI, 480 DK_ERRE, 481 DK_ERRNZ, 482 DK_ECHO, 483 DK_END 484 }; 485 486 /// Maps directive name --> DirectiveKind enum, for 487 /// directives parsed by this class. 488 StringMap<DirectiveKind> DirectiveKindMap; 489 490 // Codeview def_range type parsing. 491 enum CVDefRangeType { 492 CVDR_DEFRANGE = 0, // Placeholder 493 CVDR_DEFRANGE_REGISTER, 494 CVDR_DEFRANGE_FRAMEPOINTER_REL, 495 CVDR_DEFRANGE_SUBFIELD_REGISTER, 496 CVDR_DEFRANGE_REGISTER_REL 497 }; 498 499 /// Maps Codeview def_range types --> CVDefRangeType enum, for 500 /// Codeview def_range types parsed by this class. 501 StringMap<CVDefRangeType> CVDefRangeTypeMap; 502 503 // ".ascii", ".asciz", ".string" 504 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); 505 bool parseDirectiveValue(StringRef IDVal, 506 unsigned Size); // "byte", "word", ... 507 bool parseDirectiveRealValue(StringRef IDVal, 508 const fltSemantics &); // "real4", ... 509 510 // "=", "equ", "textequ" 511 bool parseDirectiveEquate(StringRef IDVal, StringRef Name, 512 DirectiveKind DirKind); 513 514 bool parseDirectiveOrg(); // ".org" 515 bool parseDirectiveAlign(); // "align" 516 517 // ".file", ".line", ".loc", ".stabs" 518 bool parseDirectiveFile(SMLoc DirectiveLoc); 519 bool parseDirectiveLine(); 520 bool parseDirectiveLoc(); 521 bool parseDirectiveStabs(); 522 523 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable", 524 // ".cv_inline_linetable", ".cv_def_range", ".cv_string" 525 bool parseDirectiveCVFile(); 526 bool parseDirectiveCVFuncId(); 527 bool parseDirectiveCVInlineSiteId(); 528 bool parseDirectiveCVLoc(); 529 bool parseDirectiveCVLinetable(); 530 bool parseDirectiveCVInlineLinetable(); 531 bool parseDirectiveCVDefRange(); 532 bool parseDirectiveCVString(); 533 bool parseDirectiveCVStringTable(); 534 bool parseDirectiveCVFileChecksums(); 535 bool parseDirectiveCVFileChecksumOffset(); 536 bool parseDirectiveCVFPOData(); 537 538 // .cfi directives 539 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); 540 bool parseDirectiveCFIWindowSave(); 541 bool parseDirectiveCFISections(); 542 bool parseDirectiveCFIStartProc(); 543 bool parseDirectiveCFIEndProc(); 544 bool parseDirectiveCFIDefCfaOffset(); 545 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); 546 bool parseDirectiveCFIAdjustCfaOffset(); 547 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); 548 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); 549 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); 550 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); 551 bool parseDirectiveCFIRememberState(); 552 bool parseDirectiveCFIRestoreState(); 553 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); 554 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); 555 bool parseDirectiveCFIEscape(); 556 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc); 557 bool parseDirectiveCFISignalFrame(); 558 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); 559 560 // macro directives 561 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); 562 bool parseDirectiveExitMacro(StringRef Directive); 563 bool parseDirectiveEndMacro(StringRef Directive); 564 bool parseDirectiveMacro(SMLoc DirectiveLoc); 565 bool parseDirectiveMacrosOnOff(StringRef Directive); 566 // alternate macro mode directives 567 bool parseDirectiveAltmacro(StringRef Directive); 568 569 /// Parse a directive like ".globl" which 570 /// accepts a single symbol (which should be a label or an external). 571 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); 572 573 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" 574 575 bool parseDirectiveComment(SMLoc DirectiveLoc); // "comment" 576 577 bool parseDirectiveInclude(); // "include" 578 579 // "if" or "ife" 580 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 581 // "ifb" or "ifnb", depending on ExpectBlank. 582 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); 583 // "ifidn", "ifdif", "ifidni", or "ifdifi", depending on ExpectEqual and 584 // CaseInsensitive. 585 bool parseDirectiveIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 586 bool CaseInsensitive); 587 // "ifdef" or "ifndef", depending on expect_defined 588 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); 589 // "elseif" or "elseife" 590 bool parseDirectiveElseIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 591 // "elseifb" or "elseifnb", depending on ExpectBlank. 592 bool parseDirectiveElseIfb(SMLoc DirectiveLoc, bool ExpectBlank); 593 // ".elseifdef" or ".elseifndef", depending on expect_defined 594 bool parseDirectiveElseIfdef(SMLoc DirectiveLoc, bool expect_defined); 595 // "elseifidn", "elseifdif", "elseifidni", or "elseifdifi", depending on 596 // ExpectEqual and CaseInsensitive. 597 bool parseDirectiveElseIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 598 bool CaseInsensitive); 599 bool parseDirectiveElse(SMLoc DirectiveLoc); // "else" 600 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // "endif" 601 bool parseEscapedString(std::string &Data) override; 602 bool parseAngleBracketString(std::string &Data) override; 603 604 // Macro-like directives 605 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); 606 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 607 raw_svector_ostream &OS); 608 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); 609 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" 610 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" 611 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" 612 613 // "_emit" or "__emit" 614 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, 615 size_t Len); 616 617 // "align" 618 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); 619 620 // "end" 621 bool parseDirectiveEnd(SMLoc DirectiveLoc); 622 623 // ".err" 624 bool parseDirectiveError(SMLoc DirectiveLoc); 625 // ".errb" or ".errnb", depending on ExpectBlank. 626 bool parseDirectiveErrorIfb(SMLoc DirectiveLoc, bool ExpectBlank); 627 // ".errdef" or ".errndef", depending on ExpectBlank. 628 bool parseDirectiveErrorIfdef(SMLoc DirectiveLoc, bool ExpectDefined); 629 // ".erridn", ".errdif", ".erridni", or ".errdifi", depending on ExpectEqual 630 // and CaseInsensitive. 631 bool parseDirectiveErrorIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 632 bool CaseInsensitive); 633 // ".erre" or ".errnz", depending on ExpectZero. 634 bool parseDirectiveErrorIfe(SMLoc DirectiveLoc, bool ExpectZero); 635 636 // "echo" 637 bool parseDirectiveEcho(); 638 639 void initializeDirectiveKindMap(); 640 void initializeCVDefRangeTypeMap(); 641 }; 642 643 } // end anonymous namespace 644 645 namespace llvm { 646 647 extern MCAsmParserExtension *createCOFFMasmParser(); 648 649 } // end namespace llvm 650 651 enum { DEFAULT_ADDRSPACE = 0 }; 652 653 MasmParser::MasmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 654 const MCAsmInfo &MAI, unsigned CB = 0) 655 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), 656 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) { 657 HadError = false; 658 // Save the old handler. 659 SavedDiagHandler = SrcMgr.getDiagHandler(); 660 SavedDiagContext = SrcMgr.getDiagContext(); 661 // Set our own handler which calls the saved handler. 662 SrcMgr.setDiagHandler(DiagHandler, this); 663 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 664 665 // Initialize the platform / file format parser. 666 switch (Ctx.getObjectFileInfo()->getObjectFileType()) { 667 case MCObjectFileInfo::IsCOFF: 668 PlatformParser.reset(createCOFFMasmParser()); 669 break; 670 default: 671 report_fatal_error("llvm-ml currently supports only COFF output."); 672 break; 673 } 674 675 initializeDirectiveKindMap(); 676 PlatformParser->Initialize(*this); 677 initializeCVDefRangeTypeMap(); 678 679 NumOfMacroInstantiations = 0; 680 } 681 682 MasmParser::~MasmParser() { 683 assert((HadError || ActiveMacros.empty()) && 684 "Unexpected active macro instantiation!"); 685 686 // Restore the saved diagnostics handler and context for use during 687 // finalization. 688 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext); 689 } 690 691 void MasmParser::printMacroInstantiations() { 692 // Print the active macro instantiation stack. 693 for (std::vector<MacroInstantiation *>::const_reverse_iterator 694 it = ActiveMacros.rbegin(), 695 ie = ActiveMacros.rend(); 696 it != ie; ++it) 697 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, 698 "while in macro instantiation"); 699 } 700 701 void MasmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) { 702 printPendingErrors(); 703 printMessage(L, SourceMgr::DK_Note, Msg, Range); 704 printMacroInstantiations(); 705 } 706 707 bool MasmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) { 708 if (getTargetParser().getTargetOptions().MCNoWarn) 709 return false; 710 if (getTargetParser().getTargetOptions().MCFatalWarnings) 711 return Error(L, Msg, Range); 712 printMessage(L, SourceMgr::DK_Warning, Msg, Range); 713 printMacroInstantiations(); 714 return false; 715 } 716 717 bool MasmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) { 718 HadError = true; 719 printMessage(L, SourceMgr::DK_Error, Msg, Range); 720 printMacroInstantiations(); 721 return true; 722 } 723 724 bool MasmParser::enterIncludeFile(const std::string &Filename) { 725 std::string IncludedFile; 726 unsigned NewBuf = 727 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 728 if (!NewBuf) 729 return true; 730 731 CurBuffer = NewBuf; 732 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 733 return false; 734 } 735 736 /// Process the specified .incbin file by searching for it in the include paths 737 /// then just emitting the byte contents of the file to the streamer. This 738 /// returns true on failure. 739 bool MasmParser::processIncbinFile(const std::string &Filename, int64_t Skip, 740 const MCExpr *Count, SMLoc Loc) { 741 std::string IncludedFile; 742 unsigned NewBuf = 743 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 744 if (!NewBuf) 745 return true; 746 747 // Pick up the bytes from the file and emit them. 748 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(); 749 Bytes = Bytes.drop_front(Skip); 750 if (Count) { 751 int64_t Res; 752 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr())) 753 return Error(Loc, "expected absolute expression"); 754 if (Res < 0) 755 return Warning(Loc, "negative count has no effect"); 756 Bytes = Bytes.take_front(Res); 757 } 758 getStreamer().emitBytes(Bytes); 759 return false; 760 } 761 762 void MasmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { 763 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); 764 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), 765 Loc.getPointer()); 766 } 767 768 const AsmToken &MasmParser::Lex() { 769 if (Lexer.getTok().is(AsmToken::Error)) 770 Error(Lexer.getErrLoc(), Lexer.getErr()); 771 772 // if it's a end of statement with a comment in it 773 if (getTok().is(AsmToken::EndOfStatement)) { 774 // if this is a line comment output it. 775 if (!getTok().getString().empty() && getTok().getString().front() != '\n' && 776 getTok().getString().front() != '\r' && MAI.preserveAsmComments()) 777 Out.addExplicitComment(Twine(getTok().getString())); 778 } 779 780 const AsmToken *tok = &Lexer.Lex(); 781 782 while (tok->is(AsmToken::Identifier)) { 783 auto it = Variables.find(tok->getIdentifier()); 784 if (it != Variables.end() && it->second.IsText) { 785 std::unique_ptr<MemoryBuffer> Instantiation = 786 MemoryBuffer::getMemBufferCopy(it->second.TextValue, 787 "<instantiation>"); 788 789 // Jump to the macro instantiation and prime the lexer. 790 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), 791 getTok().getEndLoc()); 792 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), nullptr, 793 /*EndStatementAtEOF=*/false); 794 tok = &Lexer.Lex(); 795 } else { 796 break; 797 } 798 } 799 800 // Parse comments here to be deferred until end of next statement. 801 while (tok->is(AsmToken::Comment)) { 802 if (MAI.preserveAsmComments()) 803 Out.addExplicitComment(Twine(tok->getString())); 804 tok = &Lexer.Lex(); 805 } 806 807 if (tok->is(AsmToken::Eof)) { 808 // If this is the end of an included file, pop the parent file off the 809 // include stack. 810 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); 811 if (ParentIncludeLoc != SMLoc()) { 812 jumpToLoc(ParentIncludeLoc); 813 return Lex(); 814 } 815 } 816 817 return *tok; 818 } 819 820 bool MasmParser::enabledGenDwarfForAssembly() { 821 // Check whether the user specified -g. 822 if (!getContext().getGenDwarfForAssembly()) 823 return false; 824 // If we haven't encountered any .file directives (which would imply that 825 // the assembler source was produced with debug info already) then emit one 826 // describing the assembler source file itself. 827 if (getContext().getGenDwarfFileNumber() == 0) { 828 // Use the first #line directive for this, if any. It's preprocessed, so 829 // there is no checksum, and of course no source directive. 830 if (!FirstCppHashFilename.empty()) 831 getContext().setMCLineTableRootFile(/*CUID=*/0, 832 getContext().getCompilationDir(), 833 FirstCppHashFilename, 834 /*Cksum=*/None, /*Source=*/None); 835 const MCDwarfFile &RootFile = 836 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile(); 837 getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective( 838 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name, 839 RootFile.Checksum, RootFile.Source)); 840 } 841 return true; 842 } 843 844 bool MasmParser::Run(bool NoInitialTextSection, bool NoFinalize) { 845 // Create the initial section, if requested. 846 if (!NoInitialTextSection) 847 Out.InitSections(false); 848 849 // Prime the lexer. 850 Lex(); 851 852 HadError = false; 853 AsmCond StartingCondState = TheCondState; 854 SmallVector<AsmRewrite, 4> AsmStrRewrites; 855 856 // If we are generating dwarf for assembly source files save the initial text 857 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't 858 // emitting any actual debug info yet and haven't had a chance to parse any 859 // embedded .file directives.) 860 if (getContext().getGenDwarfForAssembly()) { 861 MCSection *Sec = getStreamer().getCurrentSectionOnly(); 862 if (!Sec->getBeginSymbol()) { 863 MCSymbol *SectionStartSym = getContext().createTempSymbol(); 864 getStreamer().emitLabel(SectionStartSym); 865 Sec->setBeginSymbol(SectionStartSym); 866 } 867 bool InsertResult = getContext().addGenDwarfSection(Sec); 868 assert(InsertResult && ".text section should not have debug info yet"); 869 (void)InsertResult; 870 } 871 872 // While we have input, parse each statement. 873 while (Lexer.isNot(AsmToken::Eof)) { 874 ParseStatementInfo Info(&AsmStrRewrites); 875 bool Parsed = parseStatement(Info, nullptr); 876 877 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error 878 // for printing ErrMsg via Lex() only if no (presumably better) parser error 879 // exists. 880 if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) { 881 Lex(); 882 } 883 884 // parseStatement returned true so may need to emit an error. 885 printPendingErrors(); 886 887 // Skipping to the next line if needed. 888 if (Parsed && !getLexer().isAtStartOfStatement()) 889 eatToEndOfStatement(); 890 } 891 892 getTargetParser().onEndOfFile(); 893 printPendingErrors(); 894 895 // All errors should have been emitted. 896 assert(!hasPendingError() && "unexpected error from parseStatement"); 897 898 getTargetParser().flushPendingInstructions(getStreamer()); 899 900 if (TheCondState.TheCond != StartingCondState.TheCond || 901 TheCondState.Ignore != StartingCondState.Ignore) 902 printError(getTok().getLoc(), "unmatched .ifs or .elses"); 903 // Check to see there are no empty DwarfFile slots. 904 const auto &LineTables = getContext().getMCDwarfLineTables(); 905 if (!LineTables.empty()) { 906 unsigned Index = 0; 907 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { 908 if (File.Name.empty() && Index != 0) 909 printError(getTok().getLoc(), "unassigned file number: " + 910 Twine(Index) + 911 " for .file directives"); 912 ++Index; 913 } 914 } 915 916 // Check to see that all assembler local symbols were actually defined. 917 // Targets that don't do subsections via symbols may not want this, though, 918 // so conservatively exclude them. Only do this if we're finalizing, though, 919 // as otherwise we won't necessarilly have seen everything yet. 920 if (!NoFinalize) { 921 if (MAI.hasSubsectionsViaSymbols()) { 922 for (const auto &TableEntry : getContext().getSymbols()) { 923 MCSymbol *Sym = TableEntry.getValue(); 924 // Variable symbols may not be marked as defined, so check those 925 // explicitly. If we know it's a variable, we have a definition for 926 // the purposes of this check. 927 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) 928 // FIXME: We would really like to refer back to where the symbol was 929 // first referenced for a source location. We need to add something 930 // to track that. Currently, we just point to the end of the file. 931 printError(getTok().getLoc(), "assembler local symbol '" + 932 Sym->getName() + "' not defined"); 933 } 934 } 935 936 // Temporary symbols like the ones for directional jumps don't go in the 937 // symbol table. They also need to be diagnosed in all (final) cases. 938 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) { 939 if (std::get<2>(LocSym)->isUndefined()) { 940 // Reset the state of any "# line file" directives we've seen to the 941 // context as it was at the diagnostic site. 942 CppHashInfo = std::get<1>(LocSym); 943 printError(std::get<0>(LocSym), "directional label undefined"); 944 } 945 } 946 } 947 948 // Finalize the output stream if there are no errors and if the client wants 949 // us to. 950 if (!HadError && !NoFinalize) 951 Out.Finish(); 952 953 return HadError || getContext().hadError(); 954 } 955 956 bool MasmParser::checkForValidSection() { 957 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) { 958 Out.InitSections(false); 959 return Error(getTok().getLoc(), 960 "expected section directive before assembly directive"); 961 } 962 return false; 963 } 964 965 /// Throw away the rest of the line for testing purposes. 966 void MasmParser::eatToEndOfStatement() { 967 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 968 Lexer.Lex(); 969 970 // Eat EOL. 971 if (Lexer.is(AsmToken::EndOfStatement)) 972 Lexer.Lex(); 973 } 974 975 StringRef MasmParser::parseStringToEndOfStatement() { 976 const char *Start = getTok().getLoc().getPointer(); 977 978 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 979 Lexer.Lex(); 980 981 const char *End = getTok().getLoc().getPointer(); 982 return StringRef(Start, End - Start); 983 } 984 985 StringRef MasmParser::parseStringToComma() { 986 const char *Start = getTok().getLoc().getPointer(); 987 988 while (Lexer.isNot(AsmToken::EndOfStatement) && 989 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof)) 990 Lexer.Lex(); 991 992 const char *End = getTok().getLoc().getPointer(); 993 return StringRef(Start, End - Start); 994 } 995 996 /// Parse a paren expression and return it. 997 /// NOTE: This assumes the leading '(' has already been consumed. 998 /// 999 /// parenexpr ::= expr) 1000 /// 1001 bool MasmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1002 if (parseExpression(Res)) 1003 return true; 1004 if (Lexer.isNot(AsmToken::RParen)) 1005 return TokError("expected ')' in parentheses expression"); 1006 EndLoc = Lexer.getTok().getEndLoc(); 1007 Lex(); 1008 return false; 1009 } 1010 1011 /// Parse a bracket expression and return it. 1012 /// NOTE: This assumes the leading '[' has already been consumed. 1013 /// 1014 /// bracketexpr ::= expr] 1015 /// 1016 bool MasmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1017 if (parseExpression(Res)) 1018 return true; 1019 EndLoc = getTok().getEndLoc(); 1020 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression")) 1021 return true; 1022 return false; 1023 } 1024 1025 /// Parse a primary expression and return it. 1026 /// primaryexpr ::= (parenexpr 1027 /// primaryexpr ::= symbol 1028 /// primaryexpr ::= number 1029 /// primaryexpr ::= '.' 1030 /// primaryexpr ::= ~,+,- primaryexpr 1031 bool MasmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1032 SMLoc FirstTokenLoc = getLexer().getLoc(); 1033 AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); 1034 switch (FirstTokenKind) { 1035 default: 1036 return TokError("unknown token in expression"); 1037 // If we have an error assume that we've already handled it. 1038 case AsmToken::Error: 1039 return true; 1040 case AsmToken::Exclaim: 1041 Lex(); // Eat the operator. 1042 if (parsePrimaryExpr(Res, EndLoc)) 1043 return true; 1044 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc); 1045 return false; 1046 case AsmToken::Dollar: 1047 case AsmToken::At: 1048 case AsmToken::String: 1049 case AsmToken::Identifier: { 1050 StringRef Identifier; 1051 if (parseIdentifier(Identifier)) { 1052 // We may have failed but $ may be a valid token. 1053 if (getTok().is(AsmToken::Dollar)) { 1054 if (Lexer.getMAI().getDollarIsPC()) { 1055 Lex(); 1056 // This is a '$' reference, which references the current PC. Emit a 1057 // temporary label to the streamer and refer to it. 1058 MCSymbol *Sym = Ctx.createTempSymbol(); 1059 Out.emitLabel(Sym); 1060 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, 1061 getContext()); 1062 EndLoc = FirstTokenLoc; 1063 return false; 1064 } 1065 return Error(FirstTokenLoc, "invalid token in expression"); 1066 } 1067 } 1068 // Parse symbol variant 1069 std::pair<StringRef, StringRef> Split; 1070 if (!MAI.useParensForSymbolVariant()) { 1071 if (FirstTokenKind == AsmToken::String) { 1072 if (Lexer.is(AsmToken::At)) { 1073 Lex(); // eat @ 1074 SMLoc AtLoc = getLexer().getLoc(); 1075 StringRef VName; 1076 if (parseIdentifier(VName)) 1077 return Error(AtLoc, "expected symbol variant after '@'"); 1078 1079 Split = std::make_pair(Identifier, VName); 1080 } 1081 } else { 1082 Split = Identifier.split('@'); 1083 } 1084 } else if (Lexer.is(AsmToken::LParen)) { 1085 Lex(); // eat '('. 1086 StringRef VName; 1087 parseIdentifier(VName); 1088 // eat ')'. 1089 if (parseToken(AsmToken::RParen, 1090 "unexpected token in variant, expected ')'")) 1091 return true; 1092 Split = std::make_pair(Identifier, VName); 1093 } 1094 1095 EndLoc = SMLoc::getFromPointer(Identifier.end()); 1096 1097 // This is a symbol reference. 1098 StringRef SymbolName = Identifier; 1099 if (SymbolName.empty()) 1100 return Error(getLexer().getLoc(), "expected a symbol reference"); 1101 1102 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1103 1104 // Lookup the symbol variant if used. 1105 if (!Split.second.empty()) { 1106 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1107 if (Variant != MCSymbolRefExpr::VK_Invalid) { 1108 SymbolName = Split.first; 1109 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { 1110 Variant = MCSymbolRefExpr::VK_None; 1111 } else { 1112 return Error(SMLoc::getFromPointer(Split.second.begin()), 1113 "invalid variant '" + Split.second + "'"); 1114 } 1115 } 1116 1117 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName); 1118 if (!Sym) 1119 Sym = getContext().getOrCreateSymbol(SymbolName); 1120 1121 // If this is an absolute variable reference, substitute it now to preserve 1122 // semantics in the face of reassignment. 1123 if (Sym->isVariable()) { 1124 auto V = Sym->getVariableValue(/*SetUsed*/ false); 1125 bool DoInline = isa<MCConstantExpr>(V) && !Variant; 1126 if (auto TV = dyn_cast<MCTargetExpr>(V)) 1127 DoInline = TV->inlineAssignedExpr(); 1128 if (DoInline) { 1129 if (Variant) 1130 return Error(EndLoc, "unexpected modifier on variable reference"); 1131 Res = Sym->getVariableValue(/*SetUsed*/ false); 1132 return false; 1133 } 1134 } 1135 1136 // Otherwise create a symbol ref. 1137 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc); 1138 return false; 1139 } 1140 case AsmToken::BigNum: 1141 return TokError("literal value out of range for directive"); 1142 case AsmToken::Integer: { 1143 SMLoc Loc = getTok().getLoc(); 1144 int64_t IntVal = getTok().getIntVal(); 1145 Res = MCConstantExpr::create(IntVal, getContext()); 1146 EndLoc = Lexer.getTok().getEndLoc(); 1147 Lex(); // Eat token. 1148 // Look for 'b' or 'f' following an Integer as a directional label 1149 if (Lexer.getKind() == AsmToken::Identifier) { 1150 StringRef IDVal = getTok().getString(); 1151 // Lookup the symbol variant if used. 1152 std::pair<StringRef, StringRef> Split = IDVal.split('@'); 1153 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1154 if (Split.first.size() != IDVal.size()) { 1155 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1156 if (Variant == MCSymbolRefExpr::VK_Invalid) 1157 return TokError("invalid variant '" + Split.second + "'"); 1158 IDVal = Split.first; 1159 } 1160 if (IDVal == "f" || IDVal == "b") { 1161 MCSymbol *Sym = 1162 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b"); 1163 Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); 1164 if (IDVal == "b" && Sym->isUndefined()) 1165 return Error(Loc, "directional label undefined"); 1166 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym)); 1167 EndLoc = Lexer.getTok().getEndLoc(); 1168 Lex(); // Eat identifier. 1169 } 1170 } 1171 return false; 1172 } 1173 case AsmToken::Real: { 1174 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString()); 1175 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); 1176 Res = MCConstantExpr::create(IntVal, getContext()); 1177 EndLoc = Lexer.getTok().getEndLoc(); 1178 Lex(); // Eat token. 1179 return false; 1180 } 1181 case AsmToken::Dot: { 1182 // This is a '.' reference, which references the current PC. Emit a 1183 // temporary label to the streamer and refer to it. 1184 MCSymbol *Sym = Ctx.createTempSymbol(); 1185 Out.emitLabel(Sym); 1186 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); 1187 EndLoc = Lexer.getTok().getEndLoc(); 1188 Lex(); // Eat identifier. 1189 return false; 1190 } 1191 case AsmToken::LParen: 1192 Lex(); // Eat the '('. 1193 return parseParenExpr(Res, EndLoc); 1194 case AsmToken::LBrac: 1195 if (!PlatformParser->HasBracketExpressions()) 1196 return TokError("brackets expression not supported on this target"); 1197 Lex(); // Eat the '['. 1198 return parseBracketExpr(Res, EndLoc); 1199 case AsmToken::Minus: 1200 Lex(); // Eat the operator. 1201 if (parsePrimaryExpr(Res, EndLoc)) 1202 return true; 1203 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc); 1204 return false; 1205 case AsmToken::Plus: 1206 Lex(); // Eat the operator. 1207 if (parsePrimaryExpr(Res, EndLoc)) 1208 return true; 1209 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc); 1210 return false; 1211 case AsmToken::Tilde: 1212 Lex(); // Eat the operator. 1213 if (parsePrimaryExpr(Res, EndLoc)) 1214 return true; 1215 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc); 1216 return false; 1217 // MIPS unary expression operators. The lexer won't generate these tokens if 1218 // MCAsmInfo::HasMipsExpressions is false for the target. 1219 case AsmToken::PercentCall16: 1220 case AsmToken::PercentCall_Hi: 1221 case AsmToken::PercentCall_Lo: 1222 case AsmToken::PercentDtprel_Hi: 1223 case AsmToken::PercentDtprel_Lo: 1224 case AsmToken::PercentGot: 1225 case AsmToken::PercentGot_Disp: 1226 case AsmToken::PercentGot_Hi: 1227 case AsmToken::PercentGot_Lo: 1228 case AsmToken::PercentGot_Ofst: 1229 case AsmToken::PercentGot_Page: 1230 case AsmToken::PercentGottprel: 1231 case AsmToken::PercentGp_Rel: 1232 case AsmToken::PercentHi: 1233 case AsmToken::PercentHigher: 1234 case AsmToken::PercentHighest: 1235 case AsmToken::PercentLo: 1236 case AsmToken::PercentNeg: 1237 case AsmToken::PercentPcrel_Hi: 1238 case AsmToken::PercentPcrel_Lo: 1239 case AsmToken::PercentTlsgd: 1240 case AsmToken::PercentTlsldm: 1241 case AsmToken::PercentTprel_Hi: 1242 case AsmToken::PercentTprel_Lo: 1243 Lex(); // Eat the operator. 1244 if (Lexer.isNot(AsmToken::LParen)) 1245 return TokError("expected '(' after operator"); 1246 Lex(); // Eat the operator. 1247 if (parseExpression(Res, EndLoc)) 1248 return true; 1249 if (Lexer.isNot(AsmToken::RParen)) 1250 return TokError("expected ')'"); 1251 Lex(); // Eat the operator. 1252 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx); 1253 return !Res; 1254 } 1255 } 1256 1257 bool MasmParser::parseExpression(const MCExpr *&Res) { 1258 SMLoc EndLoc; 1259 return parseExpression(Res, EndLoc); 1260 } 1261 1262 /// This function checks if the next token is <string> type or arithmetic. 1263 /// string that begin with character '<' must end with character '>'. 1264 /// otherwise it is arithmetics. 1265 /// If the function returns a 'true' value, 1266 /// the End argument will be filled with the last location pointed to the '>' 1267 /// character. 1268 1269 /// There is a gap between the AltMacro's documentation and the single quote 1270 /// implementation. GCC does not fully support this feature and so we will not 1271 /// support it. 1272 /// TODO: Adding single quote as a string. 1273 static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) { 1274 assert((StrLoc.getPointer() != nullptr) && 1275 "Argument to the function cannot be a NULL value"); 1276 const char *CharPtr = StrLoc.getPointer(); 1277 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') && 1278 (*CharPtr != '\0')) { 1279 if (*CharPtr == '!') 1280 CharPtr++; 1281 CharPtr++; 1282 } 1283 if (*CharPtr == '>') { 1284 EndLoc = StrLoc.getFromPointer(CharPtr + 1); 1285 return true; 1286 } 1287 return false; 1288 } 1289 1290 /// creating a string without the escape characters '!'. 1291 static std::string angleBracketString(StringRef AltMacroStr) { 1292 std::string Res; 1293 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) { 1294 if (AltMacroStr[Pos] == '!') 1295 Pos++; 1296 Res += AltMacroStr[Pos]; 1297 } 1298 return Res; 1299 } 1300 1301 /// Parse an expression and return it. 1302 /// 1303 /// expr ::= expr &&,|| expr -> lowest. 1304 /// expr ::= expr |,^,&,! expr 1305 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr 1306 /// expr ::= expr <<,>> expr 1307 /// expr ::= expr +,- expr 1308 /// expr ::= expr *,/,% expr -> highest. 1309 /// expr ::= primaryexpr 1310 /// 1311 bool MasmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1312 // Parse the expression. 1313 Res = nullptr; 1314 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) || 1315 parseBinOpRHS(1, Res, EndLoc)) 1316 return true; 1317 1318 // Try to constant fold it up front, if possible. Do not exploit 1319 // assembler here. 1320 int64_t Value; 1321 if (Res->evaluateAsAbsolute(Value)) 1322 Res = MCConstantExpr::create(Value, getContext()); 1323 1324 return false; 1325 } 1326 1327 bool MasmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1328 Res = nullptr; 1329 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); 1330 } 1331 1332 bool MasmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 1333 SMLoc &EndLoc) { 1334 if (parseParenExpr(Res, EndLoc)) 1335 return true; 1336 1337 for (; ParenDepth > 0; --ParenDepth) { 1338 if (parseBinOpRHS(1, Res, EndLoc)) 1339 return true; 1340 1341 // We don't Lex() the last RParen. 1342 // This is the same behavior as parseParenExpression(). 1343 if (ParenDepth - 1 > 0) { 1344 EndLoc = getTok().getEndLoc(); 1345 if (parseToken(AsmToken::RParen, 1346 "expected ')' in parentheses expression")) 1347 return true; 1348 } 1349 } 1350 return false; 1351 } 1352 1353 bool MasmParser::parseAbsoluteExpression(int64_t &Res) { 1354 const MCExpr *Expr; 1355 1356 SMLoc StartLoc = Lexer.getLoc(); 1357 if (parseExpression(Expr)) 1358 return true; 1359 1360 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr())) 1361 return Error(StartLoc, "expected absolute expression"); 1362 1363 return false; 1364 } 1365 1366 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, 1367 MCBinaryExpr::Opcode &Kind, 1368 bool ShouldUseLogicalShr) { 1369 switch (K) { 1370 default: 1371 return 0; // not a binop. 1372 1373 // Lowest Precedence: &&, || 1374 case AsmToken::AmpAmp: 1375 Kind = MCBinaryExpr::LAnd; 1376 return 2; 1377 case AsmToken::PipePipe: 1378 Kind = MCBinaryExpr::LOr; 1379 return 1; 1380 1381 // Low Precedence: ==, !=, <>, <, <=, >, >= 1382 case AsmToken::EqualEqual: 1383 Kind = MCBinaryExpr::EQ; 1384 return 3; 1385 case AsmToken::ExclaimEqual: 1386 case AsmToken::LessGreater: 1387 Kind = MCBinaryExpr::NE; 1388 return 3; 1389 case AsmToken::Less: 1390 Kind = MCBinaryExpr::LT; 1391 return 3; 1392 case AsmToken::LessEqual: 1393 Kind = MCBinaryExpr::LTE; 1394 return 3; 1395 case AsmToken::Greater: 1396 Kind = MCBinaryExpr::GT; 1397 return 3; 1398 case AsmToken::GreaterEqual: 1399 Kind = MCBinaryExpr::GTE; 1400 return 3; 1401 1402 // Low Intermediate Precedence: +, - 1403 case AsmToken::Plus: 1404 Kind = MCBinaryExpr::Add; 1405 return 4; 1406 case AsmToken::Minus: 1407 Kind = MCBinaryExpr::Sub; 1408 return 4; 1409 1410 // High Intermediate Precedence: |, &, ^ 1411 // 1412 // FIXME: gas seems to support '!' as an infix operator? 1413 case AsmToken::Pipe: 1414 Kind = MCBinaryExpr::Or; 1415 return 5; 1416 case AsmToken::Caret: 1417 Kind = MCBinaryExpr::Xor; 1418 return 5; 1419 case AsmToken::Amp: 1420 Kind = MCBinaryExpr::And; 1421 return 5; 1422 1423 // Highest Precedence: *, /, %, <<, >> 1424 case AsmToken::Star: 1425 Kind = MCBinaryExpr::Mul; 1426 return 6; 1427 case AsmToken::Slash: 1428 Kind = MCBinaryExpr::Div; 1429 return 6; 1430 case AsmToken::Percent: 1431 Kind = MCBinaryExpr::Mod; 1432 return 6; 1433 case AsmToken::LessLess: 1434 Kind = MCBinaryExpr::Shl; 1435 return 6; 1436 case AsmToken::GreaterGreater: 1437 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1438 return 6; 1439 } 1440 } 1441 1442 unsigned MasmParser::getBinOpPrecedence(AsmToken::TokenKind K, 1443 MCBinaryExpr::Opcode &Kind) { 1444 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); 1445 return getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); 1446 } 1447 1448 /// Parse all binary operators with precedence >= 'Precedence'. 1449 /// Res contains the LHS of the expression on input. 1450 bool MasmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, 1451 SMLoc &EndLoc) { 1452 SMLoc StartLoc = Lexer.getLoc(); 1453 while (true) { 1454 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; 1455 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind); 1456 1457 // If the next token is lower precedence than we are allowed to eat, return 1458 // successfully with what we ate already. 1459 if (TokPrec < Precedence) 1460 return false; 1461 1462 Lex(); 1463 1464 // Eat the next primary expression. 1465 const MCExpr *RHS; 1466 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc)) 1467 return true; 1468 1469 // If BinOp binds less tightly with RHS than the operator after RHS, let 1470 // the pending operator take RHS as its LHS. 1471 MCBinaryExpr::Opcode Dummy; 1472 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); 1473 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) 1474 return true; 1475 1476 // Merge LHS and RHS according to operator. 1477 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc); 1478 } 1479 } 1480 1481 /// ParseStatement: 1482 /// ::= EndOfStatement 1483 /// ::= Label* Directive ...Operands... EndOfStatement 1484 /// ::= Label* Identifier OperandList* EndOfStatement 1485 bool MasmParser::parseStatement(ParseStatementInfo &Info, 1486 MCAsmParserSemaCallback *SI) { 1487 assert(!hasPendingError() && "parseStatement started with pending error"); 1488 // Eat initial spaces and comments 1489 while (Lexer.is(AsmToken::Space)) 1490 Lex(); 1491 if (Lexer.is(AsmToken::EndOfStatement)) { 1492 // if this is a line comment we can drop it safely 1493 if (getTok().getString().empty() || getTok().getString().front() == '\r' || 1494 getTok().getString().front() == '\n') 1495 Out.AddBlankLine(); 1496 Lex(); 1497 return false; 1498 } 1499 // Statements always start with an identifier, unless we're dealing with a 1500 // processor directive (.386, .686, etc.) that lexes as a real. 1501 AsmToken ID = getTok(); 1502 SMLoc IDLoc = ID.getLoc(); 1503 StringRef IDVal; 1504 int64_t LocalLabelVal = -1; 1505 if (Lexer.is(AsmToken::HashDirective)) 1506 return parseCppHashLineFilenameComment(IDLoc); 1507 // Allow an integer followed by a ':' as a directional local label. 1508 if (Lexer.is(AsmToken::Integer)) { 1509 LocalLabelVal = getTok().getIntVal(); 1510 if (LocalLabelVal < 0) { 1511 if (!TheCondState.Ignore) { 1512 Lex(); // always eat a token 1513 return Error(IDLoc, "unexpected token at start of statement"); 1514 } 1515 IDVal = ""; 1516 } else { 1517 IDVal = getTok().getString(); 1518 Lex(); // Consume the integer token to be used as an identifier token. 1519 if (Lexer.getKind() != AsmToken::Colon) { 1520 if (!TheCondState.Ignore) { 1521 Lex(); // always eat a token 1522 return Error(IDLoc, "unexpected token at start of statement"); 1523 } 1524 } 1525 } 1526 } else if (Lexer.is(AsmToken::Dot)) { 1527 // Treat '.' as a valid identifier in this context. 1528 Lex(); 1529 IDVal = "."; 1530 } else if (Lexer.is(AsmToken::LCurly)) { 1531 // Treat '{' as a valid identifier in this context. 1532 Lex(); 1533 IDVal = "{"; 1534 1535 } else if (Lexer.is(AsmToken::RCurly)) { 1536 // Treat '}' as a valid identifier in this context. 1537 Lex(); 1538 IDVal = "}"; 1539 } else if (Lexer.is(AsmToken::Star) && 1540 getTargetParser().starIsStartOfStatement()) { 1541 // Accept '*' as a valid start of statement. 1542 Lex(); 1543 IDVal = "*"; 1544 } else if (Lexer.is(AsmToken::Real)) { 1545 // Treat ".<number>" as a valid identifier in this context. 1546 IDVal = getTok().getString(); 1547 Lex(); // always eat a token 1548 if (!IDVal.startswith(".")) 1549 return Error(IDLoc, "unexpected token at start of statement"); 1550 } else if (parseIdentifier(IDVal)) { 1551 if (!TheCondState.Ignore) { 1552 Lex(); // always eat a token 1553 return Error(IDLoc, "unexpected token at start of statement"); 1554 } 1555 IDVal = ""; 1556 } 1557 1558 // Handle conditional assembly here before checking for skipping. We 1559 // have to do this so that .endif isn't skipped in a ".if 0" block for 1560 // example. 1561 StringMap<DirectiveKind>::const_iterator DirKindIt = 1562 DirectiveKindMap.find(IDVal.lower()); 1563 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) 1564 ? DK_NO_DIRECTIVE 1565 : DirKindIt->getValue(); 1566 switch (DirKind) { 1567 default: 1568 break; 1569 case DK_IF: 1570 case DK_IFE: 1571 return parseDirectiveIf(IDLoc, DirKind); 1572 case DK_IFB: 1573 return parseDirectiveIfb(IDLoc, true); 1574 case DK_IFNB: 1575 return parseDirectiveIfb(IDLoc, false); 1576 case DK_IFDEF: 1577 return parseDirectiveIfdef(IDLoc, true); 1578 case DK_IFNDEF: 1579 return parseDirectiveIfdef(IDLoc, false); 1580 case DK_IFDIF: 1581 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/false, 1582 /*CaseInsensitive=*/false); 1583 case DK_IFDIFI: 1584 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/false, 1585 /*CaseInsensitive=*/true); 1586 case DK_IFIDN: 1587 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/true, 1588 /*CaseInsensitive=*/false); 1589 case DK_IFIDNI: 1590 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/true, 1591 /*CaseInsensitive=*/true); 1592 case DK_ELSEIF: 1593 case DK_ELSEIFE: 1594 return parseDirectiveElseIf(IDLoc, DirKind); 1595 case DK_ELSEIFB: 1596 return parseDirectiveElseIfb(IDLoc, true); 1597 case DK_ELSEIFNB: 1598 return parseDirectiveElseIfb(IDLoc, false); 1599 case DK_ELSEIFDEF: 1600 return parseDirectiveElseIfdef(IDLoc, true); 1601 case DK_ELSEIFNDEF: 1602 return parseDirectiveElseIfdef(IDLoc, false); 1603 case DK_ELSEIFDIF: 1604 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/false, 1605 /*CaseInsensitive=*/false); 1606 case DK_ELSEIFDIFI: 1607 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/false, 1608 /*CaseInsensitive=*/true); 1609 case DK_ELSEIFIDN: 1610 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/true, 1611 /*CaseInsensitive=*/false); 1612 case DK_ELSEIFIDNI: 1613 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/true, 1614 /*CaseInsensitive=*/true); 1615 case DK_ELSE: 1616 return parseDirectiveElse(IDLoc); 1617 case DK_ENDIF: 1618 return parseDirectiveEndIf(IDLoc); 1619 } 1620 1621 // Ignore the statement if in the middle of inactive conditional 1622 // (e.g. ".if 0"). 1623 if (TheCondState.Ignore) { 1624 eatToEndOfStatement(); 1625 return false; 1626 } 1627 1628 // FIXME: Recurse on local labels? 1629 1630 // See what kind of statement we have. 1631 switch (Lexer.getKind()) { 1632 case AsmToken::Colon: { 1633 if (!getTargetParser().isLabel(ID)) 1634 break; 1635 if (checkForValidSection()) 1636 return true; 1637 1638 // identifier ':' -> Label. 1639 Lex(); 1640 1641 // Diagnose attempt to use '.' as a label. 1642 if (IDVal == ".") 1643 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); 1644 1645 // Diagnose attempt to use a variable as a label. 1646 // 1647 // FIXME: Diagnostics. Note the location of the definition as a label. 1648 // FIXME: This doesn't diagnose assignment to a symbol which has been 1649 // implicitly marked as external. 1650 MCSymbol *Sym; 1651 if (LocalLabelVal == -1) { 1652 if (ParsingInlineAsm && SI) { 1653 StringRef RewrittenLabel = 1654 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true); 1655 assert(!RewrittenLabel.empty() && 1656 "We should have an internal name here."); 1657 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(), 1658 RewrittenLabel); 1659 IDVal = RewrittenLabel; 1660 } 1661 Sym = getContext().getOrCreateSymbol(IDVal); 1662 } else 1663 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal); 1664 // End of Labels should be treated as end of line for lexing 1665 // purposes but that information is not available to the Lexer who 1666 // does not understand Labels. This may cause us to see a Hash 1667 // here instead of a preprocessor line comment. 1668 if (getTok().is(AsmToken::Hash)) { 1669 StringRef CommentStr = parseStringToEndOfStatement(); 1670 Lexer.Lex(); 1671 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr)); 1672 } 1673 1674 // Consume any end of statement token, if present, to avoid spurious 1675 // AddBlankLine calls(). 1676 if (getTok().is(AsmToken::EndOfStatement)) { 1677 Lex(); 1678 } 1679 1680 getTargetParser().doBeforeLabelEmit(Sym); 1681 1682 // Emit the label. 1683 if (!getTargetParser().isParsingInlineAsm()) 1684 Out.emitLabel(Sym, IDLoc); 1685 1686 // If we are generating dwarf for assembly source files then gather the 1687 // info to make a dwarf label entry for this label if needed. 1688 if (enabledGenDwarfForAssembly()) 1689 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), 1690 IDLoc); 1691 1692 getTargetParser().onLabelParsed(Sym); 1693 1694 return false; 1695 } 1696 1697 default: // Normal instruction or directive. 1698 break; 1699 } 1700 1701 // If macros are enabled, check to see if this is a macro instantiation. 1702 if (areMacrosEnabled()) 1703 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) { 1704 return handleMacroEntry(M, IDLoc); 1705 } 1706 1707 // Otherwise, we have a normal instruction or directive. 1708 1709 if (DirKind != DK_NO_DIRECTIVE) { 1710 // There are several entities interested in parsing directives: 1711 // 1712 // 1. Asm parser extensions. For example, platform-specific parsers 1713 // (like the ELF parser) register themselves as extensions. 1714 // 2. The target-specific assembly parser. Some directives are target 1715 // specific or may potentially behave differently on certain targets. 1716 // 3. The generic directive parser implemented by this class. These are 1717 // all the directives that behave in a target and platform independent 1718 // manner, or at least have a default behavior that's shared between 1719 // all targets and platforms. 1720 1721 getTargetParser().flushPendingInstructions(getStreamer()); 1722 1723 // First, check the extension directive map to see if any extension has 1724 // registered itself to parse this directive. 1725 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 1726 ExtensionDirectiveMap.lookup(IDVal.lower()); 1727 if (Handler.first) 1728 return (*Handler.second)(Handler.first, IDVal, IDLoc); 1729 1730 // Next, let the target-specific assembly parser try. 1731 SMLoc StartTokLoc = getTok().getLoc(); 1732 bool TPDirectiveReturn = 1733 ID.is(AsmToken::Identifier) && getTargetParser().ParseDirective(ID); 1734 1735 if (hasPendingError()) 1736 return true; 1737 // Currently the return value should be true if we are 1738 // uninterested but as this is at odds with the standard parsing 1739 // convention (return true = error) we have instances of a parsed 1740 // directive that fails returning true as an error. Catch these 1741 // cases as best as possible errors here. 1742 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc()) 1743 return true; 1744 // Return if we did some parsing or believe we succeeded. 1745 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc()) 1746 return false; 1747 1748 // Finally, if no one else is interested in this directive, it must be 1749 // generic and familiar to this class. 1750 switch (DirKind) { 1751 default: 1752 break; 1753 case DK_ASCII: 1754 return parseDirectiveAscii(IDVal, false); 1755 case DK_ASCIZ: 1756 case DK_STRING: 1757 return parseDirectiveAscii(IDVal, true); 1758 case DK_BYTE: 1759 case DK_SBYTE: 1760 case DK_DB: 1761 return parseDirectiveValue(IDVal, 1); 1762 case DK_WORD: 1763 case DK_SWORD: 1764 case DK_DW: 1765 return parseDirectiveValue(IDVal, 2); 1766 case DK_DWORD: 1767 case DK_SDWORD: 1768 case DK_DD: 1769 return parseDirectiveValue(IDVal, 4); 1770 case DK_FWORD: 1771 return parseDirectiveValue(IDVal, 6); 1772 case DK_QWORD: 1773 case DK_SQWORD: 1774 case DK_DQ: 1775 return parseDirectiveValue(IDVal, 8); 1776 case DK_REAL4: 1777 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle()); 1778 case DK_REAL8: 1779 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble()); 1780 case DK_ALIGN: 1781 return parseDirectiveAlign(); 1782 case DK_ORG: 1783 return parseDirectiveOrg(); 1784 case DK_EXTERN: 1785 eatToEndOfStatement(); // .extern is the default, ignore it. 1786 return false; 1787 case DK_PUBLIC: 1788 return parseDirectiveSymbolAttribute(MCSA_Global); 1789 case DK_COMM: 1790 return parseDirectiveComm(/*IsLocal=*/false); 1791 case DK_COMMENT: 1792 return parseDirectiveComment(IDLoc); 1793 case DK_INCLUDE: 1794 return parseDirectiveInclude(); 1795 case DK_REPT: 1796 return parseDirectiveRept(IDLoc, IDVal); 1797 case DK_IRP: 1798 return parseDirectiveIrp(IDLoc); 1799 case DK_IRPC: 1800 return parseDirectiveIrpc(IDLoc); 1801 case DK_ENDR: 1802 return parseDirectiveEndr(IDLoc); 1803 case DK_FILE: 1804 return parseDirectiveFile(IDLoc); 1805 case DK_LINE: 1806 return parseDirectiveLine(); 1807 case DK_LOC: 1808 return parseDirectiveLoc(); 1809 case DK_STABS: 1810 return parseDirectiveStabs(); 1811 case DK_CV_FILE: 1812 return parseDirectiveCVFile(); 1813 case DK_CV_FUNC_ID: 1814 return parseDirectiveCVFuncId(); 1815 case DK_CV_INLINE_SITE_ID: 1816 return parseDirectiveCVInlineSiteId(); 1817 case DK_CV_LOC: 1818 return parseDirectiveCVLoc(); 1819 case DK_CV_LINETABLE: 1820 return parseDirectiveCVLinetable(); 1821 case DK_CV_INLINE_LINETABLE: 1822 return parseDirectiveCVInlineLinetable(); 1823 case DK_CV_DEF_RANGE: 1824 return parseDirectiveCVDefRange(); 1825 case DK_CV_STRING: 1826 return parseDirectiveCVString(); 1827 case DK_CV_STRINGTABLE: 1828 return parseDirectiveCVStringTable(); 1829 case DK_CV_FILECHECKSUMS: 1830 return parseDirectiveCVFileChecksums(); 1831 case DK_CV_FILECHECKSUM_OFFSET: 1832 return parseDirectiveCVFileChecksumOffset(); 1833 case DK_CV_FPO_DATA: 1834 return parseDirectiveCVFPOData(); 1835 case DK_CFI_SECTIONS: 1836 return parseDirectiveCFISections(); 1837 case DK_CFI_STARTPROC: 1838 return parseDirectiveCFIStartProc(); 1839 case DK_CFI_ENDPROC: 1840 return parseDirectiveCFIEndProc(); 1841 case DK_CFI_DEF_CFA: 1842 return parseDirectiveCFIDefCfa(IDLoc); 1843 case DK_CFI_DEF_CFA_OFFSET: 1844 return parseDirectiveCFIDefCfaOffset(); 1845 case DK_CFI_ADJUST_CFA_OFFSET: 1846 return parseDirectiveCFIAdjustCfaOffset(); 1847 case DK_CFI_DEF_CFA_REGISTER: 1848 return parseDirectiveCFIDefCfaRegister(IDLoc); 1849 case DK_CFI_OFFSET: 1850 return parseDirectiveCFIOffset(IDLoc); 1851 case DK_CFI_REL_OFFSET: 1852 return parseDirectiveCFIRelOffset(IDLoc); 1853 case DK_CFI_PERSONALITY: 1854 return parseDirectiveCFIPersonalityOrLsda(true); 1855 case DK_CFI_LSDA: 1856 return parseDirectiveCFIPersonalityOrLsda(false); 1857 case DK_CFI_REMEMBER_STATE: 1858 return parseDirectiveCFIRememberState(); 1859 case DK_CFI_RESTORE_STATE: 1860 return parseDirectiveCFIRestoreState(); 1861 case DK_CFI_SAME_VALUE: 1862 return parseDirectiveCFISameValue(IDLoc); 1863 case DK_CFI_RESTORE: 1864 return parseDirectiveCFIRestore(IDLoc); 1865 case DK_CFI_ESCAPE: 1866 return parseDirectiveCFIEscape(); 1867 case DK_CFI_RETURN_COLUMN: 1868 return parseDirectiveCFIReturnColumn(IDLoc); 1869 case DK_CFI_SIGNAL_FRAME: 1870 return parseDirectiveCFISignalFrame(); 1871 case DK_CFI_UNDEFINED: 1872 return parseDirectiveCFIUndefined(IDLoc); 1873 case DK_CFI_REGISTER: 1874 return parseDirectiveCFIRegister(IDLoc); 1875 case DK_CFI_WINDOW_SAVE: 1876 return parseDirectiveCFIWindowSave(); 1877 case DK_MACRO: 1878 return parseDirectiveMacro(IDLoc); 1879 case DK_ALTMACRO: 1880 case DK_NOALTMACRO: 1881 return parseDirectiveAltmacro(IDVal); 1882 case DK_EXITM: 1883 return parseDirectiveExitMacro(IDVal); 1884 case DK_ENDM: 1885 return parseDirectiveEndMacro(IDVal); 1886 case DK_PURGEM: 1887 return parseDirectivePurgeMacro(IDLoc); 1888 case DK_END: 1889 return parseDirectiveEnd(IDLoc); 1890 case DK_ERR: 1891 return parseDirectiveError(IDLoc); 1892 case DK_ERRB: 1893 return parseDirectiveErrorIfb(IDLoc, true); 1894 case DK_ERRNB: 1895 return parseDirectiveErrorIfb(IDLoc, false); 1896 case DK_ERRDEF: 1897 return parseDirectiveErrorIfdef(IDLoc, true); 1898 case DK_ERRNDEF: 1899 return parseDirectiveErrorIfdef(IDLoc, false); 1900 case DK_ERRDIF: 1901 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/false, 1902 /*CaseInsensitive=*/false); 1903 case DK_ERRDIFI: 1904 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/false, 1905 /*CaseInsensitive=*/true); 1906 case DK_ERRIDN: 1907 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/true, 1908 /*CaseInsensitive=*/false); 1909 case DK_ERRIDNI: 1910 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/true, 1911 /*CaseInsensitive=*/true); 1912 case DK_ERRE: 1913 return parseDirectiveErrorIfe(IDLoc, true); 1914 case DK_ERRNZ: 1915 return parseDirectiveErrorIfe(IDLoc, false); 1916 case DK_ECHO: 1917 return parseDirectiveEcho(); 1918 } 1919 1920 return Error(IDLoc, "unknown directive"); 1921 } 1922 1923 // Non-conditional Microsoft directives sometimes follow their first argument. 1924 const AsmToken nextTok = getTok(); 1925 const StringRef nextVal = nextTok.getString(); 1926 const SMLoc nextLoc = nextTok.getLoc(); 1927 1928 // There are several entities interested in parsing infix directives: 1929 // 1930 // 1. Asm parser extensions. For example, platform-specific parsers 1931 // (like the ELF parser) register themselves as extensions. 1932 // 2. The generic directive parser implemented by this class. These are 1933 // all the directives that behave in a target and platform independent 1934 // manner, or at least have a default behavior that's shared between 1935 // all targets and platforms. 1936 1937 getTargetParser().flushPendingInstructions(getStreamer()); 1938 1939 // First, check the extension directive map to see if any extension has 1940 // registered itself to parse this directive. 1941 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 1942 ExtensionDirectiveMap.lookup(nextVal.lower()); 1943 if (Handler.first) { 1944 Lex(); 1945 Lexer.UnLex(ID); 1946 return (*Handler.second)(Handler.first, nextVal, nextLoc); 1947 } 1948 1949 // Finally, if no one else is interested in this directive, it must be 1950 // generic and familiar to this class. 1951 DirKindIt = DirectiveKindMap.find(nextVal.lower()); 1952 DirKind = (DirKindIt == DirectiveKindMap.end()) 1953 ? DK_NO_DIRECTIVE 1954 : DirKindIt->getValue(); 1955 switch (DirKind) { 1956 default: 1957 break; 1958 case DK_ASSIGN: 1959 case DK_EQU: 1960 case DK_TEXTEQU: 1961 Lex(); 1962 return parseDirectiveEquate(nextVal, IDVal, DirKind); 1963 } 1964 1965 // __asm _emit or __asm __emit 1966 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || 1967 IDVal == "_EMIT" || IDVal == "__EMIT")) 1968 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); 1969 1970 // __asm align 1971 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) 1972 return parseDirectiveMSAlign(IDLoc, Info); 1973 1974 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN")) 1975 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4); 1976 if (checkForValidSection()) 1977 return true; 1978 1979 // Canonicalize the opcode to lower case. 1980 std::string OpcodeStr = IDVal.lower(); 1981 ParseInstructionInfo IInfo(Info.AsmRewrites); 1982 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID, 1983 Info.ParsedOperands); 1984 Info.ParseError = ParseHadError; 1985 1986 // Dump the parsed representation, if requested. 1987 if (getShowParsedOperands()) { 1988 SmallString<256> Str; 1989 raw_svector_ostream OS(Str); 1990 OS << "parsed instruction: ["; 1991 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { 1992 if (i != 0) 1993 OS << ", "; 1994 Info.ParsedOperands[i]->print(OS); 1995 } 1996 OS << "]"; 1997 1998 printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); 1999 } 2000 2001 // Fail even if ParseInstruction erroneously returns false. 2002 if (hasPendingError() || ParseHadError) 2003 return true; 2004 2005 // If we are generating dwarf for the current section then generate a .loc 2006 // directive for the instruction. 2007 if (!ParseHadError && enabledGenDwarfForAssembly() && 2008 getContext().getGenDwarfSectionSyms().count( 2009 getStreamer().getCurrentSectionOnly())) { 2010 unsigned Line; 2011 if (ActiveMacros.empty()) 2012 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); 2013 else 2014 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc, 2015 ActiveMacros.front()->ExitBuffer); 2016 2017 // If we previously parsed a cpp hash file line comment then make sure the 2018 // current Dwarf File is for the CppHashFilename if not then emit the 2019 // Dwarf File table for it and adjust the line number for the .loc. 2020 if (!CppHashInfo.Filename.empty()) { 2021 unsigned FileNumber = getStreamer().emitDwarfFileDirective( 2022 0, StringRef(), CppHashInfo.Filename); 2023 getContext().setGenDwarfFileNumber(FileNumber); 2024 2025 unsigned CppHashLocLineNo = 2026 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf); 2027 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo); 2028 } 2029 2030 getStreamer().emitDwarfLocDirective( 2031 getContext().getGenDwarfFileNumber(), Line, 0, 2032 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, 2033 StringRef()); 2034 } 2035 2036 // If parsing succeeded, match the instruction. 2037 if (!ParseHadError) { 2038 uint64_t ErrorInfo; 2039 if (getTargetParser().MatchAndEmitInstruction( 2040 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo, 2041 getTargetParser().isParsingInlineAsm())) 2042 return true; 2043 } 2044 return false; 2045 } 2046 2047 // Parse and erase curly braces marking block start/end 2048 bool MasmParser::parseCurlyBlockScope( 2049 SmallVectorImpl<AsmRewrite> &AsmStrRewrites) { 2050 // Identify curly brace marking block start/end 2051 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly)) 2052 return false; 2053 2054 SMLoc StartLoc = Lexer.getLoc(); 2055 Lex(); // Eat the brace 2056 if (Lexer.is(AsmToken::EndOfStatement)) 2057 Lex(); // Eat EndOfStatement following the brace 2058 2059 // Erase the block start/end brace from the output asm string 2060 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() - 2061 StartLoc.getPointer()); 2062 return true; 2063 } 2064 2065 /// parseCppHashLineFilenameComment as this: 2066 /// ::= # number "filename" 2067 bool MasmParser::parseCppHashLineFilenameComment(SMLoc L) { 2068 Lex(); // Eat the hash token. 2069 // Lexer only ever emits HashDirective if it fully formed if it's 2070 // done the checking already so this is an internal error. 2071 assert(getTok().is(AsmToken::Integer) && 2072 "Lexing Cpp line comment: Expected Integer"); 2073 int64_t LineNumber = getTok().getIntVal(); 2074 Lex(); 2075 assert(getTok().is(AsmToken::String) && 2076 "Lexing Cpp line comment: Expected String"); 2077 StringRef Filename = getTok().getString(); 2078 Lex(); 2079 2080 // Get rid of the enclosing quotes. 2081 Filename = Filename.substr(1, Filename.size() - 2); 2082 2083 // Save the SMLoc, Filename and LineNumber for later use by diagnostics 2084 // and possibly DWARF file info. 2085 CppHashInfo.Loc = L; 2086 CppHashInfo.Filename = Filename; 2087 CppHashInfo.LineNumber = LineNumber; 2088 CppHashInfo.Buf = CurBuffer; 2089 if (FirstCppHashFilename.empty()) 2090 FirstCppHashFilename = Filename; 2091 return false; 2092 } 2093 2094 /// will use the last parsed cpp hash line filename comment 2095 /// for the Filename and LineNo if any in the diagnostic. 2096 void MasmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { 2097 const MasmParser *Parser = static_cast<const MasmParser *>(Context); 2098 raw_ostream &OS = errs(); 2099 2100 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); 2101 SMLoc DiagLoc = Diag.getLoc(); 2102 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2103 unsigned CppHashBuf = 2104 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc); 2105 2106 // Like SourceMgr::printMessage() we need to print the include stack if any 2107 // before printing the message. 2108 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2109 if (!Parser->SavedDiagHandler && DiagCurBuffer && 2110 DiagCurBuffer != DiagSrcMgr.getMainFileID()) { 2111 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); 2112 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); 2113 } 2114 2115 // If we have not parsed a cpp hash line filename comment or the source 2116 // manager changed or buffer changed (like in a nested include) then just 2117 // print the normal diagnostic using its Filename and LineNo. 2118 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr || 2119 DiagBuf != CppHashBuf) { 2120 if (Parser->SavedDiagHandler) 2121 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); 2122 else 2123 Diag.print(nullptr, OS); 2124 return; 2125 } 2126 2127 // Use the CppHashFilename and calculate a line number based on the 2128 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc 2129 // for the diagnostic. 2130 const std::string &Filename = std::string(Parser->CppHashInfo.Filename); 2131 2132 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); 2133 int CppHashLocLineNo = 2134 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf); 2135 int LineNo = 2136 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); 2137 2138 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, 2139 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), 2140 Diag.getLineContents(), Diag.getRanges()); 2141 2142 if (Parser->SavedDiagHandler) 2143 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); 2144 else 2145 NewDiag.print(nullptr, OS); 2146 } 2147 2148 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The 2149 // difference being that that function accepts '@' as part of identifiers and 2150 // we can't do that. AsmLexer.cpp should probably be changed to handle 2151 // '@' as a special case when needed. 2152 static bool isIdentifierChar(char c) { 2153 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' || 2154 c == '.'; 2155 } 2156 2157 bool MasmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, 2158 ArrayRef<MCAsmMacroParameter> Parameters, 2159 ArrayRef<MCAsmMacroArgument> A, 2160 bool EnableAtPseudoVariable, SMLoc L) { 2161 unsigned NParameters = Parameters.size(); 2162 bool HasVararg = NParameters ? Parameters.back().Vararg : false; 2163 if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) 2164 return Error(L, "Wrong number of arguments"); 2165 2166 // A macro without parameters is handled differently on Darwin: 2167 // gas accepts no arguments and does no substitutions 2168 while (!Body.empty()) { 2169 // Scan for the next substitution. 2170 std::size_t End = Body.size(), Pos = 0; 2171 for (; Pos != End; ++Pos) { 2172 // Check for a substitution or escape. 2173 if (IsDarwin && !NParameters) { 2174 // This macro has no parameters, look for $0, $1, etc. 2175 if (Body[Pos] != '$' || Pos + 1 == End) 2176 continue; 2177 2178 char Next = Body[Pos + 1]; 2179 if (Next == '$' || Next == 'n' || 2180 isdigit(static_cast<unsigned char>(Next))) 2181 break; 2182 } else { 2183 // This macro has parameters, look for \foo, \bar, etc. 2184 if (Body[Pos] == '\\' && Pos + 1 != End) 2185 break; 2186 } 2187 } 2188 2189 // Add the prefix. 2190 OS << Body.slice(0, Pos); 2191 2192 // Check if we reached the end. 2193 if (Pos == End) 2194 break; 2195 2196 if (IsDarwin && !NParameters) { 2197 switch (Body[Pos + 1]) { 2198 // $$ => $ 2199 case '$': 2200 OS << '$'; 2201 break; 2202 2203 // $n => number of arguments 2204 case 'n': 2205 OS << A.size(); 2206 break; 2207 2208 // $[0-9] => argument 2209 default: { 2210 // Missing arguments are ignored. 2211 unsigned Index = Body[Pos + 1] - '0'; 2212 if (Index >= A.size()) 2213 break; 2214 2215 // Otherwise substitute with the token values, with spaces eliminated. 2216 for (const AsmToken &Token : A[Index]) 2217 OS << Token.getString(); 2218 break; 2219 } 2220 } 2221 Pos += 2; 2222 } else { 2223 unsigned I = Pos + 1; 2224 2225 // Check for the \@ pseudo-variable. 2226 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End) 2227 ++I; 2228 else 2229 while (isIdentifierChar(Body[I]) && I + 1 != End) 2230 ++I; 2231 2232 const char *Begin = Body.data() + Pos + 1; 2233 StringRef Argument(Begin, I - (Pos + 1)); 2234 unsigned Index = 0; 2235 2236 if (Argument == "@") { 2237 OS << NumOfMacroInstantiations; 2238 Pos += 2; 2239 } else { 2240 for (; Index < NParameters; ++Index) 2241 if (Parameters[Index].Name == Argument) 2242 break; 2243 2244 if (Index == NParameters) { 2245 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 2246 Pos += 3; 2247 else { 2248 OS << '\\' << Argument; 2249 Pos = I; 2250 } 2251 } else { 2252 bool VarargParameter = HasVararg && Index == (NParameters - 1); 2253 for (const AsmToken &Token : A[Index]) 2254 // For altmacro mode, you can write '%expr'. 2255 // The prefix '%' evaluates the expression 'expr' 2256 // and uses the result as a string (e.g. replace %(1+2) with the 2257 // string "3"). 2258 // Here, we identify the integer token which is the result of the 2259 // absolute expression evaluation and replace it with its string 2260 // representation. 2261 if (AltMacroMode && Token.getString().front() == '%' && 2262 Token.is(AsmToken::Integer)) 2263 // Emit an integer value to the buffer. 2264 OS << Token.getIntVal(); 2265 // Only Token that was validated as a string and begins with '<' 2266 // is considered altMacroString!!! 2267 else if (AltMacroMode && Token.getString().front() == '<' && 2268 Token.is(AsmToken::String)) { 2269 OS << angleBracketString(Token.getStringContents()); 2270 } 2271 // We expect no quotes around the string's contents when 2272 // parsing for varargs. 2273 else if (Token.isNot(AsmToken::String) || VarargParameter) 2274 OS << Token.getString(); 2275 else 2276 OS << Token.getStringContents(); 2277 2278 Pos += 1 + Argument.size(); 2279 } 2280 } 2281 } 2282 // Update the scan point. 2283 Body = Body.substr(Pos); 2284 } 2285 2286 return false; 2287 } 2288 2289 static bool isOperator(AsmToken::TokenKind kind) { 2290 switch (kind) { 2291 default: 2292 return false; 2293 case AsmToken::Plus: 2294 case AsmToken::Minus: 2295 case AsmToken::Tilde: 2296 case AsmToken::Slash: 2297 case AsmToken::Star: 2298 case AsmToken::Dot: 2299 case AsmToken::Equal: 2300 case AsmToken::EqualEqual: 2301 case AsmToken::Pipe: 2302 case AsmToken::PipePipe: 2303 case AsmToken::Caret: 2304 case AsmToken::Amp: 2305 case AsmToken::AmpAmp: 2306 case AsmToken::Exclaim: 2307 case AsmToken::ExclaimEqual: 2308 case AsmToken::Less: 2309 case AsmToken::LessEqual: 2310 case AsmToken::LessLess: 2311 case AsmToken::LessGreater: 2312 case AsmToken::Greater: 2313 case AsmToken::GreaterEqual: 2314 case AsmToken::GreaterGreater: 2315 return true; 2316 } 2317 } 2318 2319 namespace { 2320 2321 class AsmLexerSkipSpaceRAII { 2322 public: 2323 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { 2324 Lexer.setSkipSpace(SkipSpace); 2325 } 2326 2327 ~AsmLexerSkipSpaceRAII() { 2328 Lexer.setSkipSpace(true); 2329 } 2330 2331 private: 2332 AsmLexer &Lexer; 2333 }; 2334 2335 } // end anonymous namespace 2336 2337 bool MasmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { 2338 2339 if (Vararg) { 2340 if (Lexer.isNot(AsmToken::EndOfStatement)) { 2341 StringRef Str = parseStringToEndOfStatement(); 2342 MA.emplace_back(AsmToken::String, Str); 2343 } 2344 return false; 2345 } 2346 2347 unsigned ParenLevel = 0; 2348 2349 // Darwin doesn't use spaces to delmit arguments. 2350 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); 2351 2352 bool SpaceEaten; 2353 2354 while (true) { 2355 SpaceEaten = false; 2356 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) 2357 return TokError("unexpected token in macro instantiation"); 2358 2359 if (ParenLevel == 0) { 2360 2361 if (Lexer.is(AsmToken::Comma)) 2362 break; 2363 2364 if (Lexer.is(AsmToken::Space)) { 2365 SpaceEaten = true; 2366 Lexer.Lex(); // Eat spaces 2367 } 2368 2369 // Spaces can delimit parameters, but could also be part an expression. 2370 // If the token after a space is an operator, add the token and the next 2371 // one into this argument 2372 if (!IsDarwin) { 2373 if (isOperator(Lexer.getKind())) { 2374 MA.push_back(getTok()); 2375 Lexer.Lex(); 2376 2377 // Whitespace after an operator can be ignored. 2378 if (Lexer.is(AsmToken::Space)) 2379 Lexer.Lex(); 2380 2381 continue; 2382 } 2383 } 2384 if (SpaceEaten) 2385 break; 2386 } 2387 2388 // handleMacroEntry relies on not advancing the lexer here 2389 // to be able to fill in the remaining default parameter values 2390 if (Lexer.is(AsmToken::EndOfStatement)) 2391 break; 2392 2393 // Adjust the current parentheses level. 2394 if (Lexer.is(AsmToken::LParen)) 2395 ++ParenLevel; 2396 else if (Lexer.is(AsmToken::RParen) && ParenLevel) 2397 --ParenLevel; 2398 2399 // Append the token to the current argument list. 2400 MA.push_back(getTok()); 2401 Lexer.Lex(); 2402 } 2403 2404 if (ParenLevel != 0) 2405 return TokError("unbalanced parentheses in macro argument"); 2406 return false; 2407 } 2408 2409 // Parse the macro instantiation arguments. 2410 bool MasmParser::parseMacroArguments(const MCAsmMacro *M, 2411 MCAsmMacroArguments &A) { 2412 const unsigned NParameters = M ? M->Parameters.size() : 0; 2413 bool NamedParametersFound = false; 2414 SmallVector<SMLoc, 4> FALocs; 2415 2416 A.resize(NParameters); 2417 FALocs.resize(NParameters); 2418 2419 // Parse two kinds of macro invocations: 2420 // - macros defined without any parameters accept an arbitrary number of them 2421 // - macros defined with parameters accept at most that many of them 2422 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; 2423 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; 2424 ++Parameter) { 2425 SMLoc IDLoc = Lexer.getLoc(); 2426 MCAsmMacroParameter FA; 2427 2428 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { 2429 if (parseIdentifier(FA.Name)) 2430 return Error(IDLoc, "invalid argument identifier for formal argument"); 2431 2432 if (Lexer.isNot(AsmToken::Equal)) 2433 return TokError("expected '=' after formal parameter identifier"); 2434 2435 Lex(); 2436 2437 NamedParametersFound = true; 2438 } 2439 bool Vararg = HasVararg && Parameter == (NParameters - 1); 2440 2441 if (NamedParametersFound && FA.Name.empty()) 2442 return Error(IDLoc, "cannot mix positional and keyword arguments"); 2443 2444 SMLoc StrLoc = Lexer.getLoc(); 2445 SMLoc EndLoc; 2446 if (AltMacroMode && Lexer.is(AsmToken::Percent)) { 2447 const MCExpr *AbsoluteExp; 2448 int64_t Value; 2449 /// Eat '%' 2450 Lex(); 2451 if (parseExpression(AbsoluteExp, EndLoc)) 2452 return false; 2453 if (!AbsoluteExp->evaluateAsAbsolute(Value, 2454 getStreamer().getAssemblerPtr())) 2455 return Error(StrLoc, "expected absolute expression"); 2456 const char *StrChar = StrLoc.getPointer(); 2457 const char *EndChar = EndLoc.getPointer(); 2458 AsmToken newToken(AsmToken::Integer, 2459 StringRef(StrChar, EndChar - StrChar), Value); 2460 FA.Value.push_back(newToken); 2461 } else if (AltMacroMode && Lexer.is(AsmToken::Less) && 2462 isAngleBracketString(StrLoc, EndLoc)) { 2463 const char *StrChar = StrLoc.getPointer(); 2464 const char *EndChar = EndLoc.getPointer(); 2465 jumpToLoc(EndLoc, CurBuffer); 2466 /// Eat from '<' to '>' 2467 Lex(); 2468 AsmToken newToken(AsmToken::String, 2469 StringRef(StrChar, EndChar - StrChar)); 2470 FA.Value.push_back(newToken); 2471 } else if(parseMacroArgument(FA.Value, Vararg)) 2472 return true; 2473 2474 unsigned PI = Parameter; 2475 if (!FA.Name.empty()) { 2476 unsigned FAI = 0; 2477 for (FAI = 0; FAI < NParameters; ++FAI) 2478 if (M->Parameters[FAI].Name == FA.Name) 2479 break; 2480 2481 if (FAI >= NParameters) { 2482 assert(M && "expected macro to be defined"); 2483 return Error(IDLoc, "parameter named '" + FA.Name + 2484 "' does not exist for macro '" + M->Name + "'"); 2485 } 2486 PI = FAI; 2487 } 2488 2489 if (!FA.Value.empty()) { 2490 if (A.size() <= PI) 2491 A.resize(PI + 1); 2492 A[PI] = FA.Value; 2493 2494 if (FALocs.size() <= PI) 2495 FALocs.resize(PI + 1); 2496 2497 FALocs[PI] = Lexer.getLoc(); 2498 } 2499 2500 // At the end of the statement, fill in remaining arguments that have 2501 // default values. If there aren't any, then the next argument is 2502 // required but missing 2503 if (Lexer.is(AsmToken::EndOfStatement)) { 2504 bool Failure = false; 2505 for (unsigned FAI = 0; FAI < NParameters; ++FAI) { 2506 if (A[FAI].empty()) { 2507 if (M->Parameters[FAI].Required) { 2508 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), 2509 "missing value for required parameter " 2510 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); 2511 Failure = true; 2512 } 2513 2514 if (!M->Parameters[FAI].Value.empty()) 2515 A[FAI] = M->Parameters[FAI].Value; 2516 } 2517 } 2518 return Failure; 2519 } 2520 2521 if (Lexer.is(AsmToken::Comma)) 2522 Lex(); 2523 } 2524 2525 return TokError("too many positional arguments"); 2526 } 2527 2528 bool MasmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { 2529 // Arbitrarily limit macro nesting depth (default matches 'as'). We can 2530 // eliminate this, although we should protect against infinite loops. 2531 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth; 2532 if (ActiveMacros.size() == MaxNestingDepth) { 2533 std::ostringstream MaxNestingDepthError; 2534 MaxNestingDepthError << "macros cannot be nested more than " 2535 << MaxNestingDepth << " levels deep." 2536 << " Use -asm-macro-max-nesting-depth to increase " 2537 "this limit."; 2538 return TokError(MaxNestingDepthError.str()); 2539 } 2540 2541 MCAsmMacroArguments A; 2542 if (parseMacroArguments(M, A)) 2543 return true; 2544 2545 // Macro instantiation is lexical, unfortunately. We construct a new buffer 2546 // to hold the macro body with substitutions. 2547 SmallString<256> Buf; 2548 StringRef Body = M->Body; 2549 raw_svector_ostream OS(Buf); 2550 2551 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc())) 2552 return true; 2553 2554 // We include the .endmacro in the buffer as our cue to exit the macro 2555 // instantiation. 2556 OS << ".endmacro\n"; 2557 2558 std::unique_ptr<MemoryBuffer> Instantiation = 2559 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 2560 2561 // Create the macro instantiation object and add to the current macro 2562 // instantiation stack. 2563 MacroInstantiation *MI = new MacroInstantiation{ 2564 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 2565 ActiveMacros.push_back(MI); 2566 2567 ++NumOfMacroInstantiations; 2568 2569 // Jump to the macro instantiation and prime the lexer. 2570 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 2571 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 2572 Lex(); 2573 2574 return false; 2575 } 2576 2577 void MasmParser::handleMacroExit() { 2578 // Jump to the EndOfStatement we should return to, and consume it. 2579 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); 2580 Lex(); 2581 2582 // Pop the instantiation entry. 2583 delete ActiveMacros.back(); 2584 ActiveMacros.pop_back(); 2585 } 2586 2587 /// parseIdentifier: 2588 /// ::= identifier 2589 /// ::= string 2590 bool MasmParser::parseIdentifier(StringRef &Res) { 2591 // The assembler has relaxed rules for accepting identifiers, in particular we 2592 // allow things like '.globl $foo' and '.def @feat.00', which would normally 2593 // be separate tokens. At this level, we have already lexed so we cannot 2594 // (currently) handle this as a context dependent token, instead we detect 2595 // adjacent tokens and return the combined identifier. 2596 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { 2597 SMLoc PrefixLoc = getLexer().getLoc(); 2598 2599 // Consume the prefix character, and check for a following identifier. 2600 2601 AsmToken Buf[1]; 2602 Lexer.peekTokens(Buf, false); 2603 2604 if (Buf[0].isNot(AsmToken::Identifier)) 2605 return true; 2606 2607 // We have a '$' or '@' followed by an identifier, make sure they are adjacent. 2608 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer()) 2609 return true; 2610 2611 // eat $ or @ 2612 Lexer.Lex(); // Lexer's Lex guarantees consecutive token. 2613 // Construct the joined identifier and consume the token. 2614 Res = 2615 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1); 2616 Lex(); // Parser Lex to maintain invariants. 2617 return false; 2618 } 2619 2620 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) 2621 return true; 2622 2623 Res = getTok().getIdentifier(); 2624 2625 Lex(); // Consume the identifier token. 2626 2627 return false; 2628 } 2629 2630 /// parseDirectiveEquate: 2631 /// ::= name "=" expression 2632 /// | name "equ" expression (not redefinable) 2633 /// | name "equ" text-list 2634 /// | name "textequ" text-list 2635 bool MasmParser::parseDirectiveEquate(StringRef IDVal, StringRef Name, 2636 DirectiveKind DirKind) { 2637 Variable &Var = Variables[Name]; 2638 if (Var.Name.empty()) { 2639 Var.Name = Name; 2640 } else if (!Var.Redefinable) { 2641 return TokError("invalid variable redefinition"); 2642 } 2643 Var.Redefinable = (DirKind != DK_EQU); 2644 2645 if (DirKind == DK_EQU || DirKind == DK_TEXTEQU) { 2646 // "equ" and "textequ" both allow text expressions. 2647 std::string Value; 2648 if (!parseTextItem(Value)) { 2649 Var.IsText = true; 2650 Var.TextValue = Value; 2651 2652 // Accept a text-list, not just one text-item 2653 auto parseItem = [&]() -> bool { 2654 if (parseTextItem(Value)) 2655 return true; 2656 Var.TextValue += Value; 2657 return false; 2658 }; 2659 if (parseOptionalToken(AsmToken::Comma) && parseMany(parseItem)) 2660 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2661 2662 return false; 2663 } 2664 } 2665 if (DirKind == DK_TEXTEQU) 2666 return TokError("expected <text> in '" + Twine(IDVal) + "' directive"); 2667 2668 // Parse as expression assignment 2669 const MCExpr *Expr; 2670 SMLoc EndLoc, StartLoc = Lexer.getLoc(); 2671 if (parseExpression(Expr, EndLoc)) 2672 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2673 if (Expr->evaluateAsAbsolute(Var.NumericValue, 2674 getStreamer().getAssemblerPtr())) 2675 return false; 2676 2677 // Not an absolute expression; define as a text replacement. 2678 Var.IsText = true; 2679 Var.TextValue = StringRef(StartLoc.getPointer(), 2680 EndLoc.getPointer() - StartLoc.getPointer()).str(); 2681 return false; 2682 } 2683 2684 bool MasmParser::parseEscapedString(std::string &Data) { 2685 if (check(getTok().isNot(AsmToken::String), "expected string")) 2686 return true; 2687 2688 Data = ""; 2689 StringRef Str = getTok().getStringContents(); 2690 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 2691 if (Str[i] != '\\') { 2692 Data += Str[i]; 2693 continue; 2694 } 2695 2696 // Recognize escaped characters. Note that this escape semantics currently 2697 // loosely follows Darwin 'as'. 2698 ++i; 2699 if (i == e) 2700 return TokError("unexpected backslash at end of string"); 2701 2702 // Recognize hex sequences similarly to GNU 'as'. 2703 if (Str[i] == 'x' || Str[i] == 'X') { 2704 size_t length = Str.size(); 2705 if (i + 1 >= length || !isHexDigit(Str[i + 1])) 2706 return TokError("invalid hexadecimal escape sequence"); 2707 2708 // Consume hex characters. GNU 'as' reads all hexadecimal characters and 2709 // then truncates to the lower 16 bits. Seems reasonable. 2710 unsigned Value = 0; 2711 while (i + 1 < length && isHexDigit(Str[i + 1])) 2712 Value = Value * 16 + hexDigitValue(Str[++i]); 2713 2714 Data += (unsigned char)(Value & 0xFF); 2715 continue; 2716 } 2717 2718 // Recognize octal sequences. 2719 if ((unsigned)(Str[i] - '0') <= 7) { 2720 // Consume up to three octal characters. 2721 unsigned Value = Str[i] - '0'; 2722 2723 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2724 ++i; 2725 Value = Value * 8 + (Str[i] - '0'); 2726 2727 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2728 ++i; 2729 Value = Value * 8 + (Str[i] - '0'); 2730 } 2731 } 2732 2733 if (Value > 255) 2734 return TokError("invalid octal escape sequence (out of range)"); 2735 2736 Data += (unsigned char)Value; 2737 continue; 2738 } 2739 2740 // Otherwise recognize individual escapes. 2741 switch (Str[i]) { 2742 default: 2743 // Just reject invalid escape sequences for now. 2744 return TokError("invalid escape sequence (unrecognized character)"); 2745 2746 case 'b': Data += '\b'; break; 2747 case 'f': Data += '\f'; break; 2748 case 'n': Data += '\n'; break; 2749 case 'r': Data += '\r'; break; 2750 case 't': Data += '\t'; break; 2751 case '"': Data += '"'; break; 2752 case '\\': Data += '\\'; break; 2753 } 2754 } 2755 2756 Lex(); 2757 return false; 2758 } 2759 2760 bool MasmParser::parseAngleBracketString(std::string &Data) { 2761 SMLoc EndLoc, StartLoc = getTok().getLoc(); 2762 if (isAngleBracketString(StartLoc, EndLoc)) { 2763 const char *StartChar = StartLoc.getPointer() + 1; 2764 const char *EndChar = EndLoc.getPointer() - 1; 2765 jumpToLoc(EndLoc, CurBuffer); 2766 /// Eat from '<' to '>' 2767 Lex(); 2768 2769 Data = angleBracketString(StringRef(StartChar, EndChar - StartChar)); 2770 return false; 2771 } 2772 return true; 2773 } 2774 2775 /// textItem ::= textLiteral | textMacroID | % constExpr 2776 bool MasmParser::parseTextItem(std::string &Data) { 2777 // TODO(epastor): Support textMacroID and % expansion of expressions. 2778 return parseAngleBracketString(Data); 2779 } 2780 2781 /// parseDirectiveAscii: 2782 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] 2783 bool MasmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { 2784 auto parseOp = [&]() -> bool { 2785 std::string Data; 2786 if (checkForValidSection() || parseEscapedString(Data)) 2787 return true; 2788 getStreamer().emitBytes(Data); 2789 if (ZeroTerminated) 2790 getStreamer().emitBytes(StringRef("\0", 1)); 2791 return false; 2792 }; 2793 2794 if (parseMany(parseOp)) 2795 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2796 return false; 2797 } 2798 2799 /// parseDirectiveValue 2800 /// ::= (byte | word | ... ) [ expression (, expression)* ] 2801 bool MasmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) { 2802 auto parseOp = [&]() -> bool { 2803 const MCExpr *Value; 2804 SMLoc ExprLoc = getLexer().getLoc(); 2805 if (checkForValidSection() || parseExpression(Value)) 2806 return true; 2807 // Special case constant expressions to match code generator. 2808 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 2809 assert(Size <= 8 && "Invalid size"); 2810 int64_t IntValue = MCE->getValue(); 2811 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 2812 return Error(ExprLoc, "out of range literal value"); 2813 getStreamer().emitIntValue(IntValue, Size); 2814 } else 2815 getStreamer().emitValue(Value, Size, ExprLoc); 2816 return false; 2817 }; 2818 2819 if (parseMany(parseOp)) 2820 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2821 return false; 2822 } 2823 2824 static bool parseHexOcta(MasmParser &Asm, uint64_t &hi, uint64_t &lo) { 2825 if (Asm.getTok().isNot(AsmToken::Integer) && 2826 Asm.getTok().isNot(AsmToken::BigNum)) 2827 return Asm.TokError("unknown token in expression"); 2828 SMLoc ExprLoc = Asm.getTok().getLoc(); 2829 APInt IntValue = Asm.getTok().getAPIntVal(); 2830 Asm.Lex(); 2831 if (!IntValue.isIntN(128)) 2832 return Asm.Error(ExprLoc, "out of range literal value"); 2833 if (!IntValue.isIntN(64)) { 2834 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); 2835 lo = IntValue.getLoBits(64).getZExtValue(); 2836 } else { 2837 hi = 0; 2838 lo = IntValue.getZExtValue(); 2839 } 2840 return false; 2841 } 2842 2843 bool MasmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) { 2844 // We don't truly support arithmetic on floating point expressions, so we 2845 // have to manually parse unary prefixes. 2846 bool IsNeg = false; 2847 if (getLexer().is(AsmToken::Minus)) { 2848 Lexer.Lex(); 2849 IsNeg = true; 2850 } else if (getLexer().is(AsmToken::Plus)) 2851 Lexer.Lex(); 2852 2853 if (Lexer.is(AsmToken::Error)) 2854 return TokError(Lexer.getErr()); 2855 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) && 2856 Lexer.isNot(AsmToken::Identifier)) 2857 return TokError("unexpected token in directive"); 2858 2859 // Convert to an APFloat. 2860 APFloat Value(Semantics); 2861 StringRef IDVal = getTok().getString(); 2862 if (getLexer().is(AsmToken::Identifier)) { 2863 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) 2864 Value = APFloat::getInf(Semantics); 2865 else if (!IDVal.compare_lower("nan")) 2866 Value = APFloat::getNaN(Semantics, false, ~0); 2867 else 2868 return TokError("invalid floating point literal"); 2869 } else if (errorToBool( 2870 Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) 2871 .takeError())) 2872 return TokError("invalid floating point literal"); 2873 if (IsNeg) 2874 Value.changeSign(); 2875 2876 // Consume the numeric token. 2877 Lex(); 2878 2879 Res = Value.bitcastToAPInt(); 2880 2881 return false; 2882 } 2883 2884 /// parseDirectiveRealValue 2885 /// ::= (real4 | real8) [ expression (, expression)* ] 2886 bool MasmParser::parseDirectiveRealValue(StringRef IDVal, 2887 const fltSemantics &Semantics) { 2888 auto parseOp = [&]() -> bool { 2889 APInt AsInt; 2890 if (checkForValidSection() || parseRealValue(Semantics, AsInt)) 2891 return true; 2892 getStreamer().emitIntValue(AsInt.getLimitedValue(), 2893 AsInt.getBitWidth() / 8); 2894 return false; 2895 }; 2896 2897 if (parseMany(parseOp)) 2898 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 2899 return false; 2900 } 2901 2902 /// parseDirectiveOrg 2903 /// ::= .org expression [ , expression ] 2904 bool MasmParser::parseDirectiveOrg() { 2905 const MCExpr *Offset; 2906 SMLoc OffsetLoc = Lexer.getLoc(); 2907 if (checkForValidSection() || parseExpression(Offset)) 2908 return true; 2909 2910 // Parse optional fill expression. 2911 int64_t FillExpr = 0; 2912 if (parseOptionalToken(AsmToken::Comma)) 2913 if (parseAbsoluteExpression(FillExpr)) 2914 return addErrorSuffix(" in '.org' directive"); 2915 if (parseToken(AsmToken::EndOfStatement)) 2916 return addErrorSuffix(" in '.org' directive"); 2917 2918 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc); 2919 return false; 2920 } 2921 2922 /// parseDirectiveAlign 2923 /// ::= align expression 2924 bool MasmParser::parseDirectiveAlign() { 2925 SMLoc AlignmentLoc = getLexer().getLoc(); 2926 int64_t Alignment; 2927 2928 if (checkForValidSection()) 2929 return addErrorSuffix(" in align directive"); 2930 // Ignore empty 'align' directives 2931 if (getTok().is(AsmToken::EndOfStatement)) { 2932 Warning(AlignmentLoc, "align directive with no operand is ignored"); 2933 return parseToken(AsmToken::EndOfStatement); 2934 } 2935 if (parseAbsoluteExpression(Alignment) || 2936 parseToken(AsmToken::EndOfStatement)) 2937 return addErrorSuffix(" in align directive"); 2938 2939 // Always emit an alignment here even if we thrown an error. 2940 bool ReturnVal = false; 2941 2942 // Reject alignments that aren't either a power of two or zero, 2943 // for gas compatibility. Alignment of zero is silently rounded 2944 // up to one. 2945 if (Alignment == 0) 2946 Alignment = 1; 2947 if (!isPowerOf2_64(Alignment)) 2948 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2"); 2949 2950 // Check whether we should use optimal code alignment for this align 2951 // directive. 2952 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 2953 assert(Section && "must have section to emit alignment"); 2954 if (Section->UseCodeAlign()) { 2955 getStreamer().emitCodeAlignment(Alignment, /*MaxBytesToEmit=*/0); 2956 } else { 2957 // FIXME: Target specific behavior about how the "extra" bytes are filled. 2958 getStreamer().emitValueToAlignment(Alignment, /*Value=*/0, /*ValueSize=*/1, 2959 /*MaxBytesToEmit=*/0); 2960 } 2961 2962 return ReturnVal; 2963 } 2964 2965 /// parseDirectiveFile 2966 /// ::= .file filename 2967 /// ::= .file number [directory] filename [md5 checksum] [source source-text] 2968 bool MasmParser::parseDirectiveFile(SMLoc DirectiveLoc) { 2969 // FIXME: I'm not sure what this is. 2970 int64_t FileNumber = -1; 2971 if (getLexer().is(AsmToken::Integer)) { 2972 FileNumber = getTok().getIntVal(); 2973 Lex(); 2974 2975 if (FileNumber < 0) 2976 return TokError("negative file number"); 2977 } 2978 2979 std::string Path; 2980 2981 // Usually the directory and filename together, otherwise just the directory. 2982 // Allow the strings to have escaped octal character sequence. 2983 if (check(getTok().isNot(AsmToken::String), 2984 "unexpected token in '.file' directive") || 2985 parseEscapedString(Path)) 2986 return true; 2987 2988 StringRef Directory; 2989 StringRef Filename; 2990 std::string FilenameData; 2991 if (getLexer().is(AsmToken::String)) { 2992 if (check(FileNumber == -1, 2993 "explicit path specified, but no file number") || 2994 parseEscapedString(FilenameData)) 2995 return true; 2996 Filename = FilenameData; 2997 Directory = Path; 2998 } else { 2999 Filename = Path; 3000 } 3001 3002 uint64_t MD5Hi, MD5Lo; 3003 bool HasMD5 = false; 3004 3005 Optional<StringRef> Source; 3006 bool HasSource = false; 3007 std::string SourceString; 3008 3009 while (!parseOptionalToken(AsmToken::EndOfStatement)) { 3010 StringRef Keyword; 3011 if (check(getTok().isNot(AsmToken::Identifier), 3012 "unexpected token in '.file' directive") || 3013 parseIdentifier(Keyword)) 3014 return true; 3015 if (Keyword == "md5") { 3016 HasMD5 = true; 3017 if (check(FileNumber == -1, 3018 "MD5 checksum specified, but no file number") || 3019 parseHexOcta(*this, MD5Hi, MD5Lo)) 3020 return true; 3021 } else if (Keyword == "source") { 3022 HasSource = true; 3023 if (check(FileNumber == -1, 3024 "source specified, but no file number") || 3025 check(getTok().isNot(AsmToken::String), 3026 "unexpected token in '.file' directive") || 3027 parseEscapedString(SourceString)) 3028 return true; 3029 } else { 3030 return TokError("unexpected token in '.file' directive"); 3031 } 3032 } 3033 3034 if (FileNumber == -1) { 3035 // Ignore the directive if there is no number and the target doesn't support 3036 // numberless .file directives. This allows some portability of assembler 3037 // between different object file formats. 3038 if (getContext().getAsmInfo()->hasSingleParameterDotFile()) 3039 getStreamer().emitFileDirective(Filename); 3040 } else { 3041 // In case there is a -g option as well as debug info from directive .file, 3042 // we turn off the -g option, directly use the existing debug info instead. 3043 // Throw away any implicit file table for the assembler source. 3044 if (Ctx.getGenDwarfForAssembly()) { 3045 Ctx.getMCDwarfLineTable(0).resetFileTable(); 3046 Ctx.setGenDwarfForAssembly(false); 3047 } 3048 3049 Optional<MD5::MD5Result> CKMem; 3050 if (HasMD5) { 3051 MD5::MD5Result Sum; 3052 for (unsigned i = 0; i != 8; ++i) { 3053 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8)); 3054 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8)); 3055 } 3056 CKMem = Sum; 3057 } 3058 if (HasSource) { 3059 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size())); 3060 memcpy(SourceBuf, SourceString.data(), SourceString.size()); 3061 Source = StringRef(SourceBuf, SourceString.size()); 3062 } 3063 if (FileNumber == 0) { 3064 if (Ctx.getDwarfVersion() < 5) 3065 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5"); 3066 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source); 3067 } else { 3068 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective( 3069 FileNumber, Directory, Filename, CKMem, Source); 3070 if (!FileNumOrErr) 3071 return Error(DirectiveLoc, toString(FileNumOrErr.takeError())); 3072 } 3073 // Alert the user if there are some .file directives with MD5 and some not. 3074 // But only do that once. 3075 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) { 3076 ReportedInconsistentMD5 = true; 3077 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums"); 3078 } 3079 } 3080 3081 return false; 3082 } 3083 3084 /// parseDirectiveLine 3085 /// ::= .line [number] 3086 bool MasmParser::parseDirectiveLine() { 3087 int64_t LineNumber; 3088 if (getLexer().is(AsmToken::Integer)) { 3089 if (parseIntToken(LineNumber, "unexpected token in '.line' directive")) 3090 return true; 3091 (void)LineNumber; 3092 // FIXME: Do something with the .line. 3093 } 3094 if (parseToken(AsmToken::EndOfStatement, 3095 "unexpected token in '.line' directive")) 3096 return true; 3097 3098 return false; 3099 } 3100 3101 /// parseDirectiveLoc 3102 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] 3103 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] 3104 /// The first number is a file number, must have been previously assigned with 3105 /// a .file directive, the second number is the line number and optionally the 3106 /// third number is a column position (zero if not specified). The remaining 3107 /// optional items are .loc sub-directives. 3108 bool MasmParser::parseDirectiveLoc() { 3109 int64_t FileNumber = 0, LineNumber = 0; 3110 SMLoc Loc = getTok().getLoc(); 3111 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") || 3112 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc, 3113 "file number less than one in '.loc' directive") || 3114 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc, 3115 "unassigned file number in '.loc' directive")) 3116 return true; 3117 3118 // optional 3119 if (getLexer().is(AsmToken::Integer)) { 3120 LineNumber = getTok().getIntVal(); 3121 if (LineNumber < 0) 3122 return TokError("line number less than zero in '.loc' directive"); 3123 Lex(); 3124 } 3125 3126 int64_t ColumnPos = 0; 3127 if (getLexer().is(AsmToken::Integer)) { 3128 ColumnPos = getTok().getIntVal(); 3129 if (ColumnPos < 0) 3130 return TokError("column position less than zero in '.loc' directive"); 3131 Lex(); 3132 } 3133 3134 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 3135 unsigned Isa = 0; 3136 int64_t Discriminator = 0; 3137 3138 auto parseLocOp = [&]() -> bool { 3139 StringRef Name; 3140 SMLoc Loc = getTok().getLoc(); 3141 if (parseIdentifier(Name)) 3142 return TokError("unexpected token in '.loc' directive"); 3143 3144 if (Name == "basic_block") 3145 Flags |= DWARF2_FLAG_BASIC_BLOCK; 3146 else if (Name == "prologue_end") 3147 Flags |= DWARF2_FLAG_PROLOGUE_END; 3148 else if (Name == "epilogue_begin") 3149 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; 3150 else if (Name == "is_stmt") { 3151 Loc = getTok().getLoc(); 3152 const MCExpr *Value; 3153 if (parseExpression(Value)) 3154 return true; 3155 // The expression must be the constant 0 or 1. 3156 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3157 int Value = MCE->getValue(); 3158 if (Value == 0) 3159 Flags &= ~DWARF2_FLAG_IS_STMT; 3160 else if (Value == 1) 3161 Flags |= DWARF2_FLAG_IS_STMT; 3162 else 3163 return Error(Loc, "is_stmt value not 0 or 1"); 3164 } else { 3165 return Error(Loc, "is_stmt value not the constant value of 0 or 1"); 3166 } 3167 } else if (Name == "isa") { 3168 Loc = getTok().getLoc(); 3169 const MCExpr *Value; 3170 if (parseExpression(Value)) 3171 return true; 3172 // The expression must be a constant greater or equal to 0. 3173 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3174 int Value = MCE->getValue(); 3175 if (Value < 0) 3176 return Error(Loc, "isa number less than zero"); 3177 Isa = Value; 3178 } else { 3179 return Error(Loc, "isa number not a constant value"); 3180 } 3181 } else if (Name == "discriminator") { 3182 if (parseAbsoluteExpression(Discriminator)) 3183 return true; 3184 } else { 3185 return Error(Loc, "unknown sub-directive in '.loc' directive"); 3186 } 3187 return false; 3188 }; 3189 3190 if (parseMany(parseLocOp, false /*hasComma*/)) 3191 return true; 3192 3193 getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, 3194 Isa, Discriminator, StringRef()); 3195 3196 return false; 3197 } 3198 3199 /// parseDirectiveStabs 3200 /// ::= .stabs string, number, number, number 3201 bool MasmParser::parseDirectiveStabs() { 3202 return TokError("unsupported directive '.stabs'"); 3203 } 3204 3205 /// parseDirectiveCVFile 3206 /// ::= .cv_file number filename [checksum] [checksumkind] 3207 bool MasmParser::parseDirectiveCVFile() { 3208 SMLoc FileNumberLoc = getTok().getLoc(); 3209 int64_t FileNumber; 3210 std::string Filename; 3211 std::string Checksum; 3212 int64_t ChecksumKind = 0; 3213 3214 if (parseIntToken(FileNumber, 3215 "expected file number in '.cv_file' directive") || 3216 check(FileNumber < 1, FileNumberLoc, "file number less than one") || 3217 check(getTok().isNot(AsmToken::String), 3218 "unexpected token in '.cv_file' directive") || 3219 parseEscapedString(Filename)) 3220 return true; 3221 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 3222 if (check(getTok().isNot(AsmToken::String), 3223 "unexpected token in '.cv_file' directive") || 3224 parseEscapedString(Checksum) || 3225 parseIntToken(ChecksumKind, 3226 "expected checksum kind in '.cv_file' directive") || 3227 parseToken(AsmToken::EndOfStatement, 3228 "unexpected token in '.cv_file' directive")) 3229 return true; 3230 } 3231 3232 Checksum = fromHex(Checksum); 3233 void *CKMem = Ctx.allocate(Checksum.size(), 1); 3234 memcpy(CKMem, Checksum.data(), Checksum.size()); 3235 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem), 3236 Checksum.size()); 3237 3238 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes, 3239 static_cast<uint8_t>(ChecksumKind))) 3240 return Error(FileNumberLoc, "file number already allocated"); 3241 3242 return false; 3243 } 3244 3245 bool MasmParser::parseCVFunctionId(int64_t &FunctionId, 3246 StringRef DirectiveName) { 3247 SMLoc Loc; 3248 return parseTokenLoc(Loc) || 3249 parseIntToken(FunctionId, "expected function id in '" + DirectiveName + 3250 "' directive") || 3251 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc, 3252 "expected function id within range [0, UINT_MAX)"); 3253 } 3254 3255 bool MasmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) { 3256 SMLoc Loc; 3257 return parseTokenLoc(Loc) || 3258 parseIntToken(FileNumber, "expected integer in '" + DirectiveName + 3259 "' directive") || 3260 check(FileNumber < 1, Loc, "file number less than one in '" + 3261 DirectiveName + "' directive") || 3262 check(!getCVContext().isValidFileNumber(FileNumber), Loc, 3263 "unassigned file number in '" + DirectiveName + "' directive"); 3264 } 3265 3266 /// parseDirectiveCVFuncId 3267 /// ::= .cv_func_id FunctionId 3268 /// 3269 /// Introduces a function ID that can be used with .cv_loc. 3270 bool MasmParser::parseDirectiveCVFuncId() { 3271 SMLoc FunctionIdLoc = getTok().getLoc(); 3272 int64_t FunctionId; 3273 3274 if (parseCVFunctionId(FunctionId, ".cv_func_id") || 3275 parseToken(AsmToken::EndOfStatement, 3276 "unexpected token in '.cv_func_id' directive")) 3277 return true; 3278 3279 if (!getStreamer().EmitCVFuncIdDirective(FunctionId)) 3280 return Error(FunctionIdLoc, "function id already allocated"); 3281 3282 return false; 3283 } 3284 3285 /// parseDirectiveCVInlineSiteId 3286 /// ::= .cv_inline_site_id FunctionId 3287 /// "within" IAFunc 3288 /// "inlined_at" IAFile IALine [IACol] 3289 /// 3290 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined 3291 /// at" source location information for use in the line table of the caller, 3292 /// whether the caller is a real function or another inlined call site. 3293 bool MasmParser::parseDirectiveCVInlineSiteId() { 3294 SMLoc FunctionIdLoc = getTok().getLoc(); 3295 int64_t FunctionId; 3296 int64_t IAFunc; 3297 int64_t IAFile; 3298 int64_t IALine; 3299 int64_t IACol = 0; 3300 3301 // FunctionId 3302 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id")) 3303 return true; 3304 3305 // "within" 3306 if (check((getLexer().isNot(AsmToken::Identifier) || 3307 getTok().getIdentifier() != "within"), 3308 "expected 'within' identifier in '.cv_inline_site_id' directive")) 3309 return true; 3310 Lex(); 3311 3312 // IAFunc 3313 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id")) 3314 return true; 3315 3316 // "inlined_at" 3317 if (check((getLexer().isNot(AsmToken::Identifier) || 3318 getTok().getIdentifier() != "inlined_at"), 3319 "expected 'inlined_at' identifier in '.cv_inline_site_id' " 3320 "directive") ) 3321 return true; 3322 Lex(); 3323 3324 // IAFile IALine 3325 if (parseCVFileId(IAFile, ".cv_inline_site_id") || 3326 parseIntToken(IALine, "expected line number after 'inlined_at'")) 3327 return true; 3328 3329 // [IACol] 3330 if (getLexer().is(AsmToken::Integer)) { 3331 IACol = getTok().getIntVal(); 3332 Lex(); 3333 } 3334 3335 if (parseToken(AsmToken::EndOfStatement, 3336 "unexpected token in '.cv_inline_site_id' directive")) 3337 return true; 3338 3339 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, 3340 IALine, IACol, FunctionIdLoc)) 3341 return Error(FunctionIdLoc, "function id already allocated"); 3342 3343 return false; 3344 } 3345 3346 /// parseDirectiveCVLoc 3347 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end] 3348 /// [is_stmt VALUE] 3349 /// The first number is a file number, must have been previously assigned with 3350 /// a .file directive, the second number is the line number and optionally the 3351 /// third number is a column position (zero if not specified). The remaining 3352 /// optional items are .loc sub-directives. 3353 bool MasmParser::parseDirectiveCVLoc() { 3354 SMLoc DirectiveLoc = getTok().getLoc(); 3355 int64_t FunctionId, FileNumber; 3356 if (parseCVFunctionId(FunctionId, ".cv_loc") || 3357 parseCVFileId(FileNumber, ".cv_loc")) 3358 return true; 3359 3360 int64_t LineNumber = 0; 3361 if (getLexer().is(AsmToken::Integer)) { 3362 LineNumber = getTok().getIntVal(); 3363 if (LineNumber < 0) 3364 return TokError("line number less than zero in '.cv_loc' directive"); 3365 Lex(); 3366 } 3367 3368 int64_t ColumnPos = 0; 3369 if (getLexer().is(AsmToken::Integer)) { 3370 ColumnPos = getTok().getIntVal(); 3371 if (ColumnPos < 0) 3372 return TokError("column position less than zero in '.cv_loc' directive"); 3373 Lex(); 3374 } 3375 3376 bool PrologueEnd = false; 3377 uint64_t IsStmt = 0; 3378 3379 auto parseOp = [&]() -> bool { 3380 StringRef Name; 3381 SMLoc Loc = getTok().getLoc(); 3382 if (parseIdentifier(Name)) 3383 return TokError("unexpected token in '.cv_loc' directive"); 3384 if (Name == "prologue_end") 3385 PrologueEnd = true; 3386 else if (Name == "is_stmt") { 3387 Loc = getTok().getLoc(); 3388 const MCExpr *Value; 3389 if (parseExpression(Value)) 3390 return true; 3391 // The expression must be the constant 0 or 1. 3392 IsStmt = ~0ULL; 3393 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) 3394 IsStmt = MCE->getValue(); 3395 3396 if (IsStmt > 1) 3397 return Error(Loc, "is_stmt value not 0 or 1"); 3398 } else { 3399 return Error(Loc, "unknown sub-directive in '.cv_loc' directive"); 3400 } 3401 return false; 3402 }; 3403 3404 if (parseMany(parseOp, false /*hasComma*/)) 3405 return true; 3406 3407 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber, 3408 ColumnPos, PrologueEnd, IsStmt, StringRef(), 3409 DirectiveLoc); 3410 return false; 3411 } 3412 3413 /// parseDirectiveCVLinetable 3414 /// ::= .cv_linetable FunctionId, FnStart, FnEnd 3415 bool MasmParser::parseDirectiveCVLinetable() { 3416 int64_t FunctionId; 3417 StringRef FnStartName, FnEndName; 3418 SMLoc Loc = getTok().getLoc(); 3419 if (parseCVFunctionId(FunctionId, ".cv_linetable") || 3420 parseToken(AsmToken::Comma, 3421 "unexpected token in '.cv_linetable' directive") || 3422 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3423 "expected identifier in directive") || 3424 parseToken(AsmToken::Comma, 3425 "unexpected token in '.cv_linetable' directive") || 3426 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3427 "expected identifier in directive")) 3428 return true; 3429 3430 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3431 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3432 3433 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym); 3434 return false; 3435 } 3436 3437 /// parseDirectiveCVInlineLinetable 3438 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd 3439 bool MasmParser::parseDirectiveCVInlineLinetable() { 3440 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum; 3441 StringRef FnStartName, FnEndName; 3442 SMLoc Loc = getTok().getLoc(); 3443 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") || 3444 parseTokenLoc(Loc) || 3445 parseIntToken( 3446 SourceFileId, 3447 "expected SourceField in '.cv_inline_linetable' directive") || 3448 check(SourceFileId <= 0, Loc, 3449 "File id less than zero in '.cv_inline_linetable' directive") || 3450 parseTokenLoc(Loc) || 3451 parseIntToken( 3452 SourceLineNum, 3453 "expected SourceLineNum in '.cv_inline_linetable' directive") || 3454 check(SourceLineNum < 0, Loc, 3455 "Line number less than zero in '.cv_inline_linetable' directive") || 3456 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 3457 "expected identifier in directive") || 3458 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 3459 "expected identifier in directive")) 3460 return true; 3461 3462 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 3463 return true; 3464 3465 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 3466 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 3467 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId, 3468 SourceLineNum, FnStartSym, 3469 FnEndSym); 3470 return false; 3471 } 3472 3473 void MasmParser::initializeCVDefRangeTypeMap() { 3474 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER; 3475 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL; 3476 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER; 3477 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL; 3478 } 3479 3480 /// parseDirectiveCVDefRange 3481 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes* 3482 bool MasmParser::parseDirectiveCVDefRange() { 3483 SMLoc Loc; 3484 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges; 3485 while (getLexer().is(AsmToken::Identifier)) { 3486 Loc = getLexer().getLoc(); 3487 StringRef GapStartName; 3488 if (parseIdentifier(GapStartName)) 3489 return Error(Loc, "expected identifier in directive"); 3490 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName); 3491 3492 Loc = getLexer().getLoc(); 3493 StringRef GapEndName; 3494 if (parseIdentifier(GapEndName)) 3495 return Error(Loc, "expected identifier in directive"); 3496 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName); 3497 3498 Ranges.push_back({GapStartSym, GapEndSym}); 3499 } 3500 3501 StringRef CVDefRangeTypeStr; 3502 if (parseToken( 3503 AsmToken::Comma, 3504 "expected comma before def_range type in .cv_def_range directive") || 3505 parseIdentifier(CVDefRangeTypeStr)) 3506 return Error(Loc, "expected def_range type in directive"); 3507 3508 StringMap<CVDefRangeType>::const_iterator CVTypeIt = 3509 CVDefRangeTypeMap.find(CVDefRangeTypeStr); 3510 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end()) 3511 ? CVDR_DEFRANGE 3512 : CVTypeIt->getValue(); 3513 switch (CVDRType) { 3514 case CVDR_DEFRANGE_REGISTER: { 3515 int64_t DRRegister; 3516 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3517 ".cv_def_range directive") || 3518 parseAbsoluteExpression(DRRegister)) 3519 return Error(Loc, "expected register number"); 3520 3521 codeview::DefRangeRegisterHeader DRHdr; 3522 DRHdr.Register = DRRegister; 3523 DRHdr.MayHaveNoName = 0; 3524 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr); 3525 break; 3526 } 3527 case CVDR_DEFRANGE_FRAMEPOINTER_REL: { 3528 int64_t DROffset; 3529 if (parseToken(AsmToken::Comma, 3530 "expected comma before offset in .cv_def_range directive") || 3531 parseAbsoluteExpression(DROffset)) 3532 return Error(Loc, "expected offset value"); 3533 3534 codeview::DefRangeFramePointerRelHeader DRHdr; 3535 DRHdr.Offset = DROffset; 3536 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr); 3537 break; 3538 } 3539 case CVDR_DEFRANGE_SUBFIELD_REGISTER: { 3540 int64_t DRRegister; 3541 int64_t DROffsetInParent; 3542 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3543 ".cv_def_range directive") || 3544 parseAbsoluteExpression(DRRegister)) 3545 return Error(Loc, "expected register number"); 3546 if (parseToken(AsmToken::Comma, 3547 "expected comma before offset in .cv_def_range directive") || 3548 parseAbsoluteExpression(DROffsetInParent)) 3549 return Error(Loc, "expected offset value"); 3550 3551 codeview::DefRangeSubfieldRegisterHeader DRHdr; 3552 DRHdr.Register = DRRegister; 3553 DRHdr.MayHaveNoName = 0; 3554 DRHdr.OffsetInParent = DROffsetInParent; 3555 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr); 3556 break; 3557 } 3558 case CVDR_DEFRANGE_REGISTER_REL: { 3559 int64_t DRRegister; 3560 int64_t DRFlags; 3561 int64_t DRBasePointerOffset; 3562 if (parseToken(AsmToken::Comma, "expected comma before register number in " 3563 ".cv_def_range directive") || 3564 parseAbsoluteExpression(DRRegister)) 3565 return Error(Loc, "expected register value"); 3566 if (parseToken( 3567 AsmToken::Comma, 3568 "expected comma before flag value in .cv_def_range directive") || 3569 parseAbsoluteExpression(DRFlags)) 3570 return Error(Loc, "expected flag value"); 3571 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset " 3572 "in .cv_def_range directive") || 3573 parseAbsoluteExpression(DRBasePointerOffset)) 3574 return Error(Loc, "expected base pointer offset value"); 3575 3576 codeview::DefRangeRegisterRelHeader DRHdr; 3577 DRHdr.Register = DRRegister; 3578 DRHdr.Flags = DRFlags; 3579 DRHdr.BasePointerOffset = DRBasePointerOffset; 3580 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr); 3581 break; 3582 } 3583 default: 3584 return Error(Loc, "unexpected def_range type in .cv_def_range directive"); 3585 } 3586 return true; 3587 } 3588 3589 /// parseDirectiveCVString 3590 /// ::= .cv_stringtable "string" 3591 bool MasmParser::parseDirectiveCVString() { 3592 std::string Data; 3593 if (checkForValidSection() || parseEscapedString(Data)) 3594 return addErrorSuffix(" in '.cv_string' directive"); 3595 3596 // Put the string in the table and emit the offset. 3597 std::pair<StringRef, unsigned> Insertion = 3598 getCVContext().addToStringTable(Data); 3599 getStreamer().emitIntValue(Insertion.second, 4); 3600 return false; 3601 } 3602 3603 /// parseDirectiveCVStringTable 3604 /// ::= .cv_stringtable 3605 bool MasmParser::parseDirectiveCVStringTable() { 3606 getStreamer().EmitCVStringTableDirective(); 3607 return false; 3608 } 3609 3610 /// parseDirectiveCVFileChecksums 3611 /// ::= .cv_filechecksums 3612 bool MasmParser::parseDirectiveCVFileChecksums() { 3613 getStreamer().EmitCVFileChecksumsDirective(); 3614 return false; 3615 } 3616 3617 /// parseDirectiveCVFileChecksumOffset 3618 /// ::= .cv_filechecksumoffset fileno 3619 bool MasmParser::parseDirectiveCVFileChecksumOffset() { 3620 int64_t FileNo; 3621 if (parseIntToken(FileNo, "expected identifier in directive")) 3622 return true; 3623 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 3624 return true; 3625 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo); 3626 return false; 3627 } 3628 3629 /// parseDirectiveCVFPOData 3630 /// ::= .cv_fpo_data procsym 3631 bool MasmParser::parseDirectiveCVFPOData() { 3632 SMLoc DirLoc = getLexer().getLoc(); 3633 StringRef ProcName; 3634 if (parseIdentifier(ProcName)) 3635 return TokError("expected symbol name"); 3636 if (parseEOL("unexpected tokens")) 3637 return addErrorSuffix(" in '.cv_fpo_data' directive"); 3638 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName); 3639 getStreamer().EmitCVFPOData(ProcSym, DirLoc); 3640 return false; 3641 } 3642 3643 /// parseDirectiveCFISections 3644 /// ::= .cfi_sections section [, section] 3645 bool MasmParser::parseDirectiveCFISections() { 3646 StringRef Name; 3647 bool EH = false; 3648 bool Debug = false; 3649 3650 if (parseIdentifier(Name)) 3651 return TokError("Expected an identifier"); 3652 3653 if (Name == ".eh_frame") 3654 EH = true; 3655 else if (Name == ".debug_frame") 3656 Debug = true; 3657 3658 if (getLexer().is(AsmToken::Comma)) { 3659 Lex(); 3660 3661 if (parseIdentifier(Name)) 3662 return TokError("Expected an identifier"); 3663 3664 if (Name == ".eh_frame") 3665 EH = true; 3666 else if (Name == ".debug_frame") 3667 Debug = true; 3668 } 3669 3670 getStreamer().emitCFISections(EH, Debug); 3671 return false; 3672 } 3673 3674 /// parseDirectiveCFIStartProc 3675 /// ::= .cfi_startproc [simple] 3676 bool MasmParser::parseDirectiveCFIStartProc() { 3677 StringRef Simple; 3678 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 3679 if (check(parseIdentifier(Simple) || Simple != "simple", 3680 "unexpected token") || 3681 parseToken(AsmToken::EndOfStatement)) 3682 return addErrorSuffix(" in '.cfi_startproc' directive"); 3683 } 3684 3685 // TODO(kristina): Deal with a corner case of incorrect diagnostic context 3686 // being produced if this directive is emitted as part of preprocessor macro 3687 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer. 3688 // Tools like llvm-mc on the other hand are not affected by it, and report 3689 // correct context information. 3690 getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc()); 3691 return false; 3692 } 3693 3694 /// parseDirectiveCFIEndProc 3695 /// ::= .cfi_endproc 3696 bool MasmParser::parseDirectiveCFIEndProc() { 3697 getStreamer().emitCFIEndProc(); 3698 return false; 3699 } 3700 3701 /// parse register name or number. 3702 bool MasmParser::parseRegisterOrRegisterNumber(int64_t &Register, 3703 SMLoc DirectiveLoc) { 3704 unsigned RegNo; 3705 3706 if (getLexer().isNot(AsmToken::Integer)) { 3707 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) 3708 return true; 3709 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); 3710 } else 3711 return parseAbsoluteExpression(Register); 3712 3713 return false; 3714 } 3715 3716 /// parseDirectiveCFIDefCfa 3717 /// ::= .cfi_def_cfa register, offset 3718 bool MasmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { 3719 int64_t Register = 0, Offset = 0; 3720 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 3721 parseToken(AsmToken::Comma, "unexpected token in directive") || 3722 parseAbsoluteExpression(Offset)) 3723 return true; 3724 3725 getStreamer().emitCFIDefCfa(Register, Offset); 3726 return false; 3727 } 3728 3729 /// parseDirectiveCFIDefCfaOffset 3730 /// ::= .cfi_def_cfa_offset offset 3731 bool MasmParser::parseDirectiveCFIDefCfaOffset() { 3732 int64_t Offset = 0; 3733 if (parseAbsoluteExpression(Offset)) 3734 return true; 3735 3736 getStreamer().emitCFIDefCfaOffset(Offset); 3737 return false; 3738 } 3739 3740 /// parseDirectiveCFIRegister 3741 /// ::= .cfi_register register, register 3742 bool MasmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { 3743 int64_t Register1 = 0, Register2 = 0; 3744 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || 3745 parseToken(AsmToken::Comma, "unexpected token in directive") || 3746 parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) 3747 return true; 3748 3749 getStreamer().emitCFIRegister(Register1, Register2); 3750 return false; 3751 } 3752 3753 /// parseDirectiveCFIWindowSave 3754 /// ::= .cfi_window_save 3755 bool MasmParser::parseDirectiveCFIWindowSave() { 3756 getStreamer().emitCFIWindowSave(); 3757 return false; 3758 } 3759 3760 /// parseDirectiveCFIAdjustCfaOffset 3761 /// ::= .cfi_adjust_cfa_offset adjustment 3762 bool MasmParser::parseDirectiveCFIAdjustCfaOffset() { 3763 int64_t Adjustment = 0; 3764 if (parseAbsoluteExpression(Adjustment)) 3765 return true; 3766 3767 getStreamer().emitCFIAdjustCfaOffset(Adjustment); 3768 return false; 3769 } 3770 3771 /// parseDirectiveCFIDefCfaRegister 3772 /// ::= .cfi_def_cfa_register register 3773 bool MasmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { 3774 int64_t Register = 0; 3775 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3776 return true; 3777 3778 getStreamer().emitCFIDefCfaRegister(Register); 3779 return false; 3780 } 3781 3782 /// parseDirectiveCFIOffset 3783 /// ::= .cfi_offset register, offset 3784 bool MasmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { 3785 int64_t Register = 0; 3786 int64_t Offset = 0; 3787 3788 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 3789 parseToken(AsmToken::Comma, "unexpected token in directive") || 3790 parseAbsoluteExpression(Offset)) 3791 return true; 3792 3793 getStreamer().emitCFIOffset(Register, Offset); 3794 return false; 3795 } 3796 3797 /// parseDirectiveCFIRelOffset 3798 /// ::= .cfi_rel_offset register, offset 3799 bool MasmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { 3800 int64_t Register = 0, Offset = 0; 3801 3802 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 3803 parseToken(AsmToken::Comma, "unexpected token in directive") || 3804 parseAbsoluteExpression(Offset)) 3805 return true; 3806 3807 getStreamer().emitCFIRelOffset(Register, Offset); 3808 return false; 3809 } 3810 3811 static bool isValidEncoding(int64_t Encoding) { 3812 if (Encoding & ~0xff) 3813 return false; 3814 3815 if (Encoding == dwarf::DW_EH_PE_omit) 3816 return true; 3817 3818 const unsigned Format = Encoding & 0xf; 3819 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && 3820 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && 3821 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && 3822 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) 3823 return false; 3824 3825 const unsigned Application = Encoding & 0x70; 3826 if (Application != dwarf::DW_EH_PE_absptr && 3827 Application != dwarf::DW_EH_PE_pcrel) 3828 return false; 3829 3830 return true; 3831 } 3832 3833 /// parseDirectiveCFIPersonalityOrLsda 3834 /// IsPersonality true for cfi_personality, false for cfi_lsda 3835 /// ::= .cfi_personality encoding, [symbol_name] 3836 /// ::= .cfi_lsda encoding, [symbol_name] 3837 bool MasmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { 3838 int64_t Encoding = 0; 3839 if (parseAbsoluteExpression(Encoding)) 3840 return true; 3841 if (Encoding == dwarf::DW_EH_PE_omit) 3842 return false; 3843 3844 StringRef Name; 3845 if (check(!isValidEncoding(Encoding), "unsupported encoding.") || 3846 parseToken(AsmToken::Comma, "unexpected token in directive") || 3847 check(parseIdentifier(Name), "expected identifier in directive")) 3848 return true; 3849 3850 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3851 3852 if (IsPersonality) 3853 getStreamer().emitCFIPersonality(Sym, Encoding); 3854 else 3855 getStreamer().emitCFILsda(Sym, Encoding); 3856 return false; 3857 } 3858 3859 /// parseDirectiveCFIRememberState 3860 /// ::= .cfi_remember_state 3861 bool MasmParser::parseDirectiveCFIRememberState() { 3862 getStreamer().emitCFIRememberState(); 3863 return false; 3864 } 3865 3866 /// parseDirectiveCFIRestoreState 3867 /// ::= .cfi_remember_state 3868 bool MasmParser::parseDirectiveCFIRestoreState() { 3869 getStreamer().emitCFIRestoreState(); 3870 return false; 3871 } 3872 3873 /// parseDirectiveCFISameValue 3874 /// ::= .cfi_same_value register 3875 bool MasmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { 3876 int64_t Register = 0; 3877 3878 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3879 return true; 3880 3881 getStreamer().emitCFISameValue(Register); 3882 return false; 3883 } 3884 3885 /// parseDirectiveCFIRestore 3886 /// ::= .cfi_restore register 3887 bool MasmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { 3888 int64_t Register = 0; 3889 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3890 return true; 3891 3892 getStreamer().emitCFIRestore(Register); 3893 return false; 3894 } 3895 3896 /// parseDirectiveCFIEscape 3897 /// ::= .cfi_escape expression[,...] 3898 bool MasmParser::parseDirectiveCFIEscape() { 3899 std::string Values; 3900 int64_t CurrValue; 3901 if (parseAbsoluteExpression(CurrValue)) 3902 return true; 3903 3904 Values.push_back((uint8_t)CurrValue); 3905 3906 while (getLexer().is(AsmToken::Comma)) { 3907 Lex(); 3908 3909 if (parseAbsoluteExpression(CurrValue)) 3910 return true; 3911 3912 Values.push_back((uint8_t)CurrValue); 3913 } 3914 3915 getStreamer().emitCFIEscape(Values); 3916 return false; 3917 } 3918 3919 /// parseDirectiveCFIReturnColumn 3920 /// ::= .cfi_return_column register 3921 bool MasmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) { 3922 int64_t Register = 0; 3923 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3924 return true; 3925 getStreamer().emitCFIReturnColumn(Register); 3926 return false; 3927 } 3928 3929 /// parseDirectiveCFISignalFrame 3930 /// ::= .cfi_signal_frame 3931 bool MasmParser::parseDirectiveCFISignalFrame() { 3932 if (parseToken(AsmToken::EndOfStatement, 3933 "unexpected token in '.cfi_signal_frame'")) 3934 return true; 3935 3936 getStreamer().emitCFISignalFrame(); 3937 return false; 3938 } 3939 3940 /// parseDirectiveCFIUndefined 3941 /// ::= .cfi_undefined register 3942 bool MasmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { 3943 int64_t Register = 0; 3944 3945 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3946 return true; 3947 3948 getStreamer().emitCFIUndefined(Register); 3949 return false; 3950 } 3951 3952 /// parseDirectiveAltmacro 3953 /// ::= .altmacro 3954 /// ::= .noaltmacro 3955 bool MasmParser::parseDirectiveAltmacro(StringRef Directive) { 3956 if (getLexer().isNot(AsmToken::EndOfStatement)) 3957 return TokError("unexpected token in '" + Directive + "' directive"); 3958 AltMacroMode = (Directive == ".altmacro"); 3959 return false; 3960 } 3961 3962 /// parseDirectiveMacrosOnOff 3963 /// ::= .macros_on 3964 /// ::= .macros_off 3965 bool MasmParser::parseDirectiveMacrosOnOff(StringRef Directive) { 3966 if (parseToken(AsmToken::EndOfStatement, 3967 "unexpected token in '" + Directive + "' directive")) 3968 return true; 3969 3970 setMacrosEnabled(Directive == ".macros_on"); 3971 return false; 3972 } 3973 3974 /// parseDirectiveMacro 3975 /// ::= .macro name[,] [parameters] 3976 bool MasmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { 3977 StringRef Name; 3978 if (parseIdentifier(Name)) 3979 return TokError("expected identifier in '.macro' directive"); 3980 3981 if (getLexer().is(AsmToken::Comma)) 3982 Lex(); 3983 3984 MCAsmMacroParameters Parameters; 3985 while (getLexer().isNot(AsmToken::EndOfStatement)) { 3986 3987 if (!Parameters.empty() && Parameters.back().Vararg) 3988 return Error(Lexer.getLoc(), 3989 "Vararg parameter '" + Parameters.back().Name + 3990 "' should be last one in the list of parameters."); 3991 3992 MCAsmMacroParameter Parameter; 3993 if (parseIdentifier(Parameter.Name)) 3994 return TokError("expected identifier in '.macro' directive"); 3995 3996 // Emit an error if two (or more) named parameters share the same name 3997 for (const MCAsmMacroParameter& CurrParam : Parameters) 3998 if (CurrParam.Name.equals(Parameter.Name)) 3999 return TokError("macro '" + Name + "' has multiple parameters" 4000 " named '" + Parameter.Name + "'"); 4001 4002 if (Lexer.is(AsmToken::Colon)) { 4003 Lex(); // consume ':' 4004 4005 SMLoc QualLoc; 4006 StringRef Qualifier; 4007 4008 QualLoc = Lexer.getLoc(); 4009 if (parseIdentifier(Qualifier)) 4010 return Error(QualLoc, "missing parameter qualifier for " 4011 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4012 4013 if (Qualifier == "req") 4014 Parameter.Required = true; 4015 else if (Qualifier == "vararg") 4016 Parameter.Vararg = true; 4017 else 4018 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " 4019 "for '" + Parameter.Name + "' in macro '" + Name + "'"); 4020 } 4021 4022 if (getLexer().is(AsmToken::Equal)) { 4023 Lex(); 4024 4025 SMLoc ParamLoc; 4026 4027 ParamLoc = Lexer.getLoc(); 4028 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) 4029 return true; 4030 4031 if (Parameter.Required) 4032 Warning(ParamLoc, "pointless default value for required parameter " 4033 "'" + Parameter.Name + "' in macro '" + Name + "'"); 4034 } 4035 4036 Parameters.push_back(std::move(Parameter)); 4037 4038 if (getLexer().is(AsmToken::Comma)) 4039 Lex(); 4040 } 4041 4042 // Eat just the end of statement. 4043 Lexer.Lex(); 4044 4045 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors 4046 AsmToken EndToken, StartToken = getTok(); 4047 unsigned MacroDepth = 0; 4048 // Lex the macro definition. 4049 while (true) { 4050 // Ignore Lexing errors in macros. 4051 while (Lexer.is(AsmToken::Error)) { 4052 Lexer.Lex(); 4053 } 4054 4055 // Check whether we have reached the end of the file. 4056 if (getLexer().is(AsmToken::Eof)) 4057 return Error(DirectiveLoc, "no matching '.endmacro' in definition"); 4058 4059 // Otherwise, check whether we have reach the .endmacro. 4060 if (getLexer().is(AsmToken::Identifier)) { 4061 if (getTok().getIdentifier() == ".endm" || 4062 getTok().getIdentifier() == ".endmacro") { 4063 if (MacroDepth == 0) { // Outermost macro. 4064 EndToken = getTok(); 4065 Lexer.Lex(); 4066 if (getLexer().isNot(AsmToken::EndOfStatement)) 4067 return TokError("unexpected token in '" + EndToken.getIdentifier() + 4068 "' directive"); 4069 break; 4070 } else { 4071 // Otherwise we just found the end of an inner macro. 4072 --MacroDepth; 4073 } 4074 } else if (getTok().getIdentifier() == ".macro") { 4075 // We allow nested macros. Those aren't instantiated until the outermost 4076 // macro is expanded so just ignore them for now. 4077 ++MacroDepth; 4078 } 4079 } 4080 4081 // Otherwise, scan til the end of the statement. 4082 eatToEndOfStatement(); 4083 } 4084 4085 if (getContext().lookupMacro(Name)) { 4086 return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); 4087 } 4088 4089 const char *BodyStart = StartToken.getLoc().getPointer(); 4090 const char *BodyEnd = EndToken.getLoc().getPointer(); 4091 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 4092 checkForBadMacro(DirectiveLoc, Name, Body, Parameters); 4093 MCAsmMacro Macro(Name, Body, std::move(Parameters)); 4094 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n"; 4095 Macro.dump()); 4096 getContext().defineMacro(Name, std::move(Macro)); 4097 return false; 4098 } 4099 4100 /// checkForBadMacro 4101 /// 4102 /// With the support added for named parameters there may be code out there that 4103 /// is transitioning from positional parameters. In versions of gas that did 4104 /// not support named parameters they would be ignored on the macro definition. 4105 /// But to support both styles of parameters this is not possible so if a macro 4106 /// definition has named parameters but does not use them and has what appears 4107 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a 4108 /// warning that the positional parameter found in body which have no effect. 4109 /// Hoping the developer will either remove the named parameters from the macro 4110 /// definition so the positional parameters get used if that was what was 4111 /// intended or change the macro to use the named parameters. It is possible 4112 /// this warning will trigger when the none of the named parameters are used 4113 /// and the strings like $1 are infact to simply to be passed trough unchanged. 4114 void MasmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, 4115 StringRef Body, 4116 ArrayRef<MCAsmMacroParameter> Parameters) { 4117 // If this macro is not defined with named parameters the warning we are 4118 // checking for here doesn't apply. 4119 unsigned NParameters = Parameters.size(); 4120 if (NParameters == 0) 4121 return; 4122 4123 bool NamedParametersFound = false; 4124 bool PositionalParametersFound = false; 4125 4126 // Look at the body of the macro for use of both the named parameters and what 4127 // are likely to be positional parameters. This is what expandMacro() is 4128 // doing when it finds the parameters in the body. 4129 while (!Body.empty()) { 4130 // Scan for the next possible parameter. 4131 std::size_t End = Body.size(), Pos = 0; 4132 for (; Pos != End; ++Pos) { 4133 // Check for a substitution or escape. 4134 // This macro is defined with parameters, look for \foo, \bar, etc. 4135 if (Body[Pos] == '\\' && Pos + 1 != End) 4136 break; 4137 4138 // This macro should have parameters, but look for $0, $1, ..., $n too. 4139 if (Body[Pos] != '$' || Pos + 1 == End) 4140 continue; 4141 char Next = Body[Pos + 1]; 4142 if (Next == '$' || Next == 'n' || 4143 isdigit(static_cast<unsigned char>(Next))) 4144 break; 4145 } 4146 4147 // Check if we reached the end. 4148 if (Pos == End) 4149 break; 4150 4151 if (Body[Pos] == '$') { 4152 switch (Body[Pos + 1]) { 4153 // $$ => $ 4154 case '$': 4155 break; 4156 4157 // $n => number of arguments 4158 case 'n': 4159 PositionalParametersFound = true; 4160 break; 4161 4162 // $[0-9] => argument 4163 default: { 4164 PositionalParametersFound = true; 4165 break; 4166 } 4167 } 4168 Pos += 2; 4169 } else { 4170 unsigned I = Pos + 1; 4171 while (isIdentifierChar(Body[I]) && I + 1 != End) 4172 ++I; 4173 4174 const char *Begin = Body.data() + Pos + 1; 4175 StringRef Argument(Begin, I - (Pos + 1)); 4176 unsigned Index = 0; 4177 for (; Index < NParameters; ++Index) 4178 if (Parameters[Index].Name == Argument) 4179 break; 4180 4181 if (Index == NParameters) { 4182 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 4183 Pos += 3; 4184 else { 4185 Pos = I; 4186 } 4187 } else { 4188 NamedParametersFound = true; 4189 Pos += 1 + Argument.size(); 4190 } 4191 } 4192 // Update the scan point. 4193 Body = Body.substr(Pos); 4194 } 4195 4196 if (!NamedParametersFound && PositionalParametersFound) 4197 Warning(DirectiveLoc, "macro defined with named parameters which are not " 4198 "used in macro body, possible positional parameter " 4199 "found in body which will have no effect"); 4200 } 4201 4202 /// parseDirectiveExitMacro 4203 /// ::= .exitm 4204 bool MasmParser::parseDirectiveExitMacro(StringRef Directive) { 4205 if (parseToken(AsmToken::EndOfStatement, 4206 "unexpected token in '" + Directive + "' directive")) 4207 return true; 4208 4209 if (!isInsideMacroInstantiation()) 4210 return TokError("unexpected '" + Directive + "' in file, " 4211 "no current macro definition"); 4212 4213 // Exit all conditionals that are active in the current macro. 4214 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { 4215 TheCondState = TheCondStack.back(); 4216 TheCondStack.pop_back(); 4217 } 4218 4219 handleMacroExit(); 4220 return false; 4221 } 4222 4223 /// parseDirectiveEndMacro 4224 /// ::= .endm 4225 /// ::= .endmacro 4226 bool MasmParser::parseDirectiveEndMacro(StringRef Directive) { 4227 if (getLexer().isNot(AsmToken::EndOfStatement)) 4228 return TokError("unexpected token in '" + Directive + "' directive"); 4229 4230 // If we are inside a macro instantiation, terminate the current 4231 // instantiation. 4232 if (isInsideMacroInstantiation()) { 4233 handleMacroExit(); 4234 return false; 4235 } 4236 4237 // Otherwise, this .endmacro is a stray entry in the file; well formed 4238 // .endmacro directives are handled during the macro definition parsing. 4239 return TokError("unexpected '" + Directive + "' in file, " 4240 "no current macro definition"); 4241 } 4242 4243 /// parseDirectivePurgeMacro 4244 /// ::= .purgem 4245 bool MasmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { 4246 StringRef Name; 4247 SMLoc Loc; 4248 if (parseTokenLoc(Loc) || 4249 check(parseIdentifier(Name), Loc, 4250 "expected identifier in '.purgem' directive") || 4251 parseToken(AsmToken::EndOfStatement, 4252 "unexpected token in '.purgem' directive")) 4253 return true; 4254 4255 if (!getContext().lookupMacro(Name)) 4256 return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); 4257 4258 getContext().undefineMacro(Name); 4259 DEBUG_WITH_TYPE("asm-macros", dbgs() 4260 << "Un-defining macro: " << Name << "\n"); 4261 return false; 4262 } 4263 4264 /// parseDirectiveSymbolAttribute 4265 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] 4266 bool MasmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { 4267 auto parseOp = [&]() -> bool { 4268 StringRef Name; 4269 SMLoc Loc = getTok().getLoc(); 4270 if (parseIdentifier(Name)) 4271 return Error(Loc, "expected identifier"); 4272 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4273 4274 // Assembler local symbols don't make any sense here. Complain loudly. 4275 if (Sym->isTemporary()) 4276 return Error(Loc, "non-local symbol required"); 4277 4278 if (!getStreamer().emitSymbolAttribute(Sym, Attr)) 4279 return Error(Loc, "unable to emit symbol attribute"); 4280 return false; 4281 }; 4282 4283 if (parseMany(parseOp)) 4284 return addErrorSuffix(" in directive"); 4285 return false; 4286 } 4287 4288 /// parseDirectiveComm 4289 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] 4290 bool MasmParser::parseDirectiveComm(bool IsLocal) { 4291 if (checkForValidSection()) 4292 return true; 4293 4294 SMLoc IDLoc = getLexer().getLoc(); 4295 StringRef Name; 4296 if (parseIdentifier(Name)) 4297 return TokError("expected identifier in directive"); 4298 4299 // Handle the identifier as the key symbol. 4300 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4301 4302 if (getLexer().isNot(AsmToken::Comma)) 4303 return TokError("unexpected token in directive"); 4304 Lex(); 4305 4306 int64_t Size; 4307 SMLoc SizeLoc = getLexer().getLoc(); 4308 if (parseAbsoluteExpression(Size)) 4309 return true; 4310 4311 int64_t Pow2Alignment = 0; 4312 SMLoc Pow2AlignmentLoc; 4313 if (getLexer().is(AsmToken::Comma)) { 4314 Lex(); 4315 Pow2AlignmentLoc = getLexer().getLoc(); 4316 if (parseAbsoluteExpression(Pow2Alignment)) 4317 return true; 4318 4319 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); 4320 if (IsLocal && LCOMM == LCOMM::NoAlignment) 4321 return Error(Pow2AlignmentLoc, "alignment not supported on this target"); 4322 4323 // If this target takes alignments in bytes (not log) validate and convert. 4324 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || 4325 (IsLocal && LCOMM == LCOMM::ByteAlignment)) { 4326 if (!isPowerOf2_64(Pow2Alignment)) 4327 return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); 4328 Pow2Alignment = Log2_64(Pow2Alignment); 4329 } 4330 } 4331 4332 if (parseToken(AsmToken::EndOfStatement, 4333 "unexpected token in '.comm' or '.lcomm' directive")) 4334 return true; 4335 4336 // NOTE: a size of zero for a .comm should create a undefined symbol 4337 // but a size of .lcomm creates a bss symbol of size zero. 4338 if (Size < 0) 4339 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " 4340 "be less than zero"); 4341 4342 // NOTE: The alignment in the directive is a power of 2 value, the assembler 4343 // may internally end up wanting an alignment in bytes. 4344 // FIXME: Diagnose overflow. 4345 if (Pow2Alignment < 0) 4346 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " 4347 "alignment, can't be less than zero"); 4348 4349 Sym->redefineIfPossible(); 4350 if (!Sym->isUndefined()) 4351 return Error(IDLoc, "invalid symbol redefinition"); 4352 4353 // Create the Symbol as a common or local common with Size and Pow2Alignment 4354 if (IsLocal) { 4355 getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4356 return false; 4357 } 4358 4359 getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment); 4360 return false; 4361 } 4362 4363 /// parseDirectiveComment 4364 /// ::= comment delimiter [[text]] 4365 /// [[text]] 4366 /// [[text]] delimiter [[text]] 4367 bool MasmParser::parseDirectiveComment(SMLoc DirectiveLoc) { 4368 StringRef FirstLine = parseStringToEndOfStatement(); 4369 size_t DelimiterEnd = FirstLine.find_first_of("\b\t\v\f\r\x1A "); 4370 StringRef Delimiter = FirstLine.take_front(DelimiterEnd); 4371 if (Delimiter.empty()) 4372 return Error(DirectiveLoc, "no delimiter in 'comment' directive"); 4373 do { 4374 if (getTok().is(AsmToken::Eof)) 4375 return Error(DirectiveLoc, "unmatched delimiter in 'comment' directive"); 4376 Lex(); // eat end of statement 4377 } while (!parseStringToEndOfStatement().contains(Delimiter)); 4378 return parseToken(AsmToken::EndOfStatement, 4379 "unexpected token in 'comment' directive"); 4380 } 4381 4382 /// parseDirectiveInclude 4383 /// ::= include <filename> 4384 /// | include filename 4385 bool MasmParser::parseDirectiveInclude() { 4386 // Allow the strings to have escaped octal character sequence. 4387 std::string Filename; 4388 SMLoc IncludeLoc = getTok().getLoc(); 4389 4390 if (!parseAngleBracketString(Filename)) 4391 Filename = parseStringToEndOfStatement().str(); 4392 if (check(!Filename.empty(), "missing filename in 'include' directive") || 4393 check(getTok().isNot(AsmToken::EndOfStatement), 4394 "unexpected token in 'include' directive") || 4395 // Attempt to switch the lexer to the included file before consuming the 4396 // end of statement to avoid losing it when we switch. 4397 check(enterIncludeFile(Filename), IncludeLoc, 4398 "Could not find include file '" + Filename + "'")) 4399 return true; 4400 4401 return false; 4402 } 4403 4404 /// parseDirectiveIf 4405 /// ::= .if{,eq,ge,gt,le,lt,ne} expression 4406 bool MasmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { 4407 TheCondStack.push_back(TheCondState); 4408 TheCondState.TheCond = AsmCond::IfCond; 4409 if (TheCondState.Ignore) { 4410 eatToEndOfStatement(); 4411 } else { 4412 int64_t ExprValue; 4413 if (parseAbsoluteExpression(ExprValue) || 4414 parseToken(AsmToken::EndOfStatement, 4415 "unexpected token in '.if' directive")) 4416 return true; 4417 4418 switch (DirKind) { 4419 default: 4420 llvm_unreachable("unsupported directive"); 4421 case DK_IF: 4422 break; 4423 case DK_IFE: 4424 ExprValue = ExprValue == 0; 4425 break; 4426 } 4427 4428 TheCondState.CondMet = ExprValue; 4429 TheCondState.Ignore = !TheCondState.CondMet; 4430 } 4431 4432 return false; 4433 } 4434 4435 /// parseDirectiveIfb 4436 /// ::= .ifb string 4437 bool MasmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 4438 TheCondStack.push_back(TheCondState); 4439 TheCondState.TheCond = AsmCond::IfCond; 4440 4441 if (TheCondState.Ignore) { 4442 eatToEndOfStatement(); 4443 } else { 4444 std::string Str; 4445 if (parseTextItem(Str)) 4446 return TokError("expected string parameter for 'ifb' directive"); 4447 4448 if (parseToken(AsmToken::EndOfStatement, 4449 "unexpected token in 'ifb' directive")) 4450 return true; 4451 4452 TheCondState.CondMet = ExpectBlank == Str.empty(); 4453 TheCondState.Ignore = !TheCondState.CondMet; 4454 } 4455 4456 return false; 4457 } 4458 4459 /// parseDirectiveIfidn 4460 /// ::= ifidn string1, string2 4461 bool MasmParser::parseDirectiveIfidn(SMLoc DirectiveLoc, bool ExpectEqual, bool CaseInsensitive) { 4462 std::string String1, String2; 4463 4464 if (parseTextItem(String1)) { 4465 if (ExpectEqual) 4466 return TokError("expected string parameter for 'ifidn' directive"); 4467 return TokError("expected string parameter for 'ifdif' directive"); 4468 } 4469 4470 if (Lexer.isNot(AsmToken::Comma)) { 4471 if (ExpectEqual) 4472 return TokError( 4473 "expected comma after first string for 'ifidn' directive"); 4474 return TokError("expected comma after first string for 'ifdif' directive"); 4475 } 4476 Lex(); 4477 4478 if (parseTextItem(String2)) { 4479 if (ExpectEqual) 4480 return TokError("expected string parameter for 'ifidn' directive"); 4481 return TokError("expected string parameter for 'ifdif' directive"); 4482 } 4483 4484 TheCondStack.push_back(TheCondState); 4485 TheCondState.TheCond = AsmCond::IfCond; 4486 if (CaseInsensitive) 4487 TheCondState.CondMet = 4488 ExpectEqual == (StringRef(String1).equals_lower(String2)); 4489 else 4490 TheCondState.CondMet = ExpectEqual == (String1 == String2); 4491 TheCondState.Ignore = !TheCondState.CondMet; 4492 4493 return false; 4494 } 4495 4496 /// parseDirectiveIfdef 4497 /// ::= ifdef symbol 4498 /// | ifdef variable 4499 bool MasmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { 4500 TheCondStack.push_back(TheCondState); 4501 TheCondState.TheCond = AsmCond::IfCond; 4502 4503 if (TheCondState.Ignore) { 4504 eatToEndOfStatement(); 4505 } else { 4506 bool is_defined = false; 4507 unsigned RegNo; 4508 SMLoc StartLoc, EndLoc; 4509 is_defined = (getTargetParser().tryParseRegister( 4510 RegNo, StartLoc, EndLoc) == MatchOperand_Success); 4511 if (!is_defined) { 4512 StringRef Name; 4513 if (check(parseIdentifier(Name), "expected identifier after 'ifdef'") || 4514 parseToken(AsmToken::EndOfStatement, "unexpected token in 'ifdef'")) 4515 return true; 4516 4517 if (Variables.find(Name) != Variables.end()) { 4518 is_defined = true; 4519 } else { 4520 MCSymbol *Sym = getContext().lookupSymbol(Name); 4521 is_defined = (Sym && !Sym->isUndefined(false)); 4522 } 4523 } 4524 4525 TheCondState.CondMet = (is_defined == expect_defined); 4526 TheCondState.Ignore = !TheCondState.CondMet; 4527 } 4528 4529 return false; 4530 } 4531 4532 /// parseDirectiveElseIf 4533 /// ::= elseif expression 4534 bool MasmParser::parseDirectiveElseIf(SMLoc DirectiveLoc, 4535 DirectiveKind DirKind) { 4536 if (TheCondState.TheCond != AsmCond::IfCond && 4537 TheCondState.TheCond != AsmCond::ElseIfCond) 4538 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an" 4539 " .if or an .elseif"); 4540 TheCondState.TheCond = AsmCond::ElseIfCond; 4541 4542 bool LastIgnoreState = false; 4543 if (!TheCondStack.empty()) 4544 LastIgnoreState = TheCondStack.back().Ignore; 4545 if (LastIgnoreState || TheCondState.CondMet) { 4546 TheCondState.Ignore = true; 4547 eatToEndOfStatement(); 4548 } else { 4549 int64_t ExprValue; 4550 if (parseAbsoluteExpression(ExprValue)) 4551 return true; 4552 4553 if (parseToken(AsmToken::EndOfStatement, 4554 "unexpected token in '.elseif' directive")) 4555 return true; 4556 4557 switch (DirKind) { 4558 default: 4559 llvm_unreachable("unsupported directive"); 4560 case DK_ELSEIF: 4561 break; 4562 case DK_ELSEIFE: 4563 ExprValue = ExprValue == 0; 4564 break; 4565 } 4566 4567 TheCondState.CondMet = ExprValue; 4568 TheCondState.Ignore = !TheCondState.CondMet; 4569 } 4570 4571 return false; 4572 } 4573 4574 /// parseDirectiveElseIfb 4575 /// ::= elseifb expression 4576 bool MasmParser::parseDirectiveElseIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 4577 if (TheCondState.TheCond != AsmCond::IfCond && 4578 TheCondState.TheCond != AsmCond::ElseIfCond) 4579 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 4580 " if or an elseif"); 4581 TheCondState.TheCond = AsmCond::ElseIfCond; 4582 4583 bool LastIgnoreState = false; 4584 if (!TheCondStack.empty()) 4585 LastIgnoreState = TheCondStack.back().Ignore; 4586 if (LastIgnoreState || TheCondState.CondMet) { 4587 TheCondState.Ignore = true; 4588 eatToEndOfStatement(); 4589 } else { 4590 std::string Str; 4591 if (parseTextItem(Str)) 4592 return TokError("expected string parameter for 'elseifb' directive"); 4593 4594 if (parseToken(AsmToken::EndOfStatement, 4595 "unexpected token in 'elseifb' directive")) 4596 return true; 4597 4598 TheCondState.CondMet = ExpectBlank == Str.empty(); 4599 TheCondState.Ignore = !TheCondState.CondMet; 4600 } 4601 4602 return false; 4603 } 4604 4605 /// parseDirectiveElseIfdef 4606 /// ::= elseifdef symbol 4607 /// | elseifdef variable 4608 bool MasmParser::parseDirectiveElseIfdef(SMLoc DirectiveLoc, 4609 bool expect_defined) { 4610 if (TheCondState.TheCond != AsmCond::IfCond && 4611 TheCondState.TheCond != AsmCond::ElseIfCond) 4612 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 4613 " if or an elseif"); 4614 TheCondState.TheCond = AsmCond::ElseIfCond; 4615 4616 bool LastIgnoreState = false; 4617 if (!TheCondStack.empty()) 4618 LastIgnoreState = TheCondStack.back().Ignore; 4619 if (LastIgnoreState || TheCondState.CondMet) { 4620 TheCondState.Ignore = true; 4621 eatToEndOfStatement(); 4622 } else { 4623 bool is_defined = false; 4624 unsigned RegNo; 4625 SMLoc StartLoc, EndLoc; 4626 is_defined = (getTargetParser().tryParseRegister(RegNo, StartLoc, EndLoc) == 4627 MatchOperand_Success); 4628 if (!is_defined) { 4629 StringRef Name; 4630 if (check(parseIdentifier(Name), 4631 "expected identifier after 'elseifdef'") || 4632 parseToken(AsmToken::EndOfStatement, 4633 "unexpected token in 'elseifdef'")) 4634 return true; 4635 4636 if (Variables.find(Name) != Variables.end()) { 4637 is_defined = true; 4638 } else { 4639 MCSymbol *Sym = getContext().lookupSymbol(Name); 4640 is_defined = (Sym && !Sym->isUndefined(false)); 4641 } 4642 } 4643 4644 TheCondState.CondMet = (is_defined == expect_defined); 4645 TheCondState.Ignore = !TheCondState.CondMet; 4646 } 4647 4648 return false; 4649 } 4650 4651 /// parseDirectiveElseIfidn 4652 /// ::= elseifidn string1, string2 4653 bool MasmParser::parseDirectiveElseIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 4654 bool CaseInsensitive) { 4655 if (TheCondState.TheCond != AsmCond::IfCond && 4656 TheCondState.TheCond != AsmCond::ElseIfCond) 4657 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 4658 " if or an elseif"); 4659 TheCondState.TheCond = AsmCond::ElseIfCond; 4660 4661 bool LastIgnoreState = false; 4662 if (!TheCondStack.empty()) 4663 LastIgnoreState = TheCondStack.back().Ignore; 4664 if (LastIgnoreState || TheCondState.CondMet) { 4665 TheCondState.Ignore = true; 4666 eatToEndOfStatement(); 4667 } else { 4668 std::string String1, String2; 4669 4670 if (parseTextItem(String1)) { 4671 if (ExpectEqual) 4672 return TokError("expected string parameter for 'elseifidn' directive"); 4673 return TokError("expected string parameter for 'elseifdif' directive"); 4674 } 4675 4676 if (Lexer.isNot(AsmToken::Comma)) { 4677 if (ExpectEqual) 4678 return TokError( 4679 "expected comma after first string for 'elseifidn' directive"); 4680 return TokError( 4681 "expected comma after first string for 'elseifdif' directive"); 4682 } 4683 Lex(); 4684 4685 if (parseTextItem(String2)) { 4686 if (ExpectEqual) 4687 return TokError("expected string parameter for 'elseifidn' directive"); 4688 return TokError("expected string parameter for 'elseifdif' directive"); 4689 } 4690 4691 if (CaseInsensitive) 4692 TheCondState.CondMet = 4693 ExpectEqual == (StringRef(String1).equals_lower(String2)); 4694 else 4695 TheCondState.CondMet = ExpectEqual == (String1 == String2); 4696 TheCondState.Ignore = !TheCondState.CondMet; 4697 } 4698 4699 return false; 4700 } 4701 4702 /// parseDirectiveElse 4703 /// ::= else 4704 bool MasmParser::parseDirectiveElse(SMLoc DirectiveLoc) { 4705 if (parseToken(AsmToken::EndOfStatement, 4706 "unexpected token in 'else' directive")) 4707 return true; 4708 4709 if (TheCondState.TheCond != AsmCond::IfCond && 4710 TheCondState.TheCond != AsmCond::ElseIfCond) 4711 return Error(DirectiveLoc, "Encountered an else that doesn't follow an if" 4712 " or an elseif"); 4713 TheCondState.TheCond = AsmCond::ElseCond; 4714 bool LastIgnoreState = false; 4715 if (!TheCondStack.empty()) 4716 LastIgnoreState = TheCondStack.back().Ignore; 4717 if (LastIgnoreState || TheCondState.CondMet) 4718 TheCondState.Ignore = true; 4719 else 4720 TheCondState.Ignore = false; 4721 4722 return false; 4723 } 4724 4725 /// parseDirectiveEnd 4726 /// ::= end 4727 bool MasmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { 4728 if (parseToken(AsmToken::EndOfStatement, 4729 "unexpected token in 'end' directive")) 4730 return true; 4731 4732 while (Lexer.isNot(AsmToken::Eof)) 4733 Lexer.Lex(); 4734 4735 return false; 4736 } 4737 4738 /// parseDirectiveError 4739 /// ::= .err [message] 4740 bool MasmParser::parseDirectiveError(SMLoc DirectiveLoc) { 4741 if (!TheCondStack.empty()) { 4742 if (TheCondStack.back().Ignore) { 4743 eatToEndOfStatement(); 4744 return false; 4745 } 4746 } 4747 4748 StringRef Message = ".err directive invoked in source file"; 4749 if (Lexer.isNot(AsmToken::EndOfStatement)) 4750 Message = parseStringToEndOfStatement(); 4751 Lex(); 4752 4753 return Error(DirectiveLoc, Message); 4754 } 4755 4756 /// parseDirectiveErrorIfb 4757 /// ::= .errb textitem[, message] 4758 bool MasmParser::parseDirectiveErrorIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 4759 if (!TheCondStack.empty()) { 4760 if (TheCondStack.back().Ignore) { 4761 eatToEndOfStatement(); 4762 return false; 4763 } 4764 } 4765 4766 std::string Text; 4767 if (parseTextItem(Text)) 4768 return Error(getTok().getLoc(), "missing text item in '.errb' directive"); 4769 4770 StringRef Message = ".errb directive invoked in source file"; 4771 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4772 if (parseToken(AsmToken::Comma)) 4773 return addErrorSuffix(" in '.errb' directive"); 4774 Message = parseStringToEndOfStatement(); 4775 } 4776 Lex(); 4777 4778 if (Text.empty() == ExpectBlank) 4779 return Error(DirectiveLoc, Message); 4780 return false; 4781 } 4782 4783 /// parseDirectiveErrorIfdef 4784 /// ::= .errdef name[, message] 4785 bool MasmParser::parseDirectiveErrorIfdef(SMLoc DirectiveLoc, 4786 bool ExpectDefined) { 4787 if (!TheCondStack.empty()) { 4788 if (TheCondStack.back().Ignore) { 4789 eatToEndOfStatement(); 4790 return false; 4791 } 4792 } 4793 4794 bool IsDefined = false; 4795 unsigned RegNo; 4796 SMLoc StartLoc, EndLoc; 4797 IsDefined = (getTargetParser().tryParseRegister(RegNo, StartLoc, EndLoc) == 4798 MatchOperand_Success); 4799 if (!IsDefined) { 4800 StringRef Name; 4801 if (check(parseIdentifier(Name), "expected identifier after '.errdef'")) 4802 return true; 4803 4804 if (Variables.find(Name) != Variables.end()) { 4805 IsDefined = true; 4806 } else { 4807 MCSymbol *Sym = getContext().lookupSymbol(Name); 4808 IsDefined = (Sym && !Sym->isUndefined(false)); 4809 } 4810 } 4811 4812 StringRef Message = ".errdef directive invoked in source file"; 4813 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4814 if (parseToken(AsmToken::Comma)) 4815 return addErrorSuffix(" in '.errdef' directive"); 4816 Message = parseStringToEndOfStatement(); 4817 } 4818 Lex(); 4819 4820 if (IsDefined == ExpectDefined) 4821 return Error(DirectiveLoc, Message); 4822 return false; 4823 } 4824 4825 /// parseDirectiveErrorIfidn 4826 /// ::= .erridn textitem1, textitem2[, message] 4827 bool MasmParser::parseDirectiveErrorIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 4828 bool CaseInsensitive) { 4829 if (!TheCondStack.empty()) { 4830 if (TheCondStack.back().Ignore) { 4831 eatToEndOfStatement(); 4832 return false; 4833 } 4834 } 4835 4836 std::string String1, String2; 4837 4838 if (parseTextItem(String1)) { 4839 if (ExpectEqual) 4840 return TokError("expected string parameter for '.erridn' directive"); 4841 return TokError("expected string parameter for '.errdif' directive"); 4842 } 4843 4844 if (Lexer.isNot(AsmToken::Comma)) { 4845 if (ExpectEqual) 4846 return TokError( 4847 "expected comma after first string for '.erridn' directive"); 4848 return TokError( 4849 "expected comma after first string for '.errdif' directive"); 4850 } 4851 Lex(); 4852 4853 if (parseTextItem(String2)) { 4854 if (ExpectEqual) 4855 return TokError("expected string parameter for '.erridn' directive"); 4856 return TokError("expected string parameter for '.errdif' directive"); 4857 } 4858 4859 StringRef Message; 4860 if (ExpectEqual) 4861 Message = ".erridn directive invoked in source file"; 4862 else 4863 Message = ".errdif directive invoked in source file"; 4864 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4865 if (parseToken(AsmToken::Comma)) 4866 return addErrorSuffix(" in '.erridn' directive"); 4867 Message = parseStringToEndOfStatement(); 4868 } 4869 Lex(); 4870 4871 if (CaseInsensitive) 4872 TheCondState.CondMet = 4873 ExpectEqual == (StringRef(String1).equals_lower(String2)); 4874 else 4875 TheCondState.CondMet = ExpectEqual == (String1 == String2); 4876 TheCondState.Ignore = !TheCondState.CondMet; 4877 4878 if ((CaseInsensitive && 4879 ExpectEqual == StringRef(String1).equals_lower(String2)) || 4880 (ExpectEqual == (String1 == String2))) 4881 return Error(DirectiveLoc, Message); 4882 return false; 4883 } 4884 4885 /// parseDirectiveErrorIfe 4886 /// ::= .erre expression[, message] 4887 bool MasmParser::parseDirectiveErrorIfe(SMLoc DirectiveLoc, bool ExpectZero) { 4888 if (!TheCondStack.empty()) { 4889 if (TheCondStack.back().Ignore) { 4890 eatToEndOfStatement(); 4891 return false; 4892 } 4893 } 4894 4895 int64_t ExprValue; 4896 if (parseAbsoluteExpression(ExprValue)) 4897 return addErrorSuffix(" in '.erre' directive"); 4898 4899 StringRef Message = ".erre directive invoked in source file"; 4900 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4901 if (parseToken(AsmToken::Comma)) 4902 return addErrorSuffix(" in '.erre' directive"); 4903 Message = parseStringToEndOfStatement(); 4904 } 4905 Lex(); 4906 4907 if ((ExprValue == 0) == ExpectZero) 4908 return Error(DirectiveLoc, Message); 4909 return false; 4910 } 4911 4912 /// parseDirectiveEndIf 4913 /// ::= .endif 4914 bool MasmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { 4915 if (parseToken(AsmToken::EndOfStatement, 4916 "unexpected token in '.endif' directive")) 4917 return true; 4918 4919 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) 4920 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow " 4921 "an .if or .else"); 4922 if (!TheCondStack.empty()) { 4923 TheCondState = TheCondStack.back(); 4924 TheCondStack.pop_back(); 4925 } 4926 4927 return false; 4928 } 4929 4930 void MasmParser::initializeDirectiveKindMap() { 4931 DirectiveKindMap["="] = DK_ASSIGN; 4932 DirectiveKindMap["equ"] = DK_EQU; 4933 DirectiveKindMap["textequ"] = DK_TEXTEQU; 4934 // DirectiveKindMap[".ascii"] = DK_ASCII; 4935 // DirectiveKindMap[".asciz"] = DK_ASCIZ; 4936 // DirectiveKindMap[".string"] = DK_STRING; 4937 DirectiveKindMap["byte"] = DK_BYTE; 4938 DirectiveKindMap["sbyte"] = DK_SBYTE; 4939 DirectiveKindMap["word"] = DK_WORD; 4940 DirectiveKindMap["sword"] = DK_SWORD; 4941 DirectiveKindMap["dword"] = DK_DWORD; 4942 DirectiveKindMap["sdword"] = DK_SDWORD; 4943 DirectiveKindMap["fword"] = DK_FWORD; 4944 DirectiveKindMap["qword"] = DK_QWORD; 4945 DirectiveKindMap["sqword"] = DK_SQWORD; 4946 DirectiveKindMap["real4"] = DK_REAL4; 4947 DirectiveKindMap["real8"] = DK_REAL8; 4948 DirectiveKindMap["align"] = DK_ALIGN; 4949 // DirectiveKindMap[".org"] = DK_ORG; 4950 DirectiveKindMap["extern"] = DK_EXTERN; 4951 DirectiveKindMap["public"] = DK_PUBLIC; 4952 // DirectiveKindMap[".comm"] = DK_COMM; 4953 DirectiveKindMap["comment"] = DK_COMMENT; 4954 DirectiveKindMap["include"] = DK_INCLUDE; 4955 // DirectiveKindMap[".rept"] = DK_REPT; 4956 // DirectiveKindMap[".rep"] = DK_REPT; 4957 // DirectiveKindMap[".irp"] = DK_IRP; 4958 // DirectiveKindMap[".irpc"] = DK_IRPC; 4959 // DirectiveKindMap[".endr"] = DK_ENDR; 4960 DirectiveKindMap["if"] = DK_IF; 4961 DirectiveKindMap["ife"] = DK_IFE; 4962 DirectiveKindMap["ifb"] = DK_IFB; 4963 DirectiveKindMap["ifnb"] = DK_IFNB; 4964 DirectiveKindMap["ifdef"] = DK_IFDEF; 4965 DirectiveKindMap["ifndef"] = DK_IFNDEF; 4966 DirectiveKindMap["ifdif"] = DK_IFDIF; 4967 DirectiveKindMap["ifdifi"] = DK_IFDIFI; 4968 DirectiveKindMap["ifidn"] = DK_IFIDN; 4969 DirectiveKindMap["ifidni"] = DK_IFIDNI; 4970 DirectiveKindMap["elseif"] = DK_ELSEIF; 4971 DirectiveKindMap["elseifdef"] = DK_ELSEIFDEF; 4972 DirectiveKindMap["elseifndef"] = DK_ELSEIFNDEF; 4973 DirectiveKindMap["elseifdif"] = DK_ELSEIFDIF; 4974 DirectiveKindMap["elseifidn"] = DK_ELSEIFIDN; 4975 DirectiveKindMap["else"] = DK_ELSE; 4976 DirectiveKindMap["end"] = DK_END; 4977 DirectiveKindMap["endif"] = DK_ENDIF; 4978 // DirectiveKindMap[".file"] = DK_FILE; 4979 // DirectiveKindMap[".line"] = DK_LINE; 4980 // DirectiveKindMap[".loc"] = DK_LOC; 4981 // DirectiveKindMap[".stabs"] = DK_STABS; 4982 // DirectiveKindMap[".cv_file"] = DK_CV_FILE; 4983 // DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID; 4984 // DirectiveKindMap[".cv_loc"] = DK_CV_LOC; 4985 // DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE; 4986 // DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE; 4987 // DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID; 4988 // DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE; 4989 // DirectiveKindMap[".cv_string"] = DK_CV_STRING; 4990 // DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE; 4991 // DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS; 4992 // DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET; 4993 // DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA; 4994 // DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; 4995 // DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; 4996 // DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; 4997 // DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; 4998 // DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; 4999 // DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; 5000 // DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; 5001 // DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; 5002 // DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; 5003 // DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; 5004 // DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; 5005 // DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; 5006 // DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; 5007 // DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; 5008 // DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; 5009 // DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; 5010 // DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN; 5011 // DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; 5012 // DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; 5013 // DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; 5014 // DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; 5015 // DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME; 5016 // DirectiveKindMap[".macro"] = DK_MACRO; 5017 // DirectiveKindMap[".exitm"] = DK_EXITM; 5018 // DirectiveKindMap[".endm"] = DK_ENDM; 5019 // DirectiveKindMap[".purgem"] = DK_PURGEM; 5020 DirectiveKindMap[".err"] = DK_ERR; 5021 DirectiveKindMap[".errb"] = DK_ERRB; 5022 DirectiveKindMap[".errnb"] = DK_ERRNB; 5023 DirectiveKindMap[".errdef"] = DK_ERRDEF; 5024 DirectiveKindMap[".errndef"] = DK_ERRNDEF; 5025 DirectiveKindMap[".errdif"] = DK_ERRDIF; 5026 DirectiveKindMap[".errdifi"] = DK_ERRDIFI; 5027 DirectiveKindMap[".erridn"] = DK_ERRIDN; 5028 DirectiveKindMap[".erridni"] = DK_ERRIDNI; 5029 DirectiveKindMap[".erre"] = DK_ERRE; 5030 DirectiveKindMap[".errnz"] = DK_ERRNZ; 5031 // DirectiveKindMap[".altmacro"] = DK_ALTMACRO; 5032 // DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO; 5033 DirectiveKindMap["db"] = DK_DB; 5034 DirectiveKindMap["dd"] = DK_DD; 5035 DirectiveKindMap["dq"] = DK_DQ; 5036 DirectiveKindMap["dw"] = DK_DW; 5037 DirectiveKindMap["echo"] = DK_ECHO; 5038 } 5039 5040 MCAsmMacro *MasmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { 5041 AsmToken EndToken, StartToken = getTok(); 5042 5043 unsigned NestLevel = 0; 5044 while (true) { 5045 // Check whether we have reached the end of the file. 5046 if (getLexer().is(AsmToken::Eof)) { 5047 printError(DirectiveLoc, "no matching '.endr' in definition"); 5048 return nullptr; 5049 } 5050 5051 if (Lexer.is(AsmToken::Identifier) && 5052 (getTok().getIdentifier() == ".rep" || 5053 getTok().getIdentifier() == ".rept" || 5054 getTok().getIdentifier() == ".irp" || 5055 getTok().getIdentifier() == ".irpc")) { 5056 ++NestLevel; 5057 } 5058 5059 // Otherwise, check whether we have reached the .endr. 5060 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { 5061 if (NestLevel == 0) { 5062 EndToken = getTok(); 5063 Lex(); 5064 if (Lexer.isNot(AsmToken::EndOfStatement)) { 5065 printError(getTok().getLoc(), 5066 "unexpected token in '.endr' directive"); 5067 return nullptr; 5068 } 5069 break; 5070 } 5071 --NestLevel; 5072 } 5073 5074 // Otherwise, scan till the end of the statement. 5075 eatToEndOfStatement(); 5076 } 5077 5078 const char *BodyStart = StartToken.getLoc().getPointer(); 5079 const char *BodyEnd = EndToken.getLoc().getPointer(); 5080 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 5081 5082 // We Are Anonymous. 5083 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); 5084 return &MacroLikeBodies.back(); 5085 } 5086 5087 void MasmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 5088 raw_svector_ostream &OS) { 5089 OS << ".endr\n"; 5090 5091 std::unique_ptr<MemoryBuffer> Instantiation = 5092 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 5093 5094 // Create the macro instantiation object and add to the current macro 5095 // instantiation stack. 5096 MacroInstantiation *MI = new MacroInstantiation{ 5097 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 5098 ActiveMacros.push_back(MI); 5099 5100 // Jump to the macro instantiation and prime the lexer. 5101 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 5102 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 5103 Lex(); 5104 } 5105 5106 /// parseDirectiveRept 5107 /// ::= .rep | .rept count 5108 bool MasmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { 5109 const MCExpr *CountExpr; 5110 SMLoc CountLoc = getTok().getLoc(); 5111 if (parseExpression(CountExpr)) 5112 return true; 5113 5114 int64_t Count; 5115 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) { 5116 return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); 5117 } 5118 5119 if (check(Count < 0, CountLoc, "Count is negative") || 5120 parseToken(AsmToken::EndOfStatement, 5121 "unexpected token in '" + Dir + "' directive")) 5122 return true; 5123 5124 // Lex the rept definition. 5125 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5126 if (!M) 5127 return true; 5128 5129 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5130 // to hold the macro body with substitutions. 5131 SmallString<256> Buf; 5132 raw_svector_ostream OS(Buf); 5133 while (Count--) { 5134 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t). 5135 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) 5136 return true; 5137 } 5138 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5139 5140 return false; 5141 } 5142 5143 /// parseDirectiveIrp 5144 /// ::= .irp symbol,values 5145 bool MasmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { 5146 MCAsmMacroParameter Parameter; 5147 MCAsmMacroArguments A; 5148 if (check(parseIdentifier(Parameter.Name), 5149 "expected identifier in '.irp' directive") || 5150 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") || 5151 parseMacroArguments(nullptr, A) || 5152 parseToken(AsmToken::EndOfStatement, "expected End of Statement")) 5153 return true; 5154 5155 // Lex the irp definition. 5156 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5157 if (!M) 5158 return true; 5159 5160 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5161 // to hold the macro body with substitutions. 5162 SmallString<256> Buf; 5163 raw_svector_ostream OS(Buf); 5164 5165 for (const MCAsmMacroArgument &Arg : A) { 5166 // Note that the AtPseudoVariable is enabled for instantiations of .irp. 5167 // This is undocumented, but GAS seems to support it. 5168 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5169 return true; 5170 } 5171 5172 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5173 5174 return false; 5175 } 5176 5177 /// parseDirectiveIrpc 5178 /// ::= .irpc symbol,values 5179 bool MasmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { 5180 MCAsmMacroParameter Parameter; 5181 MCAsmMacroArguments A; 5182 5183 if (check(parseIdentifier(Parameter.Name), 5184 "expected identifier in '.irpc' directive") || 5185 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") || 5186 parseMacroArguments(nullptr, A)) 5187 return true; 5188 5189 if (A.size() != 1 || A.front().size() != 1) 5190 return TokError("unexpected token in '.irpc' directive"); 5191 5192 // Eat the end of statement. 5193 if (parseToken(AsmToken::EndOfStatement, "expected end of statement")) 5194 return true; 5195 5196 // Lex the irpc definition. 5197 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 5198 if (!M) 5199 return true; 5200 5201 // Macro instantiation is lexical, unfortunately. We construct a new buffer 5202 // to hold the macro body with substitutions. 5203 SmallString<256> Buf; 5204 raw_svector_ostream OS(Buf); 5205 5206 StringRef Values = A.front().front().getString(); 5207 for (std::size_t I = 0, End = Values.size(); I != End; ++I) { 5208 MCAsmMacroArgument Arg; 5209 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); 5210 5211 // Note that the AtPseudoVariable is enabled for instantiations of .irpc. 5212 // This is undocumented, but GAS seems to support it. 5213 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 5214 return true; 5215 } 5216 5217 instantiateMacroLikeBody(M, DirectiveLoc, OS); 5218 5219 return false; 5220 } 5221 5222 bool MasmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { 5223 if (ActiveMacros.empty()) 5224 return TokError("unmatched '.endr' directive"); 5225 5226 // The only .repl that should get here are the ones created by 5227 // instantiateMacroLikeBody. 5228 assert(getLexer().is(AsmToken::EndOfStatement)); 5229 5230 handleMacroExit(); 5231 return false; 5232 } 5233 5234 bool MasmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, 5235 size_t Len) { 5236 const MCExpr *Value; 5237 SMLoc ExprLoc = getLexer().getLoc(); 5238 if (parseExpression(Value)) 5239 return true; 5240 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5241 if (!MCE) 5242 return Error(ExprLoc, "unexpected expression in _emit"); 5243 uint64_t IntValue = MCE->getValue(); 5244 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) 5245 return Error(ExprLoc, "literal value out of range for directive"); 5246 5247 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); 5248 return false; 5249 } 5250 5251 bool MasmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { 5252 const MCExpr *Value; 5253 SMLoc ExprLoc = getLexer().getLoc(); 5254 if (parseExpression(Value)) 5255 return true; 5256 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 5257 if (!MCE) 5258 return Error(ExprLoc, "unexpected expression in align"); 5259 uint64_t IntValue = MCE->getValue(); 5260 if (!isPowerOf2_64(IntValue)) 5261 return Error(ExprLoc, "literal value not a power of two greater then zero"); 5262 5263 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); 5264 return false; 5265 } 5266 5267 bool MasmParser::parseDirectiveEcho() { 5268 StringRef Message = parseStringToEndOfStatement(); 5269 Lex(); // eat end of statement 5270 llvm::outs() << Message << '\n'; 5271 return false; 5272 } 5273 5274 // We are comparing pointers, but the pointers are relative to a single string. 5275 // Thus, this should always be deterministic. 5276 static int rewritesSort(const AsmRewrite *AsmRewriteA, 5277 const AsmRewrite *AsmRewriteB) { 5278 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) 5279 return -1; 5280 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) 5281 return 1; 5282 5283 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output 5284 // rewrite to the same location. Make sure the SizeDirective rewrite is 5285 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This 5286 // ensures the sort algorithm is stable. 5287 if (AsmRewritePrecedence[AsmRewriteA->Kind] > 5288 AsmRewritePrecedence[AsmRewriteB->Kind]) 5289 return -1; 5290 5291 if (AsmRewritePrecedence[AsmRewriteA->Kind] < 5292 AsmRewritePrecedence[AsmRewriteB->Kind]) 5293 return 1; 5294 llvm_unreachable("Unstable rewrite sort."); 5295 } 5296 5297 bool MasmParser::parseMSInlineAsm( 5298 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, 5299 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls, 5300 SmallVectorImpl<std::string> &Constraints, 5301 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, 5302 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { 5303 SmallVector<void *, 4> InputDecls; 5304 SmallVector<void *, 4> OutputDecls; 5305 SmallVector<bool, 4> InputDeclsAddressOf; 5306 SmallVector<bool, 4> OutputDeclsAddressOf; 5307 SmallVector<std::string, 4> InputConstraints; 5308 SmallVector<std::string, 4> OutputConstraints; 5309 SmallVector<unsigned, 4> ClobberRegs; 5310 5311 SmallVector<AsmRewrite, 4> AsmStrRewrites; 5312 5313 // Prime the lexer. 5314 Lex(); 5315 5316 // While we have input, parse each statement. 5317 unsigned InputIdx = 0; 5318 unsigned OutputIdx = 0; 5319 while (getLexer().isNot(AsmToken::Eof)) { 5320 // Parse curly braces marking block start/end 5321 if (parseCurlyBlockScope(AsmStrRewrites)) 5322 continue; 5323 5324 ParseStatementInfo Info(&AsmStrRewrites); 5325 bool StatementErr = parseStatement(Info, &SI); 5326 5327 if (StatementErr || Info.ParseError) { 5328 // Emit pending errors if any exist. 5329 printPendingErrors(); 5330 return true; 5331 } 5332 5333 // No pending error should exist here. 5334 assert(!hasPendingError() && "unexpected error from parseStatement"); 5335 5336 if (Info.Opcode == ~0U) 5337 continue; 5338 5339 const MCInstrDesc &Desc = MII->get(Info.Opcode); 5340 5341 // Build the list of clobbers, outputs and inputs. 5342 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { 5343 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; 5344 5345 // Register operand. 5346 if (Operand.isReg() && !Operand.needAddressOf() && 5347 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { 5348 unsigned NumDefs = Desc.getNumDefs(); 5349 // Clobber. 5350 if (NumDefs && Operand.getMCOperandNum() < NumDefs) 5351 ClobberRegs.push_back(Operand.getReg()); 5352 continue; 5353 } 5354 5355 // Expr/Input or Output. 5356 StringRef SymName = Operand.getSymName(); 5357 if (SymName.empty()) 5358 continue; 5359 5360 void *OpDecl = Operand.getOpDecl(); 5361 if (!OpDecl) 5362 continue; 5363 5364 StringRef Constraint = Operand.getConstraint(); 5365 if (Operand.isImm()) { 5366 // Offset as immediate 5367 if (Operand.isOffsetOfLocal()) 5368 Constraint = "r"; 5369 else 5370 Constraint = "i"; 5371 } 5372 5373 bool isOutput = (i == 1) && Desc.mayStore(); 5374 SMLoc Start = SMLoc::getFromPointer(SymName.data()); 5375 if (isOutput) { 5376 ++InputIdx; 5377 OutputDecls.push_back(OpDecl); 5378 OutputDeclsAddressOf.push_back(Operand.needAddressOf()); 5379 OutputConstraints.push_back(("=" + Constraint).str()); 5380 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); 5381 } else { 5382 InputDecls.push_back(OpDecl); 5383 InputDeclsAddressOf.push_back(Operand.needAddressOf()); 5384 InputConstraints.push_back(Constraint.str()); 5385 if (Desc.OpInfo[i - 1].isBranchTarget()) 5386 AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size()); 5387 else 5388 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); 5389 } 5390 } 5391 5392 // Consider implicit defs to be clobbers. Think of cpuid and push. 5393 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(), 5394 Desc.getNumImplicitDefs()); 5395 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); 5396 } 5397 5398 // Set the number of Outputs and Inputs. 5399 NumOutputs = OutputDecls.size(); 5400 NumInputs = InputDecls.size(); 5401 5402 // Set the unique clobbers. 5403 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); 5404 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), 5405 ClobberRegs.end()); 5406 Clobbers.assign(ClobberRegs.size(), std::string()); 5407 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { 5408 raw_string_ostream OS(Clobbers[I]); 5409 IP->printRegName(OS, ClobberRegs[I]); 5410 } 5411 5412 // Merge the various outputs and inputs. Output are expected first. 5413 if (NumOutputs || NumInputs) { 5414 unsigned NumExprs = NumOutputs + NumInputs; 5415 OpDecls.resize(NumExprs); 5416 Constraints.resize(NumExprs); 5417 for (unsigned i = 0; i < NumOutputs; ++i) { 5418 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); 5419 Constraints[i] = OutputConstraints[i]; 5420 } 5421 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { 5422 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); 5423 Constraints[j] = InputConstraints[i]; 5424 } 5425 } 5426 5427 // Build the IR assembly string. 5428 std::string AsmStringIR; 5429 raw_string_ostream OS(AsmStringIR); 5430 StringRef ASMString = 5431 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); 5432 const char *AsmStart = ASMString.begin(); 5433 const char *AsmEnd = ASMString.end(); 5434 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); 5435 for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) { 5436 const AsmRewrite &AR = *it; 5437 // Check if this has already been covered by another rewrite... 5438 if (AR.Done) 5439 continue; 5440 AsmRewriteKind Kind = AR.Kind; 5441 5442 const char *Loc = AR.Loc.getPointer(); 5443 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); 5444 5445 // Emit everything up to the immediate/expression. 5446 if (unsigned Len = Loc - AsmStart) 5447 OS << StringRef(AsmStart, Len); 5448 5449 // Skip the original expression. 5450 if (Kind == AOK_Skip) { 5451 AsmStart = Loc + AR.Len; 5452 continue; 5453 } 5454 5455 unsigned AdditionalSkip = 0; 5456 // Rewrite expressions in $N notation. 5457 switch (Kind) { 5458 default: 5459 break; 5460 case AOK_IntelExpr: 5461 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression"); 5462 if (AR.IntelExp.NeedBracs) 5463 OS << "["; 5464 if (AR.IntelExp.hasBaseReg()) 5465 OS << AR.IntelExp.BaseReg; 5466 if (AR.IntelExp.hasIndexReg()) 5467 OS << (AR.IntelExp.hasBaseReg() ? " + " : "") 5468 << AR.IntelExp.IndexReg; 5469 if (AR.IntelExp.Scale > 1) 5470 OS << " * $$" << AR.IntelExp.Scale; 5471 if (AR.IntelExp.hasOffset()) { 5472 if (AR.IntelExp.hasRegs()) 5473 OS << " + "; 5474 // Fuse this rewrite with a rewrite of the offset name, if present. 5475 StringRef OffsetName = AR.IntelExp.OffsetName; 5476 SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data()); 5477 size_t OffsetLen = OffsetName.size(); 5478 auto rewrite_it = std::find_if( 5479 it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) { 5480 return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen && 5481 (FusingAR.Kind == AOK_Input || 5482 FusingAR.Kind == AOK_CallInput); 5483 }); 5484 if (rewrite_it == AsmStrRewrites.end()) { 5485 OS << "offset " << OffsetName; 5486 } else if (rewrite_it->Kind == AOK_CallInput) { 5487 OS << "${" << InputIdx++ << ":P}"; 5488 rewrite_it->Done = true; 5489 } else { 5490 OS << '$' << InputIdx++; 5491 rewrite_it->Done = true; 5492 } 5493 } 5494 if (AR.IntelExp.Imm || AR.IntelExp.emitImm()) 5495 OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm; 5496 if (AR.IntelExp.NeedBracs) 5497 OS << "]"; 5498 break; 5499 case AOK_Label: 5500 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; 5501 break; 5502 case AOK_Input: 5503 OS << '$' << InputIdx++; 5504 break; 5505 case AOK_CallInput: 5506 OS << "${" << InputIdx++ << ":P}"; 5507 break; 5508 case AOK_Output: 5509 OS << '$' << OutputIdx++; 5510 break; 5511 case AOK_SizeDirective: 5512 switch (AR.Val) { 5513 default: break; 5514 case 8: OS << "byte ptr "; break; 5515 case 16: OS << "word ptr "; break; 5516 case 32: OS << "dword ptr "; break; 5517 case 64: OS << "qword ptr "; break; 5518 case 80: OS << "xword ptr "; break; 5519 case 128: OS << "xmmword ptr "; break; 5520 case 256: OS << "ymmword ptr "; break; 5521 } 5522 break; 5523 case AOK_Emit: 5524 OS << ".byte"; 5525 break; 5526 case AOK_Align: { 5527 // MS alignment directives are measured in bytes. If the native assembler 5528 // measures alignment in bytes, we can pass it straight through. 5529 OS << ".align"; 5530 if (getContext().getAsmInfo()->getAlignmentIsInBytes()) 5531 break; 5532 5533 // Alignment is in log2 form, so print that instead and skip the original 5534 // immediate. 5535 unsigned Val = AR.Val; 5536 OS << ' ' << Val; 5537 assert(Val < 10 && "Expected alignment less then 2^10."); 5538 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; 5539 break; 5540 } 5541 case AOK_EVEN: 5542 OS << ".even"; 5543 break; 5544 case AOK_EndOfStatement: 5545 OS << "\n\t"; 5546 break; 5547 } 5548 5549 // Skip the original expression. 5550 AsmStart = Loc + AR.Len + AdditionalSkip; 5551 } 5552 5553 // Emit the remainder of the asm string. 5554 if (AsmStart != AsmEnd) 5555 OS << StringRef(AsmStart, AsmEnd - AsmStart); 5556 5557 AsmString = OS.str(); 5558 return false; 5559 } 5560 5561 /// Create an MCAsmParser instance. 5562 MCAsmParser *llvm::createMCMasmParser(SourceMgr &SM, MCContext &C, 5563 MCStreamer &Out, const MCAsmInfo &MAI, 5564 unsigned CB) { 5565 return new MasmParser(SM, C, Out, MAI, CB); 5566 } 5567