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