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