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