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