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