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