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