1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This class implements the parser for assembly files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/APFloat.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/MC/MCAsmInfo.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCDwarf.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCInstPrinter.h" 24 #include "llvm/MC/MCInstrInfo.h" 25 #include "llvm/MC/MCObjectFileInfo.h" 26 #include "llvm/MC/MCParser/AsmCond.h" 27 #include "llvm/MC/MCParser/AsmLexer.h" 28 #include "llvm/MC/MCParser/MCAsmParser.h" 29 #include "llvm/MC/MCParser/MCAsmParserUtils.h" 30 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 31 #include "llvm/MC/MCRegisterInfo.h" 32 #include "llvm/MC/MCSectionMachO.h" 33 #include "llvm/MC/MCStreamer.h" 34 #include "llvm/MC/MCSymbol.h" 35 #include "llvm/MC/MCTargetAsmParser.h" 36 #include "llvm/MC/MCValue.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/SourceMgr.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <cctype> 44 #include <deque> 45 #include <set> 46 #include <string> 47 #include <vector> 48 using namespace llvm; 49 50 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {} 51 52 namespace { 53 /// \brief Helper types for tracking macro definitions. 54 typedef std::vector<AsmToken> MCAsmMacroArgument; 55 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments; 56 57 struct MCAsmMacroParameter { 58 StringRef Name; 59 MCAsmMacroArgument Value; 60 bool Required; 61 bool Vararg; 62 63 MCAsmMacroParameter() : Required(false), Vararg(false) {} 64 }; 65 66 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters; 67 68 struct MCAsmMacro { 69 StringRef Name; 70 StringRef Body; 71 MCAsmMacroParameters Parameters; 72 73 public: 74 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P) 75 : Name(N), Body(B), Parameters(std::move(P)) {} 76 }; 77 78 /// \brief Helper class for storing information about an active macro 79 /// instantiation. 80 struct MacroInstantiation { 81 /// The location of the instantiation. 82 SMLoc InstantiationLoc; 83 84 /// The buffer where parsing should resume upon instantiation completion. 85 int ExitBuffer; 86 87 /// The location where parsing should resume upon instantiation completion. 88 SMLoc ExitLoc; 89 90 /// The depth of TheCondStack at the start of the instantiation. 91 size_t CondStackDepth; 92 93 public: 94 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth); 95 }; 96 97 struct ParseStatementInfo { 98 /// \brief The parsed operands from the last parsed statement. 99 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands; 100 101 /// \brief The opcode from the last parsed instruction. 102 unsigned Opcode; 103 104 /// \brief Was there an error parsing the inline assembly? 105 bool ParseError; 106 107 SmallVectorImpl<AsmRewrite> *AsmRewrites; 108 109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {} 110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites) 111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {} 112 }; 113 114 /// \brief The concrete assembly parser instance. 115 class AsmParser : public MCAsmParser { 116 AsmParser(const AsmParser &) = delete; 117 void operator=(const AsmParser &) = delete; 118 private: 119 AsmLexer Lexer; 120 MCContext &Ctx; 121 MCStreamer &Out; 122 const MCAsmInfo &MAI; 123 SourceMgr &SrcMgr; 124 SourceMgr::DiagHandlerTy SavedDiagHandler; 125 void *SavedDiagContext; 126 std::unique_ptr<MCAsmParserExtension> PlatformParser; 127 128 /// This is the current buffer index we're lexing from as managed by the 129 /// SourceMgr object. 130 unsigned CurBuffer; 131 132 AsmCond TheCondState; 133 std::vector<AsmCond> TheCondStack; 134 135 /// \brief maps directive names to handler methods in parser 136 /// extensions. Extensions register themselves in this map by calling 137 /// addDirectiveHandler. 138 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap; 139 140 /// \brief Map of currently defined macros. 141 StringMap<MCAsmMacro> MacroMap; 142 143 /// \brief Stack of active macro instantiations. 144 std::vector<MacroInstantiation*> ActiveMacros; 145 146 /// \brief List of bodies of anonymous macros. 147 std::deque<MCAsmMacro> MacroLikeBodies; 148 149 /// Boolean tracking whether macro substitution is enabled. 150 unsigned MacrosEnabledFlag : 1; 151 152 /// \brief Keeps track of how many .macro's have been instantiated. 153 unsigned NumOfMacroInstantiations; 154 155 /// Flag tracking whether any errors have been encountered. 156 unsigned HadError : 1; 157 158 /// The values from the last parsed cpp hash file line comment if any. 159 StringRef CppHashFilename; 160 int64_t CppHashLineNumber; 161 SMLoc CppHashLoc; 162 unsigned CppHashBuf; 163 /// When generating dwarf for assembly source files we need to calculate the 164 /// logical line number based on the last parsed cpp hash file line comment 165 /// and current line. Since this is slow and messes up the SourceMgr's 166 /// cache we save the last info we queried with SrcMgr.FindLineNumber(). 167 SMLoc LastQueryIDLoc; 168 unsigned LastQueryBuffer; 169 unsigned LastQueryLine; 170 171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI. 172 unsigned AssemblerDialect; 173 174 /// \brief is Darwin compatibility enabled? 175 bool IsDarwin; 176 177 /// \brief Are we parsing ms-style inline assembly? 178 bool ParsingInlineAsm; 179 180 public: 181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 182 const MCAsmInfo &MAI); 183 ~AsmParser() override; 184 185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; 186 187 void addDirectiveHandler(StringRef Directive, 188 ExtensionDirectiveHandler Handler) override { 189 ExtensionDirectiveMap[Directive] = Handler; 190 } 191 192 void addAliasForDirective(StringRef Directive, StringRef Alias) override { 193 DirectiveKindMap[Directive] = DirectiveKindMap[Alias]; 194 } 195 196 public: 197 /// @name MCAsmParser Interface 198 /// { 199 200 SourceMgr &getSourceManager() override { return SrcMgr; } 201 MCAsmLexer &getLexer() override { return Lexer; } 202 MCContext &getContext() override { return Ctx; } 203 MCStreamer &getStreamer() override { return Out; } 204 unsigned getAssemblerDialect() override { 205 if (AssemblerDialect == ~0U) 206 return MAI.getAssemblerDialect(); 207 else 208 return AssemblerDialect; 209 } 210 void setAssemblerDialect(unsigned i) override { 211 AssemblerDialect = i; 212 } 213 214 void Note(SMLoc L, const Twine &Msg, 215 ArrayRef<SMRange> Ranges = None) override; 216 bool Warning(SMLoc L, const Twine &Msg, 217 ArrayRef<SMRange> Ranges = None) override; 218 bool Error(SMLoc L, const Twine &Msg, 219 ArrayRef<SMRange> Ranges = None) override; 220 221 const AsmToken &Lex() override; 222 223 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; } 224 bool isParsingInlineAsm() override { return ParsingInlineAsm; } 225 226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, 227 unsigned &NumOutputs, unsigned &NumInputs, 228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls, 229 SmallVectorImpl<std::string> &Constraints, 230 SmallVectorImpl<std::string> &Clobbers, 231 const MCInstrInfo *MII, const MCInstPrinter *IP, 232 MCAsmParserSemaCallback &SI) override; 233 234 bool parseExpression(const MCExpr *&Res); 235 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 236 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; 237 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 238 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 239 SMLoc &EndLoc) override; 240 bool parseAbsoluteExpression(int64_t &Res) override; 241 242 /// \brief Parse an identifier or string (as a quoted identifier) 243 /// and set \p Res to the identifier contents. 244 bool parseIdentifier(StringRef &Res) override; 245 void eatToEndOfStatement() override; 246 247 void checkForValidSection() override; 248 /// } 249 250 private: 251 252 bool parseStatement(ParseStatementInfo &Info, 253 MCAsmParserSemaCallback *SI); 254 void eatToEndOfLine(); 255 bool parseCppHashLineFilenameComment(SMLoc L); 256 257 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, 258 ArrayRef<MCAsmMacroParameter> Parameters); 259 bool expandMacro(raw_svector_ostream &OS, StringRef Body, 260 ArrayRef<MCAsmMacroParameter> Parameters, 261 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable, 262 SMLoc L); 263 264 /// \brief Are macros enabled in the parser? 265 bool areMacrosEnabled() {return MacrosEnabledFlag;} 266 267 /// \brief Control a flag in the parser that enables or disables macros. 268 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;} 269 270 /// \brief Lookup a previously defined macro. 271 /// \param Name Macro name. 272 /// \returns Pointer to macro. NULL if no such macro was defined. 273 const MCAsmMacro* lookupMacro(StringRef Name); 274 275 /// \brief Define a new macro with the given name and information. 276 void defineMacro(StringRef Name, MCAsmMacro Macro); 277 278 /// \brief Undefine a macro. If no such macro was defined, it's a no-op. 279 void undefineMacro(StringRef Name); 280 281 /// \brief Are we inside a macro instantiation? 282 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} 283 284 /// \brief Handle entry to macro instantiation. 285 /// 286 /// \param M The macro. 287 /// \param NameLoc Instantiation location. 288 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); 289 290 /// \brief Handle exit from macro instantiation. 291 void handleMacroExit(); 292 293 /// \brief Extract AsmTokens for a macro argument. 294 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); 295 296 /// \brief Parse all macro arguments for a given macro. 297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); 298 299 void printMacroInstantiations(); 300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, 301 ArrayRef<SMRange> Ranges = None) const { 302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); 303 } 304 static void DiagHandler(const SMDiagnostic &Diag, void *Context); 305 306 /// \brief Enter the specified file. This returns true on failure. 307 bool enterIncludeFile(const std::string &Filename); 308 309 /// \brief Process the specified file for the .incbin directive. 310 /// This returns true on failure. 311 bool processIncbinFile(const std::string &Filename); 312 313 /// \brief Reset the current lexer position to that given by \p Loc. The 314 /// current token is not set; clients should ensure Lex() is called 315 /// subsequently. 316 /// 317 /// \param InBuffer If not 0, should be the known buffer id that contains the 318 /// location. 319 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); 320 321 /// \brief Parse up to the end of statement and a return the contents from the 322 /// current token until the end of the statement; the current token on exit 323 /// will be either the EndOfStatement or EOF. 324 StringRef parseStringToEndOfStatement() override; 325 326 /// \brief Parse until the end of a statement or a comma is encountered, 327 /// return the contents from the current token up to the end or comma. 328 StringRef parseStringToComma(); 329 330 bool parseAssignment(StringRef Name, bool allow_redef, 331 bool NoDeadStrip = false); 332 333 unsigned getBinOpPrecedence(AsmToken::TokenKind K, 334 MCBinaryExpr::Opcode &Kind); 335 336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); 337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); 338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); 339 340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); 341 342 // Generic (target and platform independent) directive parsing. 343 enum DirectiveKind { 344 DK_NO_DIRECTIVE, // Placeholder 345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT, 346 DK_RELOC, 347 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA, 348 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW, 349 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR, 350 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK, 351 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, 352 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN, 353 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE, 354 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT, 355 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC, 356 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB, 357 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF, 358 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF, 359 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS, 360 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA, 361 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER, 362 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA, 363 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE, 364 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED, 365 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE, 366 DK_MACROS_ON, DK_MACROS_OFF, 367 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM, 368 DK_SLEB128, DK_ULEB128, 369 DK_ERR, DK_ERROR, DK_WARNING, 370 DK_END 371 }; 372 373 /// \brief Maps directive name --> DirectiveKind enum, for 374 /// directives parsed by this class. 375 StringMap<DirectiveKind> DirectiveKindMap; 376 377 // ".ascii", ".asciz", ".string" 378 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); 379 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc" 380 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ... 381 bool parseDirectiveOctaValue(); // ".octa" 382 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ... 383 bool parseDirectiveFill(); // ".fill" 384 bool parseDirectiveZero(); // ".zero" 385 // ".set", ".equ", ".equiv" 386 bool parseDirectiveSet(StringRef IDVal, bool allow_redef); 387 bool parseDirectiveOrg(); // ".org" 388 // ".align{,32}", ".p2align{,w,l}" 389 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize); 390 391 // ".file", ".line", ".loc", ".stabs" 392 bool parseDirectiveFile(SMLoc DirectiveLoc); 393 bool parseDirectiveLine(); 394 bool parseDirectiveLoc(); 395 bool parseDirectiveStabs(); 396 397 // .cfi directives 398 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); 399 bool parseDirectiveCFIWindowSave(); 400 bool parseDirectiveCFISections(); 401 bool parseDirectiveCFIStartProc(); 402 bool parseDirectiveCFIEndProc(); 403 bool parseDirectiveCFIDefCfaOffset(); 404 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); 405 bool parseDirectiveCFIAdjustCfaOffset(); 406 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); 407 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); 408 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); 409 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); 410 bool parseDirectiveCFIRememberState(); 411 bool parseDirectiveCFIRestoreState(); 412 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); 413 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); 414 bool parseDirectiveCFIEscape(); 415 bool parseDirectiveCFISignalFrame(); 416 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); 417 418 // macro directives 419 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); 420 bool parseDirectiveExitMacro(StringRef Directive); 421 bool parseDirectiveEndMacro(StringRef Directive); 422 bool parseDirectiveMacro(SMLoc DirectiveLoc); 423 bool parseDirectiveMacrosOnOff(StringRef Directive); 424 425 // ".bundle_align_mode" 426 bool parseDirectiveBundleAlignMode(); 427 // ".bundle_lock" 428 bool parseDirectiveBundleLock(); 429 // ".bundle_unlock" 430 bool parseDirectiveBundleUnlock(); 431 432 // ".space", ".skip" 433 bool parseDirectiveSpace(StringRef IDVal); 434 435 // .sleb128 (Signed=true) and .uleb128 (Signed=false) 436 bool parseDirectiveLEB128(bool Signed); 437 438 /// \brief Parse a directive like ".globl" which 439 /// accepts a single symbol (which should be a label or an external). 440 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); 441 442 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" 443 444 bool parseDirectiveAbort(); // ".abort" 445 bool parseDirectiveInclude(); // ".include" 446 bool parseDirectiveIncbin(); // ".incbin" 447 448 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne" 449 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 450 // ".ifb" or ".ifnb", depending on ExpectBlank. 451 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); 452 // ".ifc" or ".ifnc", depending on ExpectEqual. 453 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual); 454 // ".ifeqs" or ".ifnes", depending on ExpectEqual. 455 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual); 456 // ".ifdef" or ".ifndef", depending on expect_defined 457 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); 458 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif" 459 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else" 460 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif 461 bool parseEscapedString(std::string &Data) override; 462 463 const MCExpr *applyModifierToExpr(const MCExpr *E, 464 MCSymbolRefExpr::VariantKind Variant); 465 466 // Macro-like directives 467 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); 468 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 469 raw_svector_ostream &OS); 470 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); 471 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" 472 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" 473 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" 474 475 // "_emit" or "__emit" 476 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, 477 size_t Len); 478 479 // "align" 480 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); 481 482 // "end" 483 bool parseDirectiveEnd(SMLoc DirectiveLoc); 484 485 // ".err" or ".error" 486 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage); 487 488 // ".warning" 489 bool parseDirectiveWarning(SMLoc DirectiveLoc); 490 491 void initializeDirectiveKindMap(); 492 }; 493 } 494 495 namespace llvm { 496 497 extern MCAsmParserExtension *createDarwinAsmParser(); 498 extern MCAsmParserExtension *createELFAsmParser(); 499 extern MCAsmParserExtension *createCOFFAsmParser(); 500 501 } 502 503 enum { DEFAULT_ADDRSPACE = 0 }; 504 505 AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 506 const MCAsmInfo &MAI) 507 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), 508 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()), 509 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0), 510 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) { 511 // Save the old handler. 512 SavedDiagHandler = SrcMgr.getDiagHandler(); 513 SavedDiagContext = SrcMgr.getDiagContext(); 514 // Set our own handler which calls the saved handler. 515 SrcMgr.setDiagHandler(DiagHandler, this); 516 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 517 518 // Initialize the platform / file format parser. 519 switch (Ctx.getObjectFileInfo()->getObjectFileType()) { 520 case MCObjectFileInfo::IsCOFF: 521 PlatformParser.reset(createCOFFAsmParser()); 522 break; 523 case MCObjectFileInfo::IsMachO: 524 PlatformParser.reset(createDarwinAsmParser()); 525 IsDarwin = true; 526 break; 527 case MCObjectFileInfo::IsELF: 528 PlatformParser.reset(createELFAsmParser()); 529 break; 530 } 531 532 PlatformParser->Initialize(*this); 533 initializeDirectiveKindMap(); 534 535 NumOfMacroInstantiations = 0; 536 } 537 538 AsmParser::~AsmParser() { 539 assert((HadError || ActiveMacros.empty()) && 540 "Unexpected active macro instantiation!"); 541 } 542 543 void AsmParser::printMacroInstantiations() { 544 // Print the active macro instantiation stack. 545 for (std::vector<MacroInstantiation *>::const_reverse_iterator 546 it = ActiveMacros.rbegin(), 547 ie = ActiveMacros.rend(); 548 it != ie; ++it) 549 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, 550 "while in macro instantiation"); 551 } 552 553 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { 554 printMessage(L, SourceMgr::DK_Note, Msg, Ranges); 555 printMacroInstantiations(); 556 } 557 558 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { 559 if(getTargetParser().getTargetOptions().MCNoWarn) 560 return false; 561 if (getTargetParser().getTargetOptions().MCFatalWarnings) 562 return Error(L, Msg, Ranges); 563 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges); 564 printMacroInstantiations(); 565 return false; 566 } 567 568 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) { 569 HadError = true; 570 printMessage(L, SourceMgr::DK_Error, Msg, Ranges); 571 printMacroInstantiations(); 572 return true; 573 } 574 575 bool AsmParser::enterIncludeFile(const std::string &Filename) { 576 std::string IncludedFile; 577 unsigned NewBuf = 578 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 579 if (!NewBuf) 580 return true; 581 582 CurBuffer = NewBuf; 583 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 584 return false; 585 } 586 587 /// Process the specified .incbin file by searching for it in the include paths 588 /// then just emitting the byte contents of the file to the streamer. This 589 /// returns true on failure. 590 bool AsmParser::processIncbinFile(const std::string &Filename) { 591 std::string IncludedFile; 592 unsigned NewBuf = 593 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 594 if (!NewBuf) 595 return true; 596 597 // Pick up the bytes from the file and emit them. 598 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer()); 599 return false; 600 } 601 602 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { 603 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); 604 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), 605 Loc.getPointer()); 606 } 607 608 const AsmToken &AsmParser::Lex() { 609 const AsmToken *tok = &Lexer.Lex(); 610 611 if (tok->is(AsmToken::Eof)) { 612 // If this is the end of an included file, pop the parent file off the 613 // include stack. 614 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); 615 if (ParentIncludeLoc != SMLoc()) { 616 jumpToLoc(ParentIncludeLoc); 617 tok = &Lexer.Lex(); 618 } 619 } 620 621 if (tok->is(AsmToken::Error)) 622 Error(Lexer.getErrLoc(), Lexer.getErr()); 623 624 return *tok; 625 } 626 627 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) { 628 // Create the initial section, if requested. 629 if (!NoInitialTextSection) 630 Out.InitSections(false); 631 632 // Prime the lexer. 633 Lex(); 634 635 HadError = false; 636 AsmCond StartingCondState = TheCondState; 637 638 // If we are generating dwarf for assembly source files save the initial text 639 // section and generate a .file directive. 640 if (getContext().getGenDwarfForAssembly()) { 641 MCSection *Sec = getStreamer().getCurrentSection().first; 642 if (!Sec->getBeginSymbol()) { 643 MCSymbol *SectionStartSym = getContext().createTempSymbol(); 644 getStreamer().EmitLabel(SectionStartSym); 645 Sec->setBeginSymbol(SectionStartSym); 646 } 647 bool InsertResult = getContext().addGenDwarfSection(Sec); 648 assert(InsertResult && ".text section should not have debug info yet"); 649 (void)InsertResult; 650 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective( 651 0, StringRef(), getContext().getMainFileName())); 652 } 653 654 // While we have input, parse each statement. 655 while (Lexer.isNot(AsmToken::Eof)) { 656 ParseStatementInfo Info; 657 if (!parseStatement(Info, nullptr)) 658 continue; 659 660 // We had an error, validate that one was emitted and recover by skipping to 661 // the next line. 662 assert(HadError && "Parse statement returned an error, but none emitted!"); 663 eatToEndOfStatement(); 664 } 665 666 if (TheCondState.TheCond != StartingCondState.TheCond || 667 TheCondState.Ignore != StartingCondState.Ignore) 668 return TokError("unmatched .ifs or .elses"); 669 670 // Check to see there are no empty DwarfFile slots. 671 const auto &LineTables = getContext().getMCDwarfLineTables(); 672 if (!LineTables.empty()) { 673 unsigned Index = 0; 674 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { 675 if (File.Name.empty() && Index != 0) 676 TokError("unassigned file number: " + Twine(Index) + 677 " for .file directives"); 678 ++Index; 679 } 680 } 681 682 // Check to see that all assembler local symbols were actually defined. 683 // Targets that don't do subsections via symbols may not want this, though, 684 // so conservatively exclude them. Only do this if we're finalizing, though, 685 // as otherwise we won't necessarilly have seen everything yet. 686 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) { 687 for (const auto &TableEntry : getContext().getSymbols()) { 688 MCSymbol *Sym = TableEntry.getValue(); 689 // Variable symbols may not be marked as defined, so check those 690 // explicitly. If we know it's a variable, we have a definition for 691 // the purposes of this check. 692 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) 693 // FIXME: We would really like to refer back to where the symbol was 694 // first referenced for a source location. We need to add something 695 // to track that. Currently, we just point to the end of the file. 696 return Error(getLexer().getLoc(), "assembler local symbol '" + 697 Sym->getName() + "' not defined"); 698 } 699 } 700 701 // Finalize the output stream if there are no errors and if the client wants 702 // us to. 703 if (!HadError && !NoFinalize) 704 Out.Finish(); 705 706 return HadError || getContext().hadError(); 707 } 708 709 void AsmParser::checkForValidSection() { 710 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) { 711 TokError("expected section directive before assembly directive"); 712 Out.InitSections(false); 713 } 714 } 715 716 /// \brief Throw away the rest of the line for testing purposes. 717 void AsmParser::eatToEndOfStatement() { 718 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 719 Lex(); 720 721 // Eat EOL. 722 if (Lexer.is(AsmToken::EndOfStatement)) 723 Lex(); 724 } 725 726 StringRef AsmParser::parseStringToEndOfStatement() { 727 const char *Start = getTok().getLoc().getPointer(); 728 729 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 730 Lex(); 731 732 const char *End = getTok().getLoc().getPointer(); 733 return StringRef(Start, End - Start); 734 } 735 736 StringRef AsmParser::parseStringToComma() { 737 const char *Start = getTok().getLoc().getPointer(); 738 739 while (Lexer.isNot(AsmToken::EndOfStatement) && 740 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof)) 741 Lex(); 742 743 const char *End = getTok().getLoc().getPointer(); 744 return StringRef(Start, End - Start); 745 } 746 747 /// \brief Parse a paren expression and return it. 748 /// NOTE: This assumes the leading '(' has already been consumed. 749 /// 750 /// parenexpr ::= expr) 751 /// 752 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { 753 if (parseExpression(Res)) 754 return true; 755 if (Lexer.isNot(AsmToken::RParen)) 756 return TokError("expected ')' in parentheses expression"); 757 EndLoc = Lexer.getTok().getEndLoc(); 758 Lex(); 759 return false; 760 } 761 762 /// \brief Parse a bracket expression and return it. 763 /// NOTE: This assumes the leading '[' has already been consumed. 764 /// 765 /// bracketexpr ::= expr] 766 /// 767 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { 768 if (parseExpression(Res)) 769 return true; 770 if (Lexer.isNot(AsmToken::RBrac)) 771 return TokError("expected ']' in brackets expression"); 772 EndLoc = Lexer.getTok().getEndLoc(); 773 Lex(); 774 return false; 775 } 776 777 /// \brief Parse a primary expression and return it. 778 /// primaryexpr ::= (parenexpr 779 /// primaryexpr ::= symbol 780 /// primaryexpr ::= number 781 /// primaryexpr ::= '.' 782 /// primaryexpr ::= ~,+,- primaryexpr 783 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { 784 SMLoc FirstTokenLoc = getLexer().getLoc(); 785 AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); 786 switch (FirstTokenKind) { 787 default: 788 return TokError("unknown token in expression"); 789 // If we have an error assume that we've already handled it. 790 case AsmToken::Error: 791 return true; 792 case AsmToken::Exclaim: 793 Lex(); // Eat the operator. 794 if (parsePrimaryExpr(Res, EndLoc)) 795 return true; 796 Res = MCUnaryExpr::createLNot(Res, getContext()); 797 return false; 798 case AsmToken::Dollar: 799 case AsmToken::At: 800 case AsmToken::String: 801 case AsmToken::Identifier: { 802 StringRef Identifier; 803 if (parseIdentifier(Identifier)) { 804 if (FirstTokenKind == AsmToken::Dollar) { 805 if (Lexer.getMAI().getDollarIsPC()) { 806 // This is a '$' reference, which references the current PC. Emit a 807 // temporary label to the streamer and refer to it. 808 MCSymbol *Sym = Ctx.createTempSymbol(); 809 Out.EmitLabel(Sym); 810 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, 811 getContext()); 812 EndLoc = FirstTokenLoc; 813 return false; 814 } 815 return Error(FirstTokenLoc, "invalid token in expression"); 816 } 817 } 818 // Parse symbol variant 819 std::pair<StringRef, StringRef> Split; 820 if (!MAI.useParensForSymbolVariant()) { 821 if (FirstTokenKind == AsmToken::String) { 822 if (Lexer.is(AsmToken::At)) { 823 Lexer.Lex(); // eat @ 824 SMLoc AtLoc = getLexer().getLoc(); 825 StringRef VName; 826 if (parseIdentifier(VName)) 827 return Error(AtLoc, "expected symbol variant after '@'"); 828 829 Split = std::make_pair(Identifier, VName); 830 } 831 } else { 832 Split = Identifier.split('@'); 833 } 834 } else if (Lexer.is(AsmToken::LParen)) { 835 Lexer.Lex(); // eat ( 836 StringRef VName; 837 parseIdentifier(VName); 838 if (Lexer.isNot(AsmToken::RParen)) { 839 return Error(Lexer.getTok().getLoc(), 840 "unexpected token in variant, expected ')'"); 841 } 842 Lexer.Lex(); // eat ) 843 Split = std::make_pair(Identifier, VName); 844 } 845 846 EndLoc = SMLoc::getFromPointer(Identifier.end()); 847 848 // This is a symbol reference. 849 StringRef SymbolName = Identifier; 850 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 851 852 // Lookup the symbol variant if used. 853 if (Split.second.size()) { 854 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 855 if (Variant != MCSymbolRefExpr::VK_Invalid) { 856 SymbolName = Split.first; 857 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { 858 Variant = MCSymbolRefExpr::VK_None; 859 } else { 860 return Error(SMLoc::getFromPointer(Split.second.begin()), 861 "invalid variant '" + Split.second + "'"); 862 } 863 } 864 865 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName); 866 867 // If this is an absolute variable reference, substitute it now to preserve 868 // semantics in the face of reassignment. 869 if (Sym->isVariable() && 870 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) { 871 if (Variant) 872 return Error(EndLoc, "unexpected modifier on variable reference"); 873 874 Res = Sym->getVariableValue(/*SetUsed*/ false); 875 return false; 876 } 877 878 // Otherwise create a symbol ref. 879 Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); 880 return false; 881 } 882 case AsmToken::BigNum: 883 return TokError("literal value out of range for directive"); 884 case AsmToken::Integer: { 885 SMLoc Loc = getTok().getLoc(); 886 int64_t IntVal = getTok().getIntVal(); 887 Res = MCConstantExpr::create(IntVal, getContext()); 888 EndLoc = Lexer.getTok().getEndLoc(); 889 Lex(); // Eat token. 890 // Look for 'b' or 'f' following an Integer as a directional label 891 if (Lexer.getKind() == AsmToken::Identifier) { 892 StringRef IDVal = getTok().getString(); 893 // Lookup the symbol variant if used. 894 std::pair<StringRef, StringRef> Split = IDVal.split('@'); 895 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 896 if (Split.first.size() != IDVal.size()) { 897 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 898 if (Variant == MCSymbolRefExpr::VK_Invalid) 899 return TokError("invalid variant '" + Split.second + "'"); 900 IDVal = Split.first; 901 } 902 if (IDVal == "f" || IDVal == "b") { 903 MCSymbol *Sym = 904 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b"); 905 Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); 906 if (IDVal == "b" && Sym->isUndefined()) 907 return Error(Loc, "invalid reference to undefined symbol"); 908 EndLoc = Lexer.getTok().getEndLoc(); 909 Lex(); // Eat identifier. 910 } 911 } 912 return false; 913 } 914 case AsmToken::Real: { 915 APFloat RealVal(APFloat::IEEEdouble, getTok().getString()); 916 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); 917 Res = MCConstantExpr::create(IntVal, getContext()); 918 EndLoc = Lexer.getTok().getEndLoc(); 919 Lex(); // Eat token. 920 return false; 921 } 922 case AsmToken::Dot: { 923 // This is a '.' reference, which references the current PC. Emit a 924 // temporary label to the streamer and refer to it. 925 MCSymbol *Sym = Ctx.createTempSymbol(); 926 Out.EmitLabel(Sym); 927 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); 928 EndLoc = Lexer.getTok().getEndLoc(); 929 Lex(); // Eat identifier. 930 return false; 931 } 932 case AsmToken::LParen: 933 Lex(); // Eat the '('. 934 return parseParenExpr(Res, EndLoc); 935 case AsmToken::LBrac: 936 if (!PlatformParser->HasBracketExpressions()) 937 return TokError("brackets expression not supported on this target"); 938 Lex(); // Eat the '['. 939 return parseBracketExpr(Res, EndLoc); 940 case AsmToken::Minus: 941 Lex(); // Eat the operator. 942 if (parsePrimaryExpr(Res, EndLoc)) 943 return true; 944 Res = MCUnaryExpr::createMinus(Res, getContext()); 945 return false; 946 case AsmToken::Plus: 947 Lex(); // Eat the operator. 948 if (parsePrimaryExpr(Res, EndLoc)) 949 return true; 950 Res = MCUnaryExpr::createPlus(Res, getContext()); 951 return false; 952 case AsmToken::Tilde: 953 Lex(); // Eat the operator. 954 if (parsePrimaryExpr(Res, EndLoc)) 955 return true; 956 Res = MCUnaryExpr::createNot(Res, getContext()); 957 return false; 958 } 959 } 960 961 bool AsmParser::parseExpression(const MCExpr *&Res) { 962 SMLoc EndLoc; 963 return parseExpression(Res, EndLoc); 964 } 965 966 const MCExpr * 967 AsmParser::applyModifierToExpr(const MCExpr *E, 968 MCSymbolRefExpr::VariantKind Variant) { 969 // Ask the target implementation about this expression first. 970 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx); 971 if (NewE) 972 return NewE; 973 // Recurse over the given expression, rebuilding it to apply the given variant 974 // if there is exactly one symbol. 975 switch (E->getKind()) { 976 case MCExpr::Target: 977 case MCExpr::Constant: 978 return nullptr; 979 980 case MCExpr::SymbolRef: { 981 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E); 982 983 if (SRE->getKind() != MCSymbolRefExpr::VK_None) { 984 TokError("invalid variant on expression '" + getTok().getIdentifier() + 985 "' (already modified)"); 986 return E; 987 } 988 989 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext()); 990 } 991 992 case MCExpr::Unary: { 993 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E); 994 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant); 995 if (!Sub) 996 return nullptr; 997 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext()); 998 } 999 1000 case MCExpr::Binary: { 1001 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E); 1002 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant); 1003 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant); 1004 1005 if (!LHS && !RHS) 1006 return nullptr; 1007 1008 if (!LHS) 1009 LHS = BE->getLHS(); 1010 if (!RHS) 1011 RHS = BE->getRHS(); 1012 1013 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext()); 1014 } 1015 } 1016 1017 llvm_unreachable("Invalid expression kind!"); 1018 } 1019 1020 /// \brief Parse an expression and return it. 1021 /// 1022 /// expr ::= expr &&,|| expr -> lowest. 1023 /// expr ::= expr |,^,&,! expr 1024 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr 1025 /// expr ::= expr <<,>> expr 1026 /// expr ::= expr +,- expr 1027 /// expr ::= expr *,/,% expr -> highest. 1028 /// expr ::= primaryexpr 1029 /// 1030 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1031 // Parse the expression. 1032 Res = nullptr; 1033 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc)) 1034 return true; 1035 1036 // As a special case, we support 'a op b @ modifier' by rewriting the 1037 // expression to include the modifier. This is inefficient, but in general we 1038 // expect users to use 'a@modifier op b'. 1039 if (Lexer.getKind() == AsmToken::At) { 1040 Lex(); 1041 1042 if (Lexer.isNot(AsmToken::Identifier)) 1043 return TokError("unexpected symbol modifier following '@'"); 1044 1045 MCSymbolRefExpr::VariantKind Variant = 1046 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier()); 1047 if (Variant == MCSymbolRefExpr::VK_Invalid) 1048 return TokError("invalid variant '" + getTok().getIdentifier() + "'"); 1049 1050 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant); 1051 if (!ModifiedRes) { 1052 return TokError("invalid modifier '" + getTok().getIdentifier() + 1053 "' (no symbols present)"); 1054 } 1055 1056 Res = ModifiedRes; 1057 Lex(); 1058 } 1059 1060 // Try to constant fold it up front, if possible. 1061 int64_t Value; 1062 if (Res->evaluateAsAbsolute(Value)) 1063 Res = MCConstantExpr::create(Value, getContext()); 1064 1065 return false; 1066 } 1067 1068 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1069 Res = nullptr; 1070 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); 1071 } 1072 1073 bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 1074 SMLoc &EndLoc) { 1075 if (parseParenExpr(Res, EndLoc)) 1076 return true; 1077 1078 for (; ParenDepth > 0; --ParenDepth) { 1079 if (parseBinOpRHS(1, Res, EndLoc)) 1080 return true; 1081 1082 // We don't Lex() the last RParen. 1083 // This is the same behavior as parseParenExpression(). 1084 if (ParenDepth - 1 > 0) { 1085 if (Lexer.isNot(AsmToken::RParen)) 1086 return TokError("expected ')' in parentheses expression"); 1087 EndLoc = Lexer.getTok().getEndLoc(); 1088 Lex(); 1089 } 1090 } 1091 return false; 1092 } 1093 1094 bool AsmParser::parseAbsoluteExpression(int64_t &Res) { 1095 const MCExpr *Expr; 1096 1097 SMLoc StartLoc = Lexer.getLoc(); 1098 if (parseExpression(Expr)) 1099 return true; 1100 1101 if (!Expr->evaluateAsAbsolute(Res)) 1102 return Error(StartLoc, "expected absolute expression"); 1103 1104 return false; 1105 } 1106 1107 static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K, 1108 MCBinaryExpr::Opcode &Kind, 1109 bool ShouldUseLogicalShr) { 1110 switch (K) { 1111 default: 1112 return 0; // not a binop. 1113 1114 // Lowest Precedence: &&, || 1115 case AsmToken::AmpAmp: 1116 Kind = MCBinaryExpr::LAnd; 1117 return 1; 1118 case AsmToken::PipePipe: 1119 Kind = MCBinaryExpr::LOr; 1120 return 1; 1121 1122 // Low Precedence: |, &, ^ 1123 // 1124 // FIXME: gas seems to support '!' as an infix operator? 1125 case AsmToken::Pipe: 1126 Kind = MCBinaryExpr::Or; 1127 return 2; 1128 case AsmToken::Caret: 1129 Kind = MCBinaryExpr::Xor; 1130 return 2; 1131 case AsmToken::Amp: 1132 Kind = MCBinaryExpr::And; 1133 return 2; 1134 1135 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >= 1136 case AsmToken::EqualEqual: 1137 Kind = MCBinaryExpr::EQ; 1138 return 3; 1139 case AsmToken::ExclaimEqual: 1140 case AsmToken::LessGreater: 1141 Kind = MCBinaryExpr::NE; 1142 return 3; 1143 case AsmToken::Less: 1144 Kind = MCBinaryExpr::LT; 1145 return 3; 1146 case AsmToken::LessEqual: 1147 Kind = MCBinaryExpr::LTE; 1148 return 3; 1149 case AsmToken::Greater: 1150 Kind = MCBinaryExpr::GT; 1151 return 3; 1152 case AsmToken::GreaterEqual: 1153 Kind = MCBinaryExpr::GTE; 1154 return 3; 1155 1156 // Intermediate Precedence: <<, >> 1157 case AsmToken::LessLess: 1158 Kind = MCBinaryExpr::Shl; 1159 return 4; 1160 case AsmToken::GreaterGreater: 1161 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1162 return 4; 1163 1164 // High Intermediate Precedence: +, - 1165 case AsmToken::Plus: 1166 Kind = MCBinaryExpr::Add; 1167 return 5; 1168 case AsmToken::Minus: 1169 Kind = MCBinaryExpr::Sub; 1170 return 5; 1171 1172 // Highest Precedence: *, /, % 1173 case AsmToken::Star: 1174 Kind = MCBinaryExpr::Mul; 1175 return 6; 1176 case AsmToken::Slash: 1177 Kind = MCBinaryExpr::Div; 1178 return 6; 1179 case AsmToken::Percent: 1180 Kind = MCBinaryExpr::Mod; 1181 return 6; 1182 } 1183 } 1184 1185 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, 1186 MCBinaryExpr::Opcode &Kind, 1187 bool ShouldUseLogicalShr) { 1188 switch (K) { 1189 default: 1190 return 0; // not a binop. 1191 1192 // Lowest Precedence: &&, || 1193 case AsmToken::AmpAmp: 1194 Kind = MCBinaryExpr::LAnd; 1195 return 2; 1196 case AsmToken::PipePipe: 1197 Kind = MCBinaryExpr::LOr; 1198 return 1; 1199 1200 // Low Precedence: ==, !=, <>, <, <=, >, >= 1201 case AsmToken::EqualEqual: 1202 Kind = MCBinaryExpr::EQ; 1203 return 3; 1204 case AsmToken::ExclaimEqual: 1205 case AsmToken::LessGreater: 1206 Kind = MCBinaryExpr::NE; 1207 return 3; 1208 case AsmToken::Less: 1209 Kind = MCBinaryExpr::LT; 1210 return 3; 1211 case AsmToken::LessEqual: 1212 Kind = MCBinaryExpr::LTE; 1213 return 3; 1214 case AsmToken::Greater: 1215 Kind = MCBinaryExpr::GT; 1216 return 3; 1217 case AsmToken::GreaterEqual: 1218 Kind = MCBinaryExpr::GTE; 1219 return 3; 1220 1221 // Low Intermediate Precedence: +, - 1222 case AsmToken::Plus: 1223 Kind = MCBinaryExpr::Add; 1224 return 4; 1225 case AsmToken::Minus: 1226 Kind = MCBinaryExpr::Sub; 1227 return 4; 1228 1229 // High Intermediate Precedence: |, &, ^ 1230 // 1231 // FIXME: gas seems to support '!' as an infix operator? 1232 case AsmToken::Pipe: 1233 Kind = MCBinaryExpr::Or; 1234 return 5; 1235 case AsmToken::Caret: 1236 Kind = MCBinaryExpr::Xor; 1237 return 5; 1238 case AsmToken::Amp: 1239 Kind = MCBinaryExpr::And; 1240 return 5; 1241 1242 // Highest Precedence: *, /, %, <<, >> 1243 case AsmToken::Star: 1244 Kind = MCBinaryExpr::Mul; 1245 return 6; 1246 case AsmToken::Slash: 1247 Kind = MCBinaryExpr::Div; 1248 return 6; 1249 case AsmToken::Percent: 1250 Kind = MCBinaryExpr::Mod; 1251 return 6; 1252 case AsmToken::LessLess: 1253 Kind = MCBinaryExpr::Shl; 1254 return 6; 1255 case AsmToken::GreaterGreater: 1256 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1257 return 6; 1258 } 1259 } 1260 1261 unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K, 1262 MCBinaryExpr::Opcode &Kind) { 1263 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); 1264 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr) 1265 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr); 1266 } 1267 1268 /// \brief Parse all binary operators with precedence >= 'Precedence'. 1269 /// Res contains the LHS of the expression on input. 1270 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, 1271 SMLoc &EndLoc) { 1272 while (1) { 1273 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; 1274 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind); 1275 1276 // If the next token is lower precedence than we are allowed to eat, return 1277 // successfully with what we ate already. 1278 if (TokPrec < Precedence) 1279 return false; 1280 1281 Lex(); 1282 1283 // Eat the next primary expression. 1284 const MCExpr *RHS; 1285 if (parsePrimaryExpr(RHS, EndLoc)) 1286 return true; 1287 1288 // If BinOp binds less tightly with RHS than the operator after RHS, let 1289 // the pending operator take RHS as its LHS. 1290 MCBinaryExpr::Opcode Dummy; 1291 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); 1292 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) 1293 return true; 1294 1295 // Merge LHS and RHS according to operator. 1296 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext()); 1297 } 1298 } 1299 1300 /// ParseStatement: 1301 /// ::= EndOfStatement 1302 /// ::= Label* Directive ...Operands... EndOfStatement 1303 /// ::= Label* Identifier OperandList* EndOfStatement 1304 bool AsmParser::parseStatement(ParseStatementInfo &Info, 1305 MCAsmParserSemaCallback *SI) { 1306 if (Lexer.is(AsmToken::EndOfStatement)) { 1307 Out.AddBlankLine(); 1308 Lex(); 1309 return false; 1310 } 1311 1312 // Statements always start with an identifier or are a full line comment. 1313 AsmToken ID = getTok(); 1314 SMLoc IDLoc = ID.getLoc(); 1315 StringRef IDVal; 1316 int64_t LocalLabelVal = -1; 1317 // A full line comment is a '#' as the first token. 1318 if (Lexer.is(AsmToken::Hash)) 1319 return parseCppHashLineFilenameComment(IDLoc); 1320 1321 // Allow an integer followed by a ':' as a directional local label. 1322 if (Lexer.is(AsmToken::Integer)) { 1323 LocalLabelVal = getTok().getIntVal(); 1324 if (LocalLabelVal < 0) { 1325 if (!TheCondState.Ignore) 1326 return TokError("unexpected token at start of statement"); 1327 IDVal = ""; 1328 } else { 1329 IDVal = getTok().getString(); 1330 Lex(); // Consume the integer token to be used as an identifier token. 1331 if (Lexer.getKind() != AsmToken::Colon) { 1332 if (!TheCondState.Ignore) 1333 return TokError("unexpected token at start of statement"); 1334 } 1335 } 1336 } else if (Lexer.is(AsmToken::Dot)) { 1337 // Treat '.' as a valid identifier in this context. 1338 Lex(); 1339 IDVal = "."; 1340 } else if (Lexer.is(AsmToken::LCurly)) { 1341 // Treat '{' as a valid identifier in this context. 1342 Lex(); 1343 IDVal = "{"; 1344 1345 } else if (Lexer.is(AsmToken::RCurly)) { 1346 // Treat '}' as a valid identifier in this context. 1347 Lex(); 1348 IDVal = "}"; 1349 } else if (parseIdentifier(IDVal)) { 1350 if (!TheCondState.Ignore) 1351 return TokError("unexpected token at start of statement"); 1352 IDVal = ""; 1353 } 1354 1355 // Handle conditional assembly here before checking for skipping. We 1356 // have to do this so that .endif isn't skipped in a ".if 0" block for 1357 // example. 1358 StringMap<DirectiveKind>::const_iterator DirKindIt = 1359 DirectiveKindMap.find(IDVal); 1360 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) 1361 ? DK_NO_DIRECTIVE 1362 : DirKindIt->getValue(); 1363 switch (DirKind) { 1364 default: 1365 break; 1366 case DK_IF: 1367 case DK_IFEQ: 1368 case DK_IFGE: 1369 case DK_IFGT: 1370 case DK_IFLE: 1371 case DK_IFLT: 1372 case DK_IFNE: 1373 return parseDirectiveIf(IDLoc, DirKind); 1374 case DK_IFB: 1375 return parseDirectiveIfb(IDLoc, true); 1376 case DK_IFNB: 1377 return parseDirectiveIfb(IDLoc, false); 1378 case DK_IFC: 1379 return parseDirectiveIfc(IDLoc, true); 1380 case DK_IFEQS: 1381 return parseDirectiveIfeqs(IDLoc, true); 1382 case DK_IFNC: 1383 return parseDirectiveIfc(IDLoc, false); 1384 case DK_IFNES: 1385 return parseDirectiveIfeqs(IDLoc, false); 1386 case DK_IFDEF: 1387 return parseDirectiveIfdef(IDLoc, true); 1388 case DK_IFNDEF: 1389 case DK_IFNOTDEF: 1390 return parseDirectiveIfdef(IDLoc, false); 1391 case DK_ELSEIF: 1392 return parseDirectiveElseIf(IDLoc); 1393 case DK_ELSE: 1394 return parseDirectiveElse(IDLoc); 1395 case DK_ENDIF: 1396 return parseDirectiveEndIf(IDLoc); 1397 } 1398 1399 // Ignore the statement if in the middle of inactive conditional 1400 // (e.g. ".if 0"). 1401 if (TheCondState.Ignore) { 1402 eatToEndOfStatement(); 1403 return false; 1404 } 1405 1406 // FIXME: Recurse on local labels? 1407 1408 // See what kind of statement we have. 1409 switch (Lexer.getKind()) { 1410 case AsmToken::Colon: { 1411 if (!getTargetParser().isLabel(ID)) 1412 break; 1413 checkForValidSection(); 1414 1415 // identifier ':' -> Label. 1416 Lex(); 1417 1418 // Diagnose attempt to use '.' as a label. 1419 if (IDVal == ".") 1420 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); 1421 1422 // Diagnose attempt to use a variable as a label. 1423 // 1424 // FIXME: Diagnostics. Note the location of the definition as a label. 1425 // FIXME: This doesn't diagnose assignment to a symbol which has been 1426 // implicitly marked as external. 1427 MCSymbol *Sym; 1428 if (LocalLabelVal == -1) { 1429 if (ParsingInlineAsm && SI) { 1430 StringRef RewrittenLabel = 1431 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true); 1432 assert(RewrittenLabel.size() && 1433 "We should have an internal name here."); 1434 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(), 1435 RewrittenLabel); 1436 IDVal = RewrittenLabel; 1437 } 1438 Sym = getContext().getOrCreateSymbol(IDVal); 1439 } else 1440 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal); 1441 1442 Sym->redefineIfPossible(); 1443 1444 if (!Sym->isUndefined() || Sym->isVariable()) 1445 return Error(IDLoc, "invalid symbol redefinition"); 1446 1447 // Emit the label. 1448 if (!ParsingInlineAsm) 1449 Out.EmitLabel(Sym); 1450 1451 // If we are generating dwarf for assembly source files then gather the 1452 // info to make a dwarf label entry for this label if needed. 1453 if (getContext().getGenDwarfForAssembly()) 1454 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), 1455 IDLoc); 1456 1457 getTargetParser().onLabelParsed(Sym); 1458 1459 // Consume any end of statement token, if present, to avoid spurious 1460 // AddBlankLine calls(). 1461 if (Lexer.is(AsmToken::EndOfStatement)) { 1462 Lex(); 1463 if (Lexer.is(AsmToken::Eof)) 1464 return false; 1465 } 1466 1467 return false; 1468 } 1469 1470 case AsmToken::Equal: 1471 if (!getTargetParser().equalIsAsmAssignment()) 1472 break; 1473 // identifier '=' ... -> assignment statement 1474 Lex(); 1475 1476 return parseAssignment(IDVal, true); 1477 1478 default: // Normal instruction or directive. 1479 break; 1480 } 1481 1482 // If macros are enabled, check to see if this is a macro instantiation. 1483 if (areMacrosEnabled()) 1484 if (const MCAsmMacro *M = lookupMacro(IDVal)) { 1485 return handleMacroEntry(M, IDLoc); 1486 } 1487 1488 // Otherwise, we have a normal instruction or directive. 1489 1490 // Directives start with "." 1491 if (IDVal[0] == '.' && IDVal != ".") { 1492 // There are several entities interested in parsing directives: 1493 // 1494 // 1. The target-specific assembly parser. Some directives are target 1495 // specific or may potentially behave differently on certain targets. 1496 // 2. Asm parser extensions. For example, platform-specific parsers 1497 // (like the ELF parser) register themselves as extensions. 1498 // 3. The generic directive parser implemented by this class. These are 1499 // all the directives that behave in a target and platform independent 1500 // manner, or at least have a default behavior that's shared between 1501 // all targets and platforms. 1502 1503 // First query the target-specific parser. It will return 'true' if it 1504 // isn't interested in this directive. 1505 if (!getTargetParser().ParseDirective(ID)) 1506 return false; 1507 1508 // Next, check the extension directive map to see if any extension has 1509 // registered itself to parse this directive. 1510 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 1511 ExtensionDirectiveMap.lookup(IDVal); 1512 if (Handler.first) 1513 return (*Handler.second)(Handler.first, IDVal, IDLoc); 1514 1515 // Finally, if no one else is interested in this directive, it must be 1516 // generic and familiar to this class. 1517 switch (DirKind) { 1518 default: 1519 break; 1520 case DK_SET: 1521 case DK_EQU: 1522 return parseDirectiveSet(IDVal, true); 1523 case DK_EQUIV: 1524 return parseDirectiveSet(IDVal, false); 1525 case DK_ASCII: 1526 return parseDirectiveAscii(IDVal, false); 1527 case DK_ASCIZ: 1528 case DK_STRING: 1529 return parseDirectiveAscii(IDVal, true); 1530 case DK_BYTE: 1531 return parseDirectiveValue(1); 1532 case DK_SHORT: 1533 case DK_VALUE: 1534 case DK_2BYTE: 1535 return parseDirectiveValue(2); 1536 case DK_LONG: 1537 case DK_INT: 1538 case DK_4BYTE: 1539 return parseDirectiveValue(4); 1540 case DK_QUAD: 1541 case DK_8BYTE: 1542 return parseDirectiveValue(8); 1543 case DK_OCTA: 1544 return parseDirectiveOctaValue(); 1545 case DK_SINGLE: 1546 case DK_FLOAT: 1547 return parseDirectiveRealValue(APFloat::IEEEsingle); 1548 case DK_DOUBLE: 1549 return parseDirectiveRealValue(APFloat::IEEEdouble); 1550 case DK_ALIGN: { 1551 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); 1552 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1); 1553 } 1554 case DK_ALIGN32: { 1555 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes(); 1556 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4); 1557 } 1558 case DK_BALIGN: 1559 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1); 1560 case DK_BALIGNW: 1561 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2); 1562 case DK_BALIGNL: 1563 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4); 1564 case DK_P2ALIGN: 1565 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1); 1566 case DK_P2ALIGNW: 1567 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2); 1568 case DK_P2ALIGNL: 1569 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4); 1570 case DK_ORG: 1571 return parseDirectiveOrg(); 1572 case DK_FILL: 1573 return parseDirectiveFill(); 1574 case DK_ZERO: 1575 return parseDirectiveZero(); 1576 case DK_EXTERN: 1577 eatToEndOfStatement(); // .extern is the default, ignore it. 1578 return false; 1579 case DK_GLOBL: 1580 case DK_GLOBAL: 1581 return parseDirectiveSymbolAttribute(MCSA_Global); 1582 case DK_LAZY_REFERENCE: 1583 return parseDirectiveSymbolAttribute(MCSA_LazyReference); 1584 case DK_NO_DEAD_STRIP: 1585 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip); 1586 case DK_SYMBOL_RESOLVER: 1587 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver); 1588 case DK_PRIVATE_EXTERN: 1589 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern); 1590 case DK_REFERENCE: 1591 return parseDirectiveSymbolAttribute(MCSA_Reference); 1592 case DK_WEAK_DEFINITION: 1593 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition); 1594 case DK_WEAK_REFERENCE: 1595 return parseDirectiveSymbolAttribute(MCSA_WeakReference); 1596 case DK_WEAK_DEF_CAN_BE_HIDDEN: 1597 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate); 1598 case DK_COMM: 1599 case DK_COMMON: 1600 return parseDirectiveComm(/*IsLocal=*/false); 1601 case DK_LCOMM: 1602 return parseDirectiveComm(/*IsLocal=*/true); 1603 case DK_ABORT: 1604 return parseDirectiveAbort(); 1605 case DK_INCLUDE: 1606 return parseDirectiveInclude(); 1607 case DK_INCBIN: 1608 return parseDirectiveIncbin(); 1609 case DK_CODE16: 1610 case DK_CODE16GCC: 1611 return TokError(Twine(IDVal) + " not supported yet"); 1612 case DK_REPT: 1613 return parseDirectiveRept(IDLoc, IDVal); 1614 case DK_IRP: 1615 return parseDirectiveIrp(IDLoc); 1616 case DK_IRPC: 1617 return parseDirectiveIrpc(IDLoc); 1618 case DK_ENDR: 1619 return parseDirectiveEndr(IDLoc); 1620 case DK_BUNDLE_ALIGN_MODE: 1621 return parseDirectiveBundleAlignMode(); 1622 case DK_BUNDLE_LOCK: 1623 return parseDirectiveBundleLock(); 1624 case DK_BUNDLE_UNLOCK: 1625 return parseDirectiveBundleUnlock(); 1626 case DK_SLEB128: 1627 return parseDirectiveLEB128(true); 1628 case DK_ULEB128: 1629 return parseDirectiveLEB128(false); 1630 case DK_SPACE: 1631 case DK_SKIP: 1632 return parseDirectiveSpace(IDVal); 1633 case DK_FILE: 1634 return parseDirectiveFile(IDLoc); 1635 case DK_LINE: 1636 return parseDirectiveLine(); 1637 case DK_LOC: 1638 return parseDirectiveLoc(); 1639 case DK_STABS: 1640 return parseDirectiveStabs(); 1641 case DK_CFI_SECTIONS: 1642 return parseDirectiveCFISections(); 1643 case DK_CFI_STARTPROC: 1644 return parseDirectiveCFIStartProc(); 1645 case DK_CFI_ENDPROC: 1646 return parseDirectiveCFIEndProc(); 1647 case DK_CFI_DEF_CFA: 1648 return parseDirectiveCFIDefCfa(IDLoc); 1649 case DK_CFI_DEF_CFA_OFFSET: 1650 return parseDirectiveCFIDefCfaOffset(); 1651 case DK_CFI_ADJUST_CFA_OFFSET: 1652 return parseDirectiveCFIAdjustCfaOffset(); 1653 case DK_CFI_DEF_CFA_REGISTER: 1654 return parseDirectiveCFIDefCfaRegister(IDLoc); 1655 case DK_CFI_OFFSET: 1656 return parseDirectiveCFIOffset(IDLoc); 1657 case DK_CFI_REL_OFFSET: 1658 return parseDirectiveCFIRelOffset(IDLoc); 1659 case DK_CFI_PERSONALITY: 1660 return parseDirectiveCFIPersonalityOrLsda(true); 1661 case DK_CFI_LSDA: 1662 return parseDirectiveCFIPersonalityOrLsda(false); 1663 case DK_CFI_REMEMBER_STATE: 1664 return parseDirectiveCFIRememberState(); 1665 case DK_CFI_RESTORE_STATE: 1666 return parseDirectiveCFIRestoreState(); 1667 case DK_CFI_SAME_VALUE: 1668 return parseDirectiveCFISameValue(IDLoc); 1669 case DK_CFI_RESTORE: 1670 return parseDirectiveCFIRestore(IDLoc); 1671 case DK_CFI_ESCAPE: 1672 return parseDirectiveCFIEscape(); 1673 case DK_CFI_SIGNAL_FRAME: 1674 return parseDirectiveCFISignalFrame(); 1675 case DK_CFI_UNDEFINED: 1676 return parseDirectiveCFIUndefined(IDLoc); 1677 case DK_CFI_REGISTER: 1678 return parseDirectiveCFIRegister(IDLoc); 1679 case DK_CFI_WINDOW_SAVE: 1680 return parseDirectiveCFIWindowSave(); 1681 case DK_MACROS_ON: 1682 case DK_MACROS_OFF: 1683 return parseDirectiveMacrosOnOff(IDVal); 1684 case DK_MACRO: 1685 return parseDirectiveMacro(IDLoc); 1686 case DK_EXITM: 1687 return parseDirectiveExitMacro(IDVal); 1688 case DK_ENDM: 1689 case DK_ENDMACRO: 1690 return parseDirectiveEndMacro(IDVal); 1691 case DK_PURGEM: 1692 return parseDirectivePurgeMacro(IDLoc); 1693 case DK_END: 1694 return parseDirectiveEnd(IDLoc); 1695 case DK_ERR: 1696 return parseDirectiveError(IDLoc, false); 1697 case DK_ERROR: 1698 return parseDirectiveError(IDLoc, true); 1699 case DK_WARNING: 1700 return parseDirectiveWarning(IDLoc); 1701 case DK_RELOC: 1702 return parseDirectiveReloc(IDLoc); 1703 } 1704 1705 return Error(IDLoc, "unknown directive"); 1706 } 1707 1708 // __asm _emit or __asm __emit 1709 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || 1710 IDVal == "_EMIT" || IDVal == "__EMIT")) 1711 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); 1712 1713 // __asm align 1714 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) 1715 return parseDirectiveMSAlign(IDLoc, Info); 1716 1717 checkForValidSection(); 1718 1719 // Canonicalize the opcode to lower case. 1720 std::string OpcodeStr = IDVal.lower(); 1721 ParseInstructionInfo IInfo(Info.AsmRewrites); 1722 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID, 1723 Info.ParsedOperands); 1724 Info.ParseError = HadError; 1725 1726 // Dump the parsed representation, if requested. 1727 if (getShowParsedOperands()) { 1728 SmallString<256> Str; 1729 raw_svector_ostream OS(Str); 1730 OS << "parsed instruction: ["; 1731 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { 1732 if (i != 0) 1733 OS << ", "; 1734 Info.ParsedOperands[i]->print(OS); 1735 } 1736 OS << "]"; 1737 1738 printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); 1739 } 1740 1741 // If we are generating dwarf for the current section then generate a .loc 1742 // directive for the instruction. 1743 if (!HadError && getContext().getGenDwarfForAssembly() && 1744 getContext().getGenDwarfSectionSyms().count( 1745 getStreamer().getCurrentSection().first)) { 1746 unsigned Line; 1747 if (ActiveMacros.empty()) 1748 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); 1749 else 1750 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc, 1751 ActiveMacros.front()->ExitBuffer); 1752 1753 // If we previously parsed a cpp hash file line comment then make sure the 1754 // current Dwarf File is for the CppHashFilename if not then emit the 1755 // Dwarf File table for it and adjust the line number for the .loc. 1756 if (CppHashFilename.size()) { 1757 unsigned FileNumber = getStreamer().EmitDwarfFileDirective( 1758 0, StringRef(), CppHashFilename); 1759 getContext().setGenDwarfFileNumber(FileNumber); 1760 1761 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's 1762 // cache with the different Loc from the call above we save the last 1763 // info we queried here with SrcMgr.FindLineNumber(). 1764 unsigned CppHashLocLineNo; 1765 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf) 1766 CppHashLocLineNo = LastQueryLine; 1767 else { 1768 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf); 1769 LastQueryLine = CppHashLocLineNo; 1770 LastQueryIDLoc = CppHashLoc; 1771 LastQueryBuffer = CppHashBuf; 1772 } 1773 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo); 1774 } 1775 1776 getStreamer().EmitDwarfLocDirective( 1777 getContext().getGenDwarfFileNumber(), Line, 0, 1778 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, 1779 StringRef()); 1780 } 1781 1782 // If parsing succeeded, match the instruction. 1783 if (!HadError) { 1784 uint64_t ErrorInfo; 1785 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode, 1786 Info.ParsedOperands, Out, 1787 ErrorInfo, ParsingInlineAsm); 1788 } 1789 1790 // Don't skip the rest of the line, the instruction parser is responsible for 1791 // that. 1792 return false; 1793 } 1794 1795 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line 1796 /// since they may not be able to be tokenized to get to the end of line token. 1797 void AsmParser::eatToEndOfLine() { 1798 if (!Lexer.is(AsmToken::EndOfStatement)) 1799 Lexer.LexUntilEndOfLine(); 1800 // Eat EOL. 1801 Lex(); 1802 } 1803 1804 /// parseCppHashLineFilenameComment as this: 1805 /// ::= # number "filename" 1806 /// or just as a full line comment if it doesn't have a number and a string. 1807 bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) { 1808 Lex(); // Eat the hash token. 1809 1810 if (getLexer().isNot(AsmToken::Integer)) { 1811 // Consume the line since in cases it is not a well-formed line directive, 1812 // as if were simply a full line comment. 1813 eatToEndOfLine(); 1814 return false; 1815 } 1816 1817 int64_t LineNumber = getTok().getIntVal(); 1818 Lex(); 1819 1820 if (getLexer().isNot(AsmToken::String)) { 1821 eatToEndOfLine(); 1822 return false; 1823 } 1824 1825 StringRef Filename = getTok().getString(); 1826 // Get rid of the enclosing quotes. 1827 Filename = Filename.substr(1, Filename.size() - 2); 1828 1829 // Save the SMLoc, Filename and LineNumber for later use by diagnostics. 1830 CppHashLoc = L; 1831 CppHashFilename = Filename; 1832 CppHashLineNumber = LineNumber; 1833 CppHashBuf = CurBuffer; 1834 1835 // Ignore any trailing characters, they're just comment. 1836 eatToEndOfLine(); 1837 return false; 1838 } 1839 1840 /// \brief will use the last parsed cpp hash line filename comment 1841 /// for the Filename and LineNo if any in the diagnostic. 1842 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { 1843 const AsmParser *Parser = static_cast<const AsmParser *>(Context); 1844 raw_ostream &OS = errs(); 1845 1846 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); 1847 SMLoc DiagLoc = Diag.getLoc(); 1848 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 1849 unsigned CppHashBuf = 1850 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc); 1851 1852 // Like SourceMgr::printMessage() we need to print the include stack if any 1853 // before printing the message. 1854 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 1855 if (!Parser->SavedDiagHandler && DiagCurBuffer && 1856 DiagCurBuffer != DiagSrcMgr.getMainFileID()) { 1857 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); 1858 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); 1859 } 1860 1861 // If we have not parsed a cpp hash line filename comment or the source 1862 // manager changed or buffer changed (like in a nested include) then just 1863 // print the normal diagnostic using its Filename and LineNo. 1864 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr || 1865 DiagBuf != CppHashBuf) { 1866 if (Parser->SavedDiagHandler) 1867 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); 1868 else 1869 Diag.print(nullptr, OS); 1870 return; 1871 } 1872 1873 // Use the CppHashFilename and calculate a line number based on the 1874 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for 1875 // the diagnostic. 1876 const std::string &Filename = Parser->CppHashFilename; 1877 1878 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); 1879 int CppHashLocLineNo = 1880 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf); 1881 int LineNo = 1882 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); 1883 1884 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, 1885 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), 1886 Diag.getLineContents(), Diag.getRanges()); 1887 1888 if (Parser->SavedDiagHandler) 1889 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); 1890 else 1891 NewDiag.print(nullptr, OS); 1892 } 1893 1894 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The 1895 // difference being that that function accepts '@' as part of identifiers and 1896 // we can't do that. AsmLexer.cpp should probably be changed to handle 1897 // '@' as a special case when needed. 1898 static bool isIdentifierChar(char c) { 1899 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' || 1900 c == '.'; 1901 } 1902 1903 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, 1904 ArrayRef<MCAsmMacroParameter> Parameters, 1905 ArrayRef<MCAsmMacroArgument> A, 1906 bool EnableAtPseudoVariable, SMLoc L) { 1907 unsigned NParameters = Parameters.size(); 1908 bool HasVararg = NParameters ? Parameters.back().Vararg : false; 1909 if ((!IsDarwin || NParameters != 0) && NParameters != A.size()) 1910 return Error(L, "Wrong number of arguments"); 1911 1912 // A macro without parameters is handled differently on Darwin: 1913 // gas accepts no arguments and does no substitutions 1914 while (!Body.empty()) { 1915 // Scan for the next substitution. 1916 std::size_t End = Body.size(), Pos = 0; 1917 for (; Pos != End; ++Pos) { 1918 // Check for a substitution or escape. 1919 if (IsDarwin && !NParameters) { 1920 // This macro has no parameters, look for $0, $1, etc. 1921 if (Body[Pos] != '$' || Pos + 1 == End) 1922 continue; 1923 1924 char Next = Body[Pos + 1]; 1925 if (Next == '$' || Next == 'n' || 1926 isdigit(static_cast<unsigned char>(Next))) 1927 break; 1928 } else { 1929 // This macro has parameters, look for \foo, \bar, etc. 1930 if (Body[Pos] == '\\' && Pos + 1 != End) 1931 break; 1932 } 1933 } 1934 1935 // Add the prefix. 1936 OS << Body.slice(0, Pos); 1937 1938 // Check if we reached the end. 1939 if (Pos == End) 1940 break; 1941 1942 if (IsDarwin && !NParameters) { 1943 switch (Body[Pos + 1]) { 1944 // $$ => $ 1945 case '$': 1946 OS << '$'; 1947 break; 1948 1949 // $n => number of arguments 1950 case 'n': 1951 OS << A.size(); 1952 break; 1953 1954 // $[0-9] => argument 1955 default: { 1956 // Missing arguments are ignored. 1957 unsigned Index = Body[Pos + 1] - '0'; 1958 if (Index >= A.size()) 1959 break; 1960 1961 // Otherwise substitute with the token values, with spaces eliminated. 1962 for (const AsmToken &Token : A[Index]) 1963 OS << Token.getString(); 1964 break; 1965 } 1966 } 1967 Pos += 2; 1968 } else { 1969 unsigned I = Pos + 1; 1970 1971 // Check for the \@ pseudo-variable. 1972 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End) 1973 ++I; 1974 else 1975 while (isIdentifierChar(Body[I]) && I + 1 != End) 1976 ++I; 1977 1978 const char *Begin = Body.data() + Pos + 1; 1979 StringRef Argument(Begin, I - (Pos + 1)); 1980 unsigned Index = 0; 1981 1982 if (Argument == "@") { 1983 OS << NumOfMacroInstantiations; 1984 Pos += 2; 1985 } else { 1986 for (; Index < NParameters; ++Index) 1987 if (Parameters[Index].Name == Argument) 1988 break; 1989 1990 if (Index == NParameters) { 1991 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 1992 Pos += 3; 1993 else { 1994 OS << '\\' << Argument; 1995 Pos = I; 1996 } 1997 } else { 1998 bool VarargParameter = HasVararg && Index == (NParameters - 1); 1999 for (const AsmToken &Token : A[Index]) 2000 // We expect no quotes around the string's contents when 2001 // parsing for varargs. 2002 if (Token.getKind() != AsmToken::String || VarargParameter) 2003 OS << Token.getString(); 2004 else 2005 OS << Token.getStringContents(); 2006 2007 Pos += 1 + Argument.size(); 2008 } 2009 } 2010 } 2011 // Update the scan point. 2012 Body = Body.substr(Pos); 2013 } 2014 2015 return false; 2016 } 2017 2018 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL, 2019 size_t CondStackDepth) 2020 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL), 2021 CondStackDepth(CondStackDepth) {} 2022 2023 static bool isOperator(AsmToken::TokenKind kind) { 2024 switch (kind) { 2025 default: 2026 return false; 2027 case AsmToken::Plus: 2028 case AsmToken::Minus: 2029 case AsmToken::Tilde: 2030 case AsmToken::Slash: 2031 case AsmToken::Star: 2032 case AsmToken::Dot: 2033 case AsmToken::Equal: 2034 case AsmToken::EqualEqual: 2035 case AsmToken::Pipe: 2036 case AsmToken::PipePipe: 2037 case AsmToken::Caret: 2038 case AsmToken::Amp: 2039 case AsmToken::AmpAmp: 2040 case AsmToken::Exclaim: 2041 case AsmToken::ExclaimEqual: 2042 case AsmToken::Percent: 2043 case AsmToken::Less: 2044 case AsmToken::LessEqual: 2045 case AsmToken::LessLess: 2046 case AsmToken::LessGreater: 2047 case AsmToken::Greater: 2048 case AsmToken::GreaterEqual: 2049 case AsmToken::GreaterGreater: 2050 return true; 2051 } 2052 } 2053 2054 namespace { 2055 class AsmLexerSkipSpaceRAII { 2056 public: 2057 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { 2058 Lexer.setSkipSpace(SkipSpace); 2059 } 2060 2061 ~AsmLexerSkipSpaceRAII() { 2062 Lexer.setSkipSpace(true); 2063 } 2064 2065 private: 2066 AsmLexer &Lexer; 2067 }; 2068 } 2069 2070 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { 2071 2072 if (Vararg) { 2073 if (Lexer.isNot(AsmToken::EndOfStatement)) { 2074 StringRef Str = parseStringToEndOfStatement(); 2075 MA.emplace_back(AsmToken::String, Str); 2076 } 2077 return false; 2078 } 2079 2080 unsigned ParenLevel = 0; 2081 unsigned AddTokens = 0; 2082 2083 // Darwin doesn't use spaces to delmit arguments. 2084 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); 2085 2086 for (;;) { 2087 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) 2088 return TokError("unexpected token in macro instantiation"); 2089 2090 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) 2091 break; 2092 2093 if (Lexer.is(AsmToken::Space)) { 2094 Lex(); // Eat spaces 2095 2096 // Spaces can delimit parameters, but could also be part an expression. 2097 // If the token after a space is an operator, add the token and the next 2098 // one into this argument 2099 if (!IsDarwin) { 2100 if (isOperator(Lexer.getKind())) { 2101 // Check to see whether the token is used as an operator, 2102 // or part of an identifier 2103 const char *NextChar = getTok().getEndLoc().getPointer(); 2104 if (*NextChar == ' ') 2105 AddTokens = 2; 2106 } 2107 2108 if (!AddTokens && ParenLevel == 0) { 2109 break; 2110 } 2111 } 2112 } 2113 2114 // handleMacroEntry relies on not advancing the lexer here 2115 // to be able to fill in the remaining default parameter values 2116 if (Lexer.is(AsmToken::EndOfStatement)) 2117 break; 2118 2119 // Adjust the current parentheses level. 2120 if (Lexer.is(AsmToken::LParen)) 2121 ++ParenLevel; 2122 else if (Lexer.is(AsmToken::RParen) && ParenLevel) 2123 --ParenLevel; 2124 2125 // Append the token to the current argument list. 2126 MA.push_back(getTok()); 2127 if (AddTokens) 2128 AddTokens--; 2129 Lex(); 2130 } 2131 2132 if (ParenLevel != 0) 2133 return TokError("unbalanced parentheses in macro argument"); 2134 return false; 2135 } 2136 2137 // Parse the macro instantiation arguments. 2138 bool AsmParser::parseMacroArguments(const MCAsmMacro *M, 2139 MCAsmMacroArguments &A) { 2140 const unsigned NParameters = M ? M->Parameters.size() : 0; 2141 bool NamedParametersFound = false; 2142 SmallVector<SMLoc, 4> FALocs; 2143 2144 A.resize(NParameters); 2145 FALocs.resize(NParameters); 2146 2147 // Parse two kinds of macro invocations: 2148 // - macros defined without any parameters accept an arbitrary number of them 2149 // - macros defined with parameters accept at most that many of them 2150 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; 2151 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; 2152 ++Parameter) { 2153 SMLoc IDLoc = Lexer.getLoc(); 2154 MCAsmMacroParameter FA; 2155 2156 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { 2157 if (parseIdentifier(FA.Name)) { 2158 Error(IDLoc, "invalid argument identifier for formal argument"); 2159 eatToEndOfStatement(); 2160 return true; 2161 } 2162 2163 if (!Lexer.is(AsmToken::Equal)) { 2164 TokError("expected '=' after formal parameter identifier"); 2165 eatToEndOfStatement(); 2166 return true; 2167 } 2168 Lex(); 2169 2170 NamedParametersFound = true; 2171 } 2172 2173 if (NamedParametersFound && FA.Name.empty()) { 2174 Error(IDLoc, "cannot mix positional and keyword arguments"); 2175 eatToEndOfStatement(); 2176 return true; 2177 } 2178 2179 bool Vararg = HasVararg && Parameter == (NParameters - 1); 2180 if (parseMacroArgument(FA.Value, Vararg)) 2181 return true; 2182 2183 unsigned PI = Parameter; 2184 if (!FA.Name.empty()) { 2185 unsigned FAI = 0; 2186 for (FAI = 0; FAI < NParameters; ++FAI) 2187 if (M->Parameters[FAI].Name == FA.Name) 2188 break; 2189 2190 if (FAI >= NParameters) { 2191 assert(M && "expected macro to be defined"); 2192 Error(IDLoc, 2193 "parameter named '" + FA.Name + "' does not exist for macro '" + 2194 M->Name + "'"); 2195 return true; 2196 } 2197 PI = FAI; 2198 } 2199 2200 if (!FA.Value.empty()) { 2201 if (A.size() <= PI) 2202 A.resize(PI + 1); 2203 A[PI] = FA.Value; 2204 2205 if (FALocs.size() <= PI) 2206 FALocs.resize(PI + 1); 2207 2208 FALocs[PI] = Lexer.getLoc(); 2209 } 2210 2211 // At the end of the statement, fill in remaining arguments that have 2212 // default values. If there aren't any, then the next argument is 2213 // required but missing 2214 if (Lexer.is(AsmToken::EndOfStatement)) { 2215 bool Failure = false; 2216 for (unsigned FAI = 0; FAI < NParameters; ++FAI) { 2217 if (A[FAI].empty()) { 2218 if (M->Parameters[FAI].Required) { 2219 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), 2220 "missing value for required parameter " 2221 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); 2222 Failure = true; 2223 } 2224 2225 if (!M->Parameters[FAI].Value.empty()) 2226 A[FAI] = M->Parameters[FAI].Value; 2227 } 2228 } 2229 return Failure; 2230 } 2231 2232 if (Lexer.is(AsmToken::Comma)) 2233 Lex(); 2234 } 2235 2236 return TokError("too many positional arguments"); 2237 } 2238 2239 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) { 2240 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name); 2241 return (I == MacroMap.end()) ? nullptr : &I->getValue(); 2242 } 2243 2244 void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) { 2245 MacroMap.insert(std::make_pair(Name, std::move(Macro))); 2246 } 2247 2248 void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); } 2249 2250 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { 2251 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate 2252 // this, although we should protect against infinite loops. 2253 if (ActiveMacros.size() == 20) 2254 return TokError("macros cannot be nested more than 20 levels deep"); 2255 2256 MCAsmMacroArguments A; 2257 if (parseMacroArguments(M, A)) 2258 return true; 2259 2260 // Macro instantiation is lexical, unfortunately. We construct a new buffer 2261 // to hold the macro body with substitutions. 2262 SmallString<256> Buf; 2263 StringRef Body = M->Body; 2264 raw_svector_ostream OS(Buf); 2265 2266 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc())) 2267 return true; 2268 2269 // We include the .endmacro in the buffer as our cue to exit the macro 2270 // instantiation. 2271 OS << ".endmacro\n"; 2272 2273 std::unique_ptr<MemoryBuffer> Instantiation = 2274 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 2275 2276 // Create the macro instantiation object and add to the current macro 2277 // instantiation stack. 2278 MacroInstantiation *MI = new MacroInstantiation( 2279 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()); 2280 ActiveMacros.push_back(MI); 2281 2282 ++NumOfMacroInstantiations; 2283 2284 // Jump to the macro instantiation and prime the lexer. 2285 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 2286 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 2287 Lex(); 2288 2289 return false; 2290 } 2291 2292 void AsmParser::handleMacroExit() { 2293 // Jump to the EndOfStatement we should return to, and consume it. 2294 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); 2295 Lex(); 2296 2297 // Pop the instantiation entry. 2298 delete ActiveMacros.back(); 2299 ActiveMacros.pop_back(); 2300 } 2301 2302 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef, 2303 bool NoDeadStrip) { 2304 MCSymbol *Sym; 2305 const MCExpr *Value; 2306 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym, 2307 Value)) 2308 return true; 2309 2310 if (!Sym) { 2311 // In the case where we parse an expression starting with a '.', we will 2312 // not generate an error, nor will we create a symbol. In this case we 2313 // should just return out. 2314 return false; 2315 } 2316 2317 // Do the assignment. 2318 Out.EmitAssignment(Sym, Value); 2319 if (NoDeadStrip) 2320 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip); 2321 2322 return false; 2323 } 2324 2325 /// parseIdentifier: 2326 /// ::= identifier 2327 /// ::= string 2328 bool AsmParser::parseIdentifier(StringRef &Res) { 2329 // The assembler has relaxed rules for accepting identifiers, in particular we 2330 // allow things like '.globl $foo' and '.def @feat.00', which would normally be 2331 // separate tokens. At this level, we have already lexed so we cannot (currently) 2332 // handle this as a context dependent token, instead we detect adjacent tokens 2333 // and return the combined identifier. 2334 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { 2335 SMLoc PrefixLoc = getLexer().getLoc(); 2336 2337 // Consume the prefix character, and check for a following identifier. 2338 Lex(); 2339 if (Lexer.isNot(AsmToken::Identifier)) 2340 return true; 2341 2342 // We have a '$' or '@' followed by an identifier, make sure they are adjacent. 2343 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer()) 2344 return true; 2345 2346 // Construct the joined identifier and consume the token. 2347 Res = 2348 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1); 2349 Lex(); 2350 return false; 2351 } 2352 2353 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) 2354 return true; 2355 2356 Res = getTok().getIdentifier(); 2357 2358 Lex(); // Consume the identifier token. 2359 2360 return false; 2361 } 2362 2363 /// parseDirectiveSet: 2364 /// ::= .equ identifier ',' expression 2365 /// ::= .equiv identifier ',' expression 2366 /// ::= .set identifier ',' expression 2367 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) { 2368 StringRef Name; 2369 2370 if (parseIdentifier(Name)) 2371 return TokError("expected identifier after '" + Twine(IDVal) + "'"); 2372 2373 if (getLexer().isNot(AsmToken::Comma)) 2374 return TokError("unexpected token in '" + Twine(IDVal) + "'"); 2375 Lex(); 2376 2377 return parseAssignment(Name, allow_redef, true); 2378 } 2379 2380 bool AsmParser::parseEscapedString(std::string &Data) { 2381 assert(getLexer().is(AsmToken::String) && "Unexpected current token!"); 2382 2383 Data = ""; 2384 StringRef Str = getTok().getStringContents(); 2385 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 2386 if (Str[i] != '\\') { 2387 Data += Str[i]; 2388 continue; 2389 } 2390 2391 // Recognize escaped characters. Note that this escape semantics currently 2392 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes. 2393 ++i; 2394 if (i == e) 2395 return TokError("unexpected backslash at end of string"); 2396 2397 // Recognize octal sequences. 2398 if ((unsigned)(Str[i] - '0') <= 7) { 2399 // Consume up to three octal characters. 2400 unsigned Value = Str[i] - '0'; 2401 2402 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2403 ++i; 2404 Value = Value * 8 + (Str[i] - '0'); 2405 2406 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) { 2407 ++i; 2408 Value = Value * 8 + (Str[i] - '0'); 2409 } 2410 } 2411 2412 if (Value > 255) 2413 return TokError("invalid octal escape sequence (out of range)"); 2414 2415 Data += (unsigned char)Value; 2416 continue; 2417 } 2418 2419 // Otherwise recognize individual escapes. 2420 switch (Str[i]) { 2421 default: 2422 // Just reject invalid escape sequences for now. 2423 return TokError("invalid escape sequence (unrecognized character)"); 2424 2425 case 'b': Data += '\b'; break; 2426 case 'f': Data += '\f'; break; 2427 case 'n': Data += '\n'; break; 2428 case 'r': Data += '\r'; break; 2429 case 't': Data += '\t'; break; 2430 case '"': Data += '"'; break; 2431 case '\\': Data += '\\'; break; 2432 } 2433 } 2434 2435 return false; 2436 } 2437 2438 /// parseDirectiveAscii: 2439 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] 2440 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { 2441 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2442 checkForValidSection(); 2443 2444 for (;;) { 2445 if (getLexer().isNot(AsmToken::String)) 2446 return TokError("expected string in '" + Twine(IDVal) + "' directive"); 2447 2448 std::string Data; 2449 if (parseEscapedString(Data)) 2450 return true; 2451 2452 getStreamer().EmitBytes(Data); 2453 if (ZeroTerminated) 2454 getStreamer().EmitBytes(StringRef("\0", 1)); 2455 2456 Lex(); 2457 2458 if (getLexer().is(AsmToken::EndOfStatement)) 2459 break; 2460 2461 if (getLexer().isNot(AsmToken::Comma)) 2462 return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); 2463 Lex(); 2464 } 2465 } 2466 2467 Lex(); 2468 return false; 2469 } 2470 2471 /// parseDirectiveReloc 2472 /// ::= .reloc expression , identifier [ , expression ] 2473 bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) { 2474 const MCExpr *Offset; 2475 const MCExpr *Expr = nullptr; 2476 2477 SMLoc OffsetLoc = Lexer.getTok().getLoc(); 2478 if (parseExpression(Offset)) 2479 return true; 2480 2481 // We can only deal with constant expressions at the moment. 2482 int64_t OffsetValue; 2483 if (!Offset->evaluateAsAbsolute(OffsetValue)) 2484 return Error(OffsetLoc, "expression is not a constant value"); 2485 2486 if (Lexer.isNot(AsmToken::Comma)) 2487 return TokError("expected comma"); 2488 Lexer.Lex(); 2489 2490 if (Lexer.isNot(AsmToken::Identifier)) 2491 return TokError("expected relocation name"); 2492 SMLoc NameLoc = Lexer.getTok().getLoc(); 2493 StringRef Name = Lexer.getTok().getIdentifier(); 2494 Lexer.Lex(); 2495 2496 if (Lexer.is(AsmToken::Comma)) { 2497 Lexer.Lex(); 2498 SMLoc ExprLoc = Lexer.getLoc(); 2499 if (parseExpression(Expr)) 2500 return true; 2501 2502 MCValue Value; 2503 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr)) 2504 return Error(ExprLoc, "expression must be relocatable"); 2505 } 2506 2507 if (Lexer.isNot(AsmToken::EndOfStatement)) 2508 return TokError("unexpected token in .reloc directive"); 2509 2510 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc)) 2511 return Error(NameLoc, "unknown relocation name"); 2512 2513 return false; 2514 } 2515 2516 /// parseDirectiveValue 2517 /// ::= (.byte | .short | ... ) [ expression (, expression)* ] 2518 bool AsmParser::parseDirectiveValue(unsigned Size) { 2519 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2520 checkForValidSection(); 2521 2522 for (;;) { 2523 const MCExpr *Value; 2524 SMLoc ExprLoc = getLexer().getLoc(); 2525 if (parseExpression(Value)) 2526 return true; 2527 2528 // Special case constant expressions to match code generator. 2529 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 2530 assert(Size <= 8 && "Invalid size"); 2531 uint64_t IntValue = MCE->getValue(); 2532 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 2533 return Error(ExprLoc, "literal value out of range for directive"); 2534 getStreamer().EmitIntValue(IntValue, Size); 2535 } else 2536 getStreamer().EmitValue(Value, Size, ExprLoc); 2537 2538 if (getLexer().is(AsmToken::EndOfStatement)) 2539 break; 2540 2541 // FIXME: Improve diagnostic. 2542 if (getLexer().isNot(AsmToken::Comma)) 2543 return TokError("unexpected token in directive"); 2544 Lex(); 2545 } 2546 } 2547 2548 Lex(); 2549 return false; 2550 } 2551 2552 /// ParseDirectiveOctaValue 2553 /// ::= .octa [ hexconstant (, hexconstant)* ] 2554 bool AsmParser::parseDirectiveOctaValue() { 2555 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2556 checkForValidSection(); 2557 2558 for (;;) { 2559 if (Lexer.getKind() == AsmToken::Error) 2560 return true; 2561 if (Lexer.getKind() != AsmToken::Integer && 2562 Lexer.getKind() != AsmToken::BigNum) 2563 return TokError("unknown token in expression"); 2564 2565 SMLoc ExprLoc = getLexer().getLoc(); 2566 APInt IntValue = getTok().getAPIntVal(); 2567 Lex(); 2568 2569 uint64_t hi, lo; 2570 if (IntValue.isIntN(64)) { 2571 hi = 0; 2572 lo = IntValue.getZExtValue(); 2573 } else if (IntValue.isIntN(128)) { 2574 // It might actually have more than 128 bits, but the top ones are zero. 2575 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); 2576 lo = IntValue.getLoBits(64).getZExtValue(); 2577 } else 2578 return Error(ExprLoc, "literal value out of range for directive"); 2579 2580 if (MAI.isLittleEndian()) { 2581 getStreamer().EmitIntValue(lo, 8); 2582 getStreamer().EmitIntValue(hi, 8); 2583 } else { 2584 getStreamer().EmitIntValue(hi, 8); 2585 getStreamer().EmitIntValue(lo, 8); 2586 } 2587 2588 if (getLexer().is(AsmToken::EndOfStatement)) 2589 break; 2590 2591 // FIXME: Improve diagnostic. 2592 if (getLexer().isNot(AsmToken::Comma)) 2593 return TokError("unexpected token in directive"); 2594 Lex(); 2595 } 2596 } 2597 2598 Lex(); 2599 return false; 2600 } 2601 2602 /// parseDirectiveRealValue 2603 /// ::= (.single | .double) [ expression (, expression)* ] 2604 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) { 2605 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2606 checkForValidSection(); 2607 2608 for (;;) { 2609 // We don't truly support arithmetic on floating point expressions, so we 2610 // have to manually parse unary prefixes. 2611 bool IsNeg = false; 2612 if (getLexer().is(AsmToken::Minus)) { 2613 Lex(); 2614 IsNeg = true; 2615 } else if (getLexer().is(AsmToken::Plus)) 2616 Lex(); 2617 2618 if (getLexer().isNot(AsmToken::Integer) && 2619 getLexer().isNot(AsmToken::Real) && 2620 getLexer().isNot(AsmToken::Identifier)) 2621 return TokError("unexpected token in directive"); 2622 2623 // Convert to an APFloat. 2624 APFloat Value(Semantics); 2625 StringRef IDVal = getTok().getString(); 2626 if (getLexer().is(AsmToken::Identifier)) { 2627 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf")) 2628 Value = APFloat::getInf(Semantics); 2629 else if (!IDVal.compare_lower("nan")) 2630 Value = APFloat::getNaN(Semantics, false, ~0); 2631 else 2632 return TokError("invalid floating point literal"); 2633 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) == 2634 APFloat::opInvalidOp) 2635 return TokError("invalid floating point literal"); 2636 if (IsNeg) 2637 Value.changeSign(); 2638 2639 // Consume the numeric token. 2640 Lex(); 2641 2642 // Emit the value as an integer. 2643 APInt AsInt = Value.bitcastToAPInt(); 2644 getStreamer().EmitIntValue(AsInt.getLimitedValue(), 2645 AsInt.getBitWidth() / 8); 2646 2647 if (getLexer().is(AsmToken::EndOfStatement)) 2648 break; 2649 2650 if (getLexer().isNot(AsmToken::Comma)) 2651 return TokError("unexpected token in directive"); 2652 Lex(); 2653 } 2654 } 2655 2656 Lex(); 2657 return false; 2658 } 2659 2660 /// parseDirectiveZero 2661 /// ::= .zero expression 2662 bool AsmParser::parseDirectiveZero() { 2663 checkForValidSection(); 2664 2665 int64_t NumBytes; 2666 if (parseAbsoluteExpression(NumBytes)) 2667 return true; 2668 2669 int64_t Val = 0; 2670 if (getLexer().is(AsmToken::Comma)) { 2671 Lex(); 2672 if (parseAbsoluteExpression(Val)) 2673 return true; 2674 } 2675 2676 if (getLexer().isNot(AsmToken::EndOfStatement)) 2677 return TokError("unexpected token in '.zero' directive"); 2678 2679 Lex(); 2680 2681 getStreamer().EmitFill(NumBytes, Val); 2682 2683 return false; 2684 } 2685 2686 /// parseDirectiveFill 2687 /// ::= .fill expression [ , expression [ , expression ] ] 2688 bool AsmParser::parseDirectiveFill() { 2689 checkForValidSection(); 2690 2691 SMLoc RepeatLoc = getLexer().getLoc(); 2692 int64_t NumValues; 2693 if (parseAbsoluteExpression(NumValues)) 2694 return true; 2695 2696 if (NumValues < 0) { 2697 Warning(RepeatLoc, 2698 "'.fill' directive with negative repeat count has no effect"); 2699 NumValues = 0; 2700 } 2701 2702 int64_t FillSize = 1; 2703 int64_t FillExpr = 0; 2704 2705 SMLoc SizeLoc, ExprLoc; 2706 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2707 if (getLexer().isNot(AsmToken::Comma)) 2708 return TokError("unexpected token in '.fill' directive"); 2709 Lex(); 2710 2711 SizeLoc = getLexer().getLoc(); 2712 if (parseAbsoluteExpression(FillSize)) 2713 return true; 2714 2715 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2716 if (getLexer().isNot(AsmToken::Comma)) 2717 return TokError("unexpected token in '.fill' directive"); 2718 Lex(); 2719 2720 ExprLoc = getLexer().getLoc(); 2721 if (parseAbsoluteExpression(FillExpr)) 2722 return true; 2723 2724 if (getLexer().isNot(AsmToken::EndOfStatement)) 2725 return TokError("unexpected token in '.fill' directive"); 2726 2727 Lex(); 2728 } 2729 } 2730 2731 if (FillSize < 0) { 2732 Warning(SizeLoc, "'.fill' directive with negative size has no effect"); 2733 NumValues = 0; 2734 } 2735 if (FillSize > 8) { 2736 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8"); 2737 FillSize = 8; 2738 } 2739 2740 if (!isUInt<32>(FillExpr) && FillSize > 4) 2741 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits"); 2742 2743 if (NumValues > 0) { 2744 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize; 2745 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8); 2746 for (uint64_t i = 0, e = NumValues; i != e; ++i) { 2747 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize); 2748 if (NonZeroFillSize < FillSize) 2749 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize); 2750 } 2751 } 2752 2753 return false; 2754 } 2755 2756 /// parseDirectiveOrg 2757 /// ::= .org expression [ , expression ] 2758 bool AsmParser::parseDirectiveOrg() { 2759 checkForValidSection(); 2760 2761 const MCExpr *Offset; 2762 if (parseExpression(Offset)) 2763 return true; 2764 2765 // Parse optional fill expression. 2766 int64_t FillExpr = 0; 2767 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2768 if (getLexer().isNot(AsmToken::Comma)) 2769 return TokError("unexpected token in '.org' directive"); 2770 Lex(); 2771 2772 if (parseAbsoluteExpression(FillExpr)) 2773 return true; 2774 2775 if (getLexer().isNot(AsmToken::EndOfStatement)) 2776 return TokError("unexpected token in '.org' directive"); 2777 } 2778 2779 Lex(); 2780 getStreamer().emitValueToOffset(Offset, FillExpr); 2781 return false; 2782 } 2783 2784 /// parseDirectiveAlign 2785 /// ::= {.align, ...} expression [ , expression [ , expression ]] 2786 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) { 2787 checkForValidSection(); 2788 2789 SMLoc AlignmentLoc = getLexer().getLoc(); 2790 int64_t Alignment; 2791 if (parseAbsoluteExpression(Alignment)) 2792 return true; 2793 2794 SMLoc MaxBytesLoc; 2795 bool HasFillExpr = false; 2796 int64_t FillExpr = 0; 2797 int64_t MaxBytesToFill = 0; 2798 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2799 if (getLexer().isNot(AsmToken::Comma)) 2800 return TokError("unexpected token in directive"); 2801 Lex(); 2802 2803 // The fill expression can be omitted while specifying a maximum number of 2804 // alignment bytes, e.g: 2805 // .align 3,,4 2806 if (getLexer().isNot(AsmToken::Comma)) { 2807 HasFillExpr = true; 2808 if (parseAbsoluteExpression(FillExpr)) 2809 return true; 2810 } 2811 2812 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2813 if (getLexer().isNot(AsmToken::Comma)) 2814 return TokError("unexpected token in directive"); 2815 Lex(); 2816 2817 MaxBytesLoc = getLexer().getLoc(); 2818 if (parseAbsoluteExpression(MaxBytesToFill)) 2819 return true; 2820 2821 if (getLexer().isNot(AsmToken::EndOfStatement)) 2822 return TokError("unexpected token in directive"); 2823 } 2824 } 2825 2826 Lex(); 2827 2828 if (!HasFillExpr) 2829 FillExpr = 0; 2830 2831 // Compute alignment in bytes. 2832 if (IsPow2) { 2833 // FIXME: Diagnose overflow. 2834 if (Alignment >= 32) { 2835 Error(AlignmentLoc, "invalid alignment value"); 2836 Alignment = 31; 2837 } 2838 2839 Alignment = 1ULL << Alignment; 2840 } else { 2841 // Reject alignments that aren't either a power of two or zero, 2842 // for gas compatibility. Alignment of zero is silently rounded 2843 // up to one. 2844 if (Alignment == 0) 2845 Alignment = 1; 2846 if (!isPowerOf2_64(Alignment)) 2847 Error(AlignmentLoc, "alignment must be a power of 2"); 2848 } 2849 2850 // Diagnose non-sensical max bytes to align. 2851 if (MaxBytesLoc.isValid()) { 2852 if (MaxBytesToFill < 1) { 2853 Error(MaxBytesLoc, "alignment directive can never be satisfied in this " 2854 "many bytes, ignoring maximum bytes expression"); 2855 MaxBytesToFill = 0; 2856 } 2857 2858 if (MaxBytesToFill >= Alignment) { 2859 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and " 2860 "has no effect"); 2861 MaxBytesToFill = 0; 2862 } 2863 } 2864 2865 // Check whether we should use optimal code alignment for this .align 2866 // directive. 2867 const MCSection *Section = getStreamer().getCurrentSection().first; 2868 assert(Section && "must have section to emit alignment"); 2869 bool UseCodeAlign = Section->UseCodeAlign(); 2870 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) && 2871 ValueSize == 1 && UseCodeAlign) { 2872 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill); 2873 } else { 2874 // FIXME: Target specific behavior about how the "extra" bytes are filled. 2875 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize, 2876 MaxBytesToFill); 2877 } 2878 2879 return false; 2880 } 2881 2882 /// parseDirectiveFile 2883 /// ::= .file [number] filename 2884 /// ::= .file number directory filename 2885 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) { 2886 // FIXME: I'm not sure what this is. 2887 int64_t FileNumber = -1; 2888 SMLoc FileNumberLoc = getLexer().getLoc(); 2889 if (getLexer().is(AsmToken::Integer)) { 2890 FileNumber = getTok().getIntVal(); 2891 Lex(); 2892 2893 if (FileNumber < 1) 2894 return TokError("file number less than one"); 2895 } 2896 2897 if (getLexer().isNot(AsmToken::String)) 2898 return TokError("unexpected token in '.file' directive"); 2899 2900 // Usually the directory and filename together, otherwise just the directory. 2901 // Allow the strings to have escaped octal character sequence. 2902 std::string Path = getTok().getString(); 2903 if (parseEscapedString(Path)) 2904 return true; 2905 Lex(); 2906 2907 StringRef Directory; 2908 StringRef Filename; 2909 std::string FilenameData; 2910 if (getLexer().is(AsmToken::String)) { 2911 if (FileNumber == -1) 2912 return TokError("explicit path specified, but no file number"); 2913 if (parseEscapedString(FilenameData)) 2914 return true; 2915 Filename = FilenameData; 2916 Directory = Path; 2917 Lex(); 2918 } else { 2919 Filename = Path; 2920 } 2921 2922 if (getLexer().isNot(AsmToken::EndOfStatement)) 2923 return TokError("unexpected token in '.file' directive"); 2924 2925 if (FileNumber == -1) 2926 getStreamer().EmitFileDirective(Filename); 2927 else { 2928 if (getContext().getGenDwarfForAssembly()) 2929 Error(DirectiveLoc, 2930 "input can't have .file dwarf directives when -g is " 2931 "used to generate dwarf debug info for assembly code"); 2932 2933 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) == 2934 0) 2935 Error(FileNumberLoc, "file number already allocated"); 2936 } 2937 2938 return false; 2939 } 2940 2941 /// parseDirectiveLine 2942 /// ::= .line [number] 2943 bool AsmParser::parseDirectiveLine() { 2944 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2945 if (getLexer().isNot(AsmToken::Integer)) 2946 return TokError("unexpected token in '.line' directive"); 2947 2948 int64_t LineNumber = getTok().getIntVal(); 2949 (void)LineNumber; 2950 Lex(); 2951 2952 // FIXME: Do something with the .line. 2953 } 2954 2955 if (getLexer().isNot(AsmToken::EndOfStatement)) 2956 return TokError("unexpected token in '.line' directive"); 2957 2958 return false; 2959 } 2960 2961 /// parseDirectiveLoc 2962 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] 2963 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] 2964 /// The first number is a file number, must have been previously assigned with 2965 /// a .file directive, the second number is the line number and optionally the 2966 /// third number is a column position (zero if not specified). The remaining 2967 /// optional items are .loc sub-directives. 2968 bool AsmParser::parseDirectiveLoc() { 2969 if (getLexer().isNot(AsmToken::Integer)) 2970 return TokError("unexpected token in '.loc' directive"); 2971 int64_t FileNumber = getTok().getIntVal(); 2972 if (FileNumber < 1) 2973 return TokError("file number less than one in '.loc' directive"); 2974 if (!getContext().isValidDwarfFileNumber(FileNumber)) 2975 return TokError("unassigned file number in '.loc' directive"); 2976 Lex(); 2977 2978 int64_t LineNumber = 0; 2979 if (getLexer().is(AsmToken::Integer)) { 2980 LineNumber = getTok().getIntVal(); 2981 if (LineNumber < 0) 2982 return TokError("line number less than zero in '.loc' directive"); 2983 Lex(); 2984 } 2985 2986 int64_t ColumnPos = 0; 2987 if (getLexer().is(AsmToken::Integer)) { 2988 ColumnPos = getTok().getIntVal(); 2989 if (ColumnPos < 0) 2990 return TokError("column position less than zero in '.loc' directive"); 2991 Lex(); 2992 } 2993 2994 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0; 2995 unsigned Isa = 0; 2996 int64_t Discriminator = 0; 2997 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2998 for (;;) { 2999 if (getLexer().is(AsmToken::EndOfStatement)) 3000 break; 3001 3002 StringRef Name; 3003 SMLoc Loc = getTok().getLoc(); 3004 if (parseIdentifier(Name)) 3005 return TokError("unexpected token in '.loc' directive"); 3006 3007 if (Name == "basic_block") 3008 Flags |= DWARF2_FLAG_BASIC_BLOCK; 3009 else if (Name == "prologue_end") 3010 Flags |= DWARF2_FLAG_PROLOGUE_END; 3011 else if (Name == "epilogue_begin") 3012 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; 3013 else if (Name == "is_stmt") { 3014 Loc = getTok().getLoc(); 3015 const MCExpr *Value; 3016 if (parseExpression(Value)) 3017 return true; 3018 // The expression must be the constant 0 or 1. 3019 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3020 int Value = MCE->getValue(); 3021 if (Value == 0) 3022 Flags &= ~DWARF2_FLAG_IS_STMT; 3023 else if (Value == 1) 3024 Flags |= DWARF2_FLAG_IS_STMT; 3025 else 3026 return Error(Loc, "is_stmt value not 0 or 1"); 3027 } else { 3028 return Error(Loc, "is_stmt value not the constant value of 0 or 1"); 3029 } 3030 } else if (Name == "isa") { 3031 Loc = getTok().getLoc(); 3032 const MCExpr *Value; 3033 if (parseExpression(Value)) 3034 return true; 3035 // The expression must be a constant greater or equal to 0. 3036 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3037 int Value = MCE->getValue(); 3038 if (Value < 0) 3039 return Error(Loc, "isa number less than zero"); 3040 Isa = Value; 3041 } else { 3042 return Error(Loc, "isa number not a constant value"); 3043 } 3044 } else if (Name == "discriminator") { 3045 if (parseAbsoluteExpression(Discriminator)) 3046 return true; 3047 } else { 3048 return Error(Loc, "unknown sub-directive in '.loc' directive"); 3049 } 3050 3051 if (getLexer().is(AsmToken::EndOfStatement)) 3052 break; 3053 } 3054 } 3055 3056 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, 3057 Isa, Discriminator, StringRef()); 3058 3059 return false; 3060 } 3061 3062 /// parseDirectiveStabs 3063 /// ::= .stabs string, number, number, number 3064 bool AsmParser::parseDirectiveStabs() { 3065 return TokError("unsupported directive '.stabs'"); 3066 } 3067 3068 /// parseDirectiveCFISections 3069 /// ::= .cfi_sections section [, section] 3070 bool AsmParser::parseDirectiveCFISections() { 3071 StringRef Name; 3072 bool EH = false; 3073 bool Debug = false; 3074 3075 if (parseIdentifier(Name)) 3076 return TokError("Expected an identifier"); 3077 3078 if (Name == ".eh_frame") 3079 EH = true; 3080 else if (Name == ".debug_frame") 3081 Debug = true; 3082 3083 if (getLexer().is(AsmToken::Comma)) { 3084 Lex(); 3085 3086 if (parseIdentifier(Name)) 3087 return TokError("Expected an identifier"); 3088 3089 if (Name == ".eh_frame") 3090 EH = true; 3091 else if (Name == ".debug_frame") 3092 Debug = true; 3093 } 3094 3095 getStreamer().EmitCFISections(EH, Debug); 3096 return false; 3097 } 3098 3099 /// parseDirectiveCFIStartProc 3100 /// ::= .cfi_startproc [simple] 3101 bool AsmParser::parseDirectiveCFIStartProc() { 3102 StringRef Simple; 3103 if (getLexer().isNot(AsmToken::EndOfStatement)) 3104 if (parseIdentifier(Simple) || Simple != "simple") 3105 return TokError("unexpected token in .cfi_startproc directive"); 3106 3107 getStreamer().EmitCFIStartProc(!Simple.empty()); 3108 return false; 3109 } 3110 3111 /// parseDirectiveCFIEndProc 3112 /// ::= .cfi_endproc 3113 bool AsmParser::parseDirectiveCFIEndProc() { 3114 getStreamer().EmitCFIEndProc(); 3115 return false; 3116 } 3117 3118 /// \brief parse register name or number. 3119 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register, 3120 SMLoc DirectiveLoc) { 3121 unsigned RegNo; 3122 3123 if (getLexer().isNot(AsmToken::Integer)) { 3124 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) 3125 return true; 3126 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); 3127 } else 3128 return parseAbsoluteExpression(Register); 3129 3130 return false; 3131 } 3132 3133 /// parseDirectiveCFIDefCfa 3134 /// ::= .cfi_def_cfa register, offset 3135 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { 3136 int64_t Register = 0; 3137 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3138 return true; 3139 3140 if (getLexer().isNot(AsmToken::Comma)) 3141 return TokError("unexpected token in directive"); 3142 Lex(); 3143 3144 int64_t Offset = 0; 3145 if (parseAbsoluteExpression(Offset)) 3146 return true; 3147 3148 getStreamer().EmitCFIDefCfa(Register, Offset); 3149 return false; 3150 } 3151 3152 /// parseDirectiveCFIDefCfaOffset 3153 /// ::= .cfi_def_cfa_offset offset 3154 bool AsmParser::parseDirectiveCFIDefCfaOffset() { 3155 int64_t Offset = 0; 3156 if (parseAbsoluteExpression(Offset)) 3157 return true; 3158 3159 getStreamer().EmitCFIDefCfaOffset(Offset); 3160 return false; 3161 } 3162 3163 /// parseDirectiveCFIRegister 3164 /// ::= .cfi_register register, register 3165 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { 3166 int64_t Register1 = 0; 3167 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc)) 3168 return true; 3169 3170 if (getLexer().isNot(AsmToken::Comma)) 3171 return TokError("unexpected token in directive"); 3172 Lex(); 3173 3174 int64_t Register2 = 0; 3175 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) 3176 return true; 3177 3178 getStreamer().EmitCFIRegister(Register1, Register2); 3179 return false; 3180 } 3181 3182 /// parseDirectiveCFIWindowSave 3183 /// ::= .cfi_window_save 3184 bool AsmParser::parseDirectiveCFIWindowSave() { 3185 getStreamer().EmitCFIWindowSave(); 3186 return false; 3187 } 3188 3189 /// parseDirectiveCFIAdjustCfaOffset 3190 /// ::= .cfi_adjust_cfa_offset adjustment 3191 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() { 3192 int64_t Adjustment = 0; 3193 if (parseAbsoluteExpression(Adjustment)) 3194 return true; 3195 3196 getStreamer().EmitCFIAdjustCfaOffset(Adjustment); 3197 return false; 3198 } 3199 3200 /// parseDirectiveCFIDefCfaRegister 3201 /// ::= .cfi_def_cfa_register register 3202 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { 3203 int64_t Register = 0; 3204 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3205 return true; 3206 3207 getStreamer().EmitCFIDefCfaRegister(Register); 3208 return false; 3209 } 3210 3211 /// parseDirectiveCFIOffset 3212 /// ::= .cfi_offset register, offset 3213 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { 3214 int64_t Register = 0; 3215 int64_t Offset = 0; 3216 3217 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3218 return true; 3219 3220 if (getLexer().isNot(AsmToken::Comma)) 3221 return TokError("unexpected token in directive"); 3222 Lex(); 3223 3224 if (parseAbsoluteExpression(Offset)) 3225 return true; 3226 3227 getStreamer().EmitCFIOffset(Register, Offset); 3228 return false; 3229 } 3230 3231 /// parseDirectiveCFIRelOffset 3232 /// ::= .cfi_rel_offset register, offset 3233 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { 3234 int64_t Register = 0; 3235 3236 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3237 return true; 3238 3239 if (getLexer().isNot(AsmToken::Comma)) 3240 return TokError("unexpected token in directive"); 3241 Lex(); 3242 3243 int64_t Offset = 0; 3244 if (parseAbsoluteExpression(Offset)) 3245 return true; 3246 3247 getStreamer().EmitCFIRelOffset(Register, Offset); 3248 return false; 3249 } 3250 3251 static bool isValidEncoding(int64_t Encoding) { 3252 if (Encoding & ~0xff) 3253 return false; 3254 3255 if (Encoding == dwarf::DW_EH_PE_omit) 3256 return true; 3257 3258 const unsigned Format = Encoding & 0xf; 3259 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && 3260 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && 3261 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && 3262 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) 3263 return false; 3264 3265 const unsigned Application = Encoding & 0x70; 3266 if (Application != dwarf::DW_EH_PE_absptr && 3267 Application != dwarf::DW_EH_PE_pcrel) 3268 return false; 3269 3270 return true; 3271 } 3272 3273 /// parseDirectiveCFIPersonalityOrLsda 3274 /// IsPersonality true for cfi_personality, false for cfi_lsda 3275 /// ::= .cfi_personality encoding, [symbol_name] 3276 /// ::= .cfi_lsda encoding, [symbol_name] 3277 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { 3278 int64_t Encoding = 0; 3279 if (parseAbsoluteExpression(Encoding)) 3280 return true; 3281 if (Encoding == dwarf::DW_EH_PE_omit) 3282 return false; 3283 3284 if (!isValidEncoding(Encoding)) 3285 return TokError("unsupported encoding."); 3286 3287 if (getLexer().isNot(AsmToken::Comma)) 3288 return TokError("unexpected token in directive"); 3289 Lex(); 3290 3291 StringRef Name; 3292 if (parseIdentifier(Name)) 3293 return TokError("expected identifier in directive"); 3294 3295 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3296 3297 if (IsPersonality) 3298 getStreamer().EmitCFIPersonality(Sym, Encoding); 3299 else 3300 getStreamer().EmitCFILsda(Sym, Encoding); 3301 return false; 3302 } 3303 3304 /// parseDirectiveCFIRememberState 3305 /// ::= .cfi_remember_state 3306 bool AsmParser::parseDirectiveCFIRememberState() { 3307 getStreamer().EmitCFIRememberState(); 3308 return false; 3309 } 3310 3311 /// parseDirectiveCFIRestoreState 3312 /// ::= .cfi_remember_state 3313 bool AsmParser::parseDirectiveCFIRestoreState() { 3314 getStreamer().EmitCFIRestoreState(); 3315 return false; 3316 } 3317 3318 /// parseDirectiveCFISameValue 3319 /// ::= .cfi_same_value register 3320 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { 3321 int64_t Register = 0; 3322 3323 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3324 return true; 3325 3326 getStreamer().EmitCFISameValue(Register); 3327 return false; 3328 } 3329 3330 /// parseDirectiveCFIRestore 3331 /// ::= .cfi_restore register 3332 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { 3333 int64_t Register = 0; 3334 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3335 return true; 3336 3337 getStreamer().EmitCFIRestore(Register); 3338 return false; 3339 } 3340 3341 /// parseDirectiveCFIEscape 3342 /// ::= .cfi_escape expression[,...] 3343 bool AsmParser::parseDirectiveCFIEscape() { 3344 std::string Values; 3345 int64_t CurrValue; 3346 if (parseAbsoluteExpression(CurrValue)) 3347 return true; 3348 3349 Values.push_back((uint8_t)CurrValue); 3350 3351 while (getLexer().is(AsmToken::Comma)) { 3352 Lex(); 3353 3354 if (parseAbsoluteExpression(CurrValue)) 3355 return true; 3356 3357 Values.push_back((uint8_t)CurrValue); 3358 } 3359 3360 getStreamer().EmitCFIEscape(Values); 3361 return false; 3362 } 3363 3364 /// parseDirectiveCFISignalFrame 3365 /// ::= .cfi_signal_frame 3366 bool AsmParser::parseDirectiveCFISignalFrame() { 3367 if (getLexer().isNot(AsmToken::EndOfStatement)) 3368 return Error(getLexer().getLoc(), 3369 "unexpected token in '.cfi_signal_frame'"); 3370 3371 getStreamer().EmitCFISignalFrame(); 3372 return false; 3373 } 3374 3375 /// parseDirectiveCFIUndefined 3376 /// ::= .cfi_undefined register 3377 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { 3378 int64_t Register = 0; 3379 3380 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 3381 return true; 3382 3383 getStreamer().EmitCFIUndefined(Register); 3384 return false; 3385 } 3386 3387 /// parseDirectiveMacrosOnOff 3388 /// ::= .macros_on 3389 /// ::= .macros_off 3390 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) { 3391 if (getLexer().isNot(AsmToken::EndOfStatement)) 3392 return Error(getLexer().getLoc(), 3393 "unexpected token in '" + Directive + "' directive"); 3394 3395 setMacrosEnabled(Directive == ".macros_on"); 3396 return false; 3397 } 3398 3399 /// parseDirectiveMacro 3400 /// ::= .macro name[,] [parameters] 3401 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) { 3402 StringRef Name; 3403 if (parseIdentifier(Name)) 3404 return TokError("expected identifier in '.macro' directive"); 3405 3406 if (getLexer().is(AsmToken::Comma)) 3407 Lex(); 3408 3409 MCAsmMacroParameters Parameters; 3410 while (getLexer().isNot(AsmToken::EndOfStatement)) { 3411 3412 if (!Parameters.empty() && Parameters.back().Vararg) 3413 return Error(Lexer.getLoc(), 3414 "Vararg parameter '" + Parameters.back().Name + 3415 "' should be last one in the list of parameters."); 3416 3417 MCAsmMacroParameter Parameter; 3418 if (parseIdentifier(Parameter.Name)) 3419 return TokError("expected identifier in '.macro' directive"); 3420 3421 if (Lexer.is(AsmToken::Colon)) { 3422 Lex(); // consume ':' 3423 3424 SMLoc QualLoc; 3425 StringRef Qualifier; 3426 3427 QualLoc = Lexer.getLoc(); 3428 if (parseIdentifier(Qualifier)) 3429 return Error(QualLoc, "missing parameter qualifier for " 3430 "'" + Parameter.Name + "' in macro '" + Name + "'"); 3431 3432 if (Qualifier == "req") 3433 Parameter.Required = true; 3434 else if (Qualifier == "vararg") 3435 Parameter.Vararg = true; 3436 else 3437 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier " 3438 "for '" + Parameter.Name + "' in macro '" + Name + "'"); 3439 } 3440 3441 if (getLexer().is(AsmToken::Equal)) { 3442 Lex(); 3443 3444 SMLoc ParamLoc; 3445 3446 ParamLoc = Lexer.getLoc(); 3447 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) 3448 return true; 3449 3450 if (Parameter.Required) 3451 Warning(ParamLoc, "pointless default value for required parameter " 3452 "'" + Parameter.Name + "' in macro '" + Name + "'"); 3453 } 3454 3455 Parameters.push_back(std::move(Parameter)); 3456 3457 if (getLexer().is(AsmToken::Comma)) 3458 Lex(); 3459 } 3460 3461 // Eat the end of statement. 3462 Lex(); 3463 3464 AsmToken EndToken, StartToken = getTok(); 3465 unsigned MacroDepth = 0; 3466 3467 // Lex the macro definition. 3468 for (;;) { 3469 // Check whether we have reached the end of the file. 3470 if (getLexer().is(AsmToken::Eof)) 3471 return Error(DirectiveLoc, "no matching '.endmacro' in definition"); 3472 3473 // Otherwise, check whether we have reach the .endmacro. 3474 if (getLexer().is(AsmToken::Identifier)) { 3475 if (getTok().getIdentifier() == ".endm" || 3476 getTok().getIdentifier() == ".endmacro") { 3477 if (MacroDepth == 0) { // Outermost macro. 3478 EndToken = getTok(); 3479 Lex(); 3480 if (getLexer().isNot(AsmToken::EndOfStatement)) 3481 return TokError("unexpected token in '" + EndToken.getIdentifier() + 3482 "' directive"); 3483 break; 3484 } else { 3485 // Otherwise we just found the end of an inner macro. 3486 --MacroDepth; 3487 } 3488 } else if (getTok().getIdentifier() == ".macro") { 3489 // We allow nested macros. Those aren't instantiated until the outermost 3490 // macro is expanded so just ignore them for now. 3491 ++MacroDepth; 3492 } 3493 } 3494 3495 // Otherwise, scan til the end of the statement. 3496 eatToEndOfStatement(); 3497 } 3498 3499 if (lookupMacro(Name)) { 3500 return Error(DirectiveLoc, "macro '" + Name + "' is already defined"); 3501 } 3502 3503 const char *BodyStart = StartToken.getLoc().getPointer(); 3504 const char *BodyEnd = EndToken.getLoc().getPointer(); 3505 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 3506 checkForBadMacro(DirectiveLoc, Name, Body, Parameters); 3507 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters))); 3508 return false; 3509 } 3510 3511 /// checkForBadMacro 3512 /// 3513 /// With the support added for named parameters there may be code out there that 3514 /// is transitioning from positional parameters. In versions of gas that did 3515 /// not support named parameters they would be ignored on the macro definition. 3516 /// But to support both styles of parameters this is not possible so if a macro 3517 /// definition has named parameters but does not use them and has what appears 3518 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a 3519 /// warning that the positional parameter found in body which have no effect. 3520 /// Hoping the developer will either remove the named parameters from the macro 3521 /// definition so the positional parameters get used if that was what was 3522 /// intended or change the macro to use the named parameters. It is possible 3523 /// this warning will trigger when the none of the named parameters are used 3524 /// and the strings like $1 are infact to simply to be passed trough unchanged. 3525 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, 3526 StringRef Body, 3527 ArrayRef<MCAsmMacroParameter> Parameters) { 3528 // If this macro is not defined with named parameters the warning we are 3529 // checking for here doesn't apply. 3530 unsigned NParameters = Parameters.size(); 3531 if (NParameters == 0) 3532 return; 3533 3534 bool NamedParametersFound = false; 3535 bool PositionalParametersFound = false; 3536 3537 // Look at the body of the macro for use of both the named parameters and what 3538 // are likely to be positional parameters. This is what expandMacro() is 3539 // doing when it finds the parameters in the body. 3540 while (!Body.empty()) { 3541 // Scan for the next possible parameter. 3542 std::size_t End = Body.size(), Pos = 0; 3543 for (; Pos != End; ++Pos) { 3544 // Check for a substitution or escape. 3545 // This macro is defined with parameters, look for \foo, \bar, etc. 3546 if (Body[Pos] == '\\' && Pos + 1 != End) 3547 break; 3548 3549 // This macro should have parameters, but look for $0, $1, ..., $n too. 3550 if (Body[Pos] != '$' || Pos + 1 == End) 3551 continue; 3552 char Next = Body[Pos + 1]; 3553 if (Next == '$' || Next == 'n' || 3554 isdigit(static_cast<unsigned char>(Next))) 3555 break; 3556 } 3557 3558 // Check if we reached the end. 3559 if (Pos == End) 3560 break; 3561 3562 if (Body[Pos] == '$') { 3563 switch (Body[Pos + 1]) { 3564 // $$ => $ 3565 case '$': 3566 break; 3567 3568 // $n => number of arguments 3569 case 'n': 3570 PositionalParametersFound = true; 3571 break; 3572 3573 // $[0-9] => argument 3574 default: { 3575 PositionalParametersFound = true; 3576 break; 3577 } 3578 } 3579 Pos += 2; 3580 } else { 3581 unsigned I = Pos + 1; 3582 while (isIdentifierChar(Body[I]) && I + 1 != End) 3583 ++I; 3584 3585 const char *Begin = Body.data() + Pos + 1; 3586 StringRef Argument(Begin, I - (Pos + 1)); 3587 unsigned Index = 0; 3588 for (; Index < NParameters; ++Index) 3589 if (Parameters[Index].Name == Argument) 3590 break; 3591 3592 if (Index == NParameters) { 3593 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 3594 Pos += 3; 3595 else { 3596 Pos = I; 3597 } 3598 } else { 3599 NamedParametersFound = true; 3600 Pos += 1 + Argument.size(); 3601 } 3602 } 3603 // Update the scan point. 3604 Body = Body.substr(Pos); 3605 } 3606 3607 if (!NamedParametersFound && PositionalParametersFound) 3608 Warning(DirectiveLoc, "macro defined with named parameters which are not " 3609 "used in macro body, possible positional parameter " 3610 "found in body which will have no effect"); 3611 } 3612 3613 /// parseDirectiveExitMacro 3614 /// ::= .exitm 3615 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) { 3616 if (getLexer().isNot(AsmToken::EndOfStatement)) 3617 return TokError("unexpected token in '" + Directive + "' directive"); 3618 3619 if (!isInsideMacroInstantiation()) 3620 return TokError("unexpected '" + Directive + "' in file, " 3621 "no current macro definition"); 3622 3623 // Exit all conditionals that are active in the current macro. 3624 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { 3625 TheCondState = TheCondStack.back(); 3626 TheCondStack.pop_back(); 3627 } 3628 3629 handleMacroExit(); 3630 return false; 3631 } 3632 3633 /// parseDirectiveEndMacro 3634 /// ::= .endm 3635 /// ::= .endmacro 3636 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) { 3637 if (getLexer().isNot(AsmToken::EndOfStatement)) 3638 return TokError("unexpected token in '" + Directive + "' directive"); 3639 3640 // If we are inside a macro instantiation, terminate the current 3641 // instantiation. 3642 if (isInsideMacroInstantiation()) { 3643 handleMacroExit(); 3644 return false; 3645 } 3646 3647 // Otherwise, this .endmacro is a stray entry in the file; well formed 3648 // .endmacro directives are handled during the macro definition parsing. 3649 return TokError("unexpected '" + Directive + "' in file, " 3650 "no current macro definition"); 3651 } 3652 3653 /// parseDirectivePurgeMacro 3654 /// ::= .purgem 3655 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { 3656 StringRef Name; 3657 if (parseIdentifier(Name)) 3658 return TokError("expected identifier in '.purgem' directive"); 3659 3660 if (getLexer().isNot(AsmToken::EndOfStatement)) 3661 return TokError("unexpected token in '.purgem' directive"); 3662 3663 if (!lookupMacro(Name)) 3664 return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); 3665 3666 undefineMacro(Name); 3667 return false; 3668 } 3669 3670 /// parseDirectiveBundleAlignMode 3671 /// ::= {.bundle_align_mode} expression 3672 bool AsmParser::parseDirectiveBundleAlignMode() { 3673 checkForValidSection(); 3674 3675 // Expect a single argument: an expression that evaluates to a constant 3676 // in the inclusive range 0-30. 3677 SMLoc ExprLoc = getLexer().getLoc(); 3678 int64_t AlignSizePow2; 3679 if (parseAbsoluteExpression(AlignSizePow2)) 3680 return true; 3681 else if (getLexer().isNot(AsmToken::EndOfStatement)) 3682 return TokError("unexpected token after expression in" 3683 " '.bundle_align_mode' directive"); 3684 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30) 3685 return Error(ExprLoc, 3686 "invalid bundle alignment size (expected between 0 and 30)"); 3687 3688 Lex(); 3689 3690 // Because of AlignSizePow2's verified range we can safely truncate it to 3691 // unsigned. 3692 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2)); 3693 return false; 3694 } 3695 3696 /// parseDirectiveBundleLock 3697 /// ::= {.bundle_lock} [align_to_end] 3698 bool AsmParser::parseDirectiveBundleLock() { 3699 checkForValidSection(); 3700 bool AlignToEnd = false; 3701 3702 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3703 StringRef Option; 3704 SMLoc Loc = getTok().getLoc(); 3705 const char *kInvalidOptionError = 3706 "invalid option for '.bundle_lock' directive"; 3707 3708 if (parseIdentifier(Option)) 3709 return Error(Loc, kInvalidOptionError); 3710 3711 if (Option != "align_to_end") 3712 return Error(Loc, kInvalidOptionError); 3713 else if (getLexer().isNot(AsmToken::EndOfStatement)) 3714 return Error(Loc, 3715 "unexpected token after '.bundle_lock' directive option"); 3716 AlignToEnd = true; 3717 } 3718 3719 Lex(); 3720 3721 getStreamer().EmitBundleLock(AlignToEnd); 3722 return false; 3723 } 3724 3725 /// parseDirectiveBundleLock 3726 /// ::= {.bundle_lock} 3727 bool AsmParser::parseDirectiveBundleUnlock() { 3728 checkForValidSection(); 3729 3730 if (getLexer().isNot(AsmToken::EndOfStatement)) 3731 return TokError("unexpected token in '.bundle_unlock' directive"); 3732 Lex(); 3733 3734 getStreamer().EmitBundleUnlock(); 3735 return false; 3736 } 3737 3738 /// parseDirectiveSpace 3739 /// ::= (.skip | .space) expression [ , expression ] 3740 bool AsmParser::parseDirectiveSpace(StringRef IDVal) { 3741 checkForValidSection(); 3742 3743 int64_t NumBytes; 3744 if (parseAbsoluteExpression(NumBytes)) 3745 return true; 3746 3747 int64_t FillExpr = 0; 3748 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3749 if (getLexer().isNot(AsmToken::Comma)) 3750 return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); 3751 Lex(); 3752 3753 if (parseAbsoluteExpression(FillExpr)) 3754 return true; 3755 3756 if (getLexer().isNot(AsmToken::EndOfStatement)) 3757 return TokError("unexpected token in '" + Twine(IDVal) + "' directive"); 3758 } 3759 3760 Lex(); 3761 3762 if (NumBytes <= 0) 3763 return TokError("invalid number of bytes in '" + Twine(IDVal) + 3764 "' directive"); 3765 3766 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0. 3767 getStreamer().EmitFill(NumBytes, FillExpr); 3768 3769 return false; 3770 } 3771 3772 /// parseDirectiveLEB128 3773 /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ] 3774 bool AsmParser::parseDirectiveLEB128(bool Signed) { 3775 checkForValidSection(); 3776 const MCExpr *Value; 3777 3778 for (;;) { 3779 if (parseExpression(Value)) 3780 return true; 3781 3782 if (Signed) 3783 getStreamer().EmitSLEB128Value(Value); 3784 else 3785 getStreamer().EmitULEB128Value(Value); 3786 3787 if (getLexer().is(AsmToken::EndOfStatement)) 3788 break; 3789 3790 if (getLexer().isNot(AsmToken::Comma)) 3791 return TokError("unexpected token in directive"); 3792 Lex(); 3793 } 3794 3795 return false; 3796 } 3797 3798 /// parseDirectiveSymbolAttribute 3799 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] 3800 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { 3801 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3802 for (;;) { 3803 StringRef Name; 3804 SMLoc Loc = getTok().getLoc(); 3805 3806 if (parseIdentifier(Name)) 3807 return Error(Loc, "expected identifier in directive"); 3808 3809 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3810 3811 // Assembler local symbols don't make any sense here. Complain loudly. 3812 if (Sym->isTemporary()) 3813 return Error(Loc, "non-local symbol required in directive"); 3814 3815 if (!getStreamer().EmitSymbolAttribute(Sym, Attr)) 3816 return Error(Loc, "unable to emit symbol attribute"); 3817 3818 if (getLexer().is(AsmToken::EndOfStatement)) 3819 break; 3820 3821 if (getLexer().isNot(AsmToken::Comma)) 3822 return TokError("unexpected token in directive"); 3823 Lex(); 3824 } 3825 } 3826 3827 Lex(); 3828 return false; 3829 } 3830 3831 /// parseDirectiveComm 3832 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] 3833 bool AsmParser::parseDirectiveComm(bool IsLocal) { 3834 checkForValidSection(); 3835 3836 SMLoc IDLoc = getLexer().getLoc(); 3837 StringRef Name; 3838 if (parseIdentifier(Name)) 3839 return TokError("expected identifier in directive"); 3840 3841 // Handle the identifier as the key symbol. 3842 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3843 3844 if (getLexer().isNot(AsmToken::Comma)) 3845 return TokError("unexpected token in directive"); 3846 Lex(); 3847 3848 int64_t Size; 3849 SMLoc SizeLoc = getLexer().getLoc(); 3850 if (parseAbsoluteExpression(Size)) 3851 return true; 3852 3853 int64_t Pow2Alignment = 0; 3854 SMLoc Pow2AlignmentLoc; 3855 if (getLexer().is(AsmToken::Comma)) { 3856 Lex(); 3857 Pow2AlignmentLoc = getLexer().getLoc(); 3858 if (parseAbsoluteExpression(Pow2Alignment)) 3859 return true; 3860 3861 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); 3862 if (IsLocal && LCOMM == LCOMM::NoAlignment) 3863 return Error(Pow2AlignmentLoc, "alignment not supported on this target"); 3864 3865 // If this target takes alignments in bytes (not log) validate and convert. 3866 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || 3867 (IsLocal && LCOMM == LCOMM::ByteAlignment)) { 3868 if (!isPowerOf2_64(Pow2Alignment)) 3869 return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); 3870 Pow2Alignment = Log2_64(Pow2Alignment); 3871 } 3872 } 3873 3874 if (getLexer().isNot(AsmToken::EndOfStatement)) 3875 return TokError("unexpected token in '.comm' or '.lcomm' directive"); 3876 3877 Lex(); 3878 3879 // NOTE: a size of zero for a .comm should create a undefined symbol 3880 // but a size of .lcomm creates a bss symbol of size zero. 3881 if (Size < 0) 3882 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " 3883 "be less than zero"); 3884 3885 // NOTE: The alignment in the directive is a power of 2 value, the assembler 3886 // may internally end up wanting an alignment in bytes. 3887 // FIXME: Diagnose overflow. 3888 if (Pow2Alignment < 0) 3889 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " 3890 "alignment, can't be less than zero"); 3891 3892 if (!Sym->isUndefined()) 3893 return Error(IDLoc, "invalid symbol redefinition"); 3894 3895 // Create the Symbol as a common or local common with Size and Pow2Alignment 3896 if (IsLocal) { 3897 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); 3898 return false; 3899 } 3900 3901 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment); 3902 return false; 3903 } 3904 3905 /// parseDirectiveAbort 3906 /// ::= .abort [... message ...] 3907 bool AsmParser::parseDirectiveAbort() { 3908 // FIXME: Use loc from directive. 3909 SMLoc Loc = getLexer().getLoc(); 3910 3911 StringRef Str = parseStringToEndOfStatement(); 3912 if (getLexer().isNot(AsmToken::EndOfStatement)) 3913 return TokError("unexpected token in '.abort' directive"); 3914 3915 Lex(); 3916 3917 if (Str.empty()) 3918 Error(Loc, ".abort detected. Assembly stopping."); 3919 else 3920 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping."); 3921 // FIXME: Actually abort assembly here. 3922 3923 return false; 3924 } 3925 3926 /// parseDirectiveInclude 3927 /// ::= .include "filename" 3928 bool AsmParser::parseDirectiveInclude() { 3929 if (getLexer().isNot(AsmToken::String)) 3930 return TokError("expected string in '.include' directive"); 3931 3932 // Allow the strings to have escaped octal character sequence. 3933 std::string Filename; 3934 if (parseEscapedString(Filename)) 3935 return true; 3936 SMLoc IncludeLoc = getLexer().getLoc(); 3937 Lex(); 3938 3939 if (getLexer().isNot(AsmToken::EndOfStatement)) 3940 return TokError("unexpected token in '.include' directive"); 3941 3942 // Attempt to switch the lexer to the included file before consuming the end 3943 // of statement to avoid losing it when we switch. 3944 if (enterIncludeFile(Filename)) { 3945 Error(IncludeLoc, "Could not find include file '" + Filename + "'"); 3946 return true; 3947 } 3948 3949 return false; 3950 } 3951 3952 /// parseDirectiveIncbin 3953 /// ::= .incbin "filename" 3954 bool AsmParser::parseDirectiveIncbin() { 3955 if (getLexer().isNot(AsmToken::String)) 3956 return TokError("expected string in '.incbin' directive"); 3957 3958 // Allow the strings to have escaped octal character sequence. 3959 std::string Filename; 3960 if (parseEscapedString(Filename)) 3961 return true; 3962 SMLoc IncbinLoc = getLexer().getLoc(); 3963 Lex(); 3964 3965 if (getLexer().isNot(AsmToken::EndOfStatement)) 3966 return TokError("unexpected token in '.incbin' directive"); 3967 3968 // Attempt to process the included file. 3969 if (processIncbinFile(Filename)) { 3970 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'"); 3971 return true; 3972 } 3973 3974 return false; 3975 } 3976 3977 /// parseDirectiveIf 3978 /// ::= .if{,eq,ge,gt,le,lt,ne} expression 3979 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { 3980 TheCondStack.push_back(TheCondState); 3981 TheCondState.TheCond = AsmCond::IfCond; 3982 if (TheCondState.Ignore) { 3983 eatToEndOfStatement(); 3984 } else { 3985 int64_t ExprValue; 3986 if (parseAbsoluteExpression(ExprValue)) 3987 return true; 3988 3989 if (getLexer().isNot(AsmToken::EndOfStatement)) 3990 return TokError("unexpected token in '.if' directive"); 3991 3992 Lex(); 3993 3994 switch (DirKind) { 3995 default: 3996 llvm_unreachable("unsupported directive"); 3997 case DK_IF: 3998 case DK_IFNE: 3999 break; 4000 case DK_IFEQ: 4001 ExprValue = ExprValue == 0; 4002 break; 4003 case DK_IFGE: 4004 ExprValue = ExprValue >= 0; 4005 break; 4006 case DK_IFGT: 4007 ExprValue = ExprValue > 0; 4008 break; 4009 case DK_IFLE: 4010 ExprValue = ExprValue <= 0; 4011 break; 4012 case DK_IFLT: 4013 ExprValue = ExprValue < 0; 4014 break; 4015 } 4016 4017 TheCondState.CondMet = ExprValue; 4018 TheCondState.Ignore = !TheCondState.CondMet; 4019 } 4020 4021 return false; 4022 } 4023 4024 /// parseDirectiveIfb 4025 /// ::= .ifb string 4026 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 4027 TheCondStack.push_back(TheCondState); 4028 TheCondState.TheCond = AsmCond::IfCond; 4029 4030 if (TheCondState.Ignore) { 4031 eatToEndOfStatement(); 4032 } else { 4033 StringRef Str = parseStringToEndOfStatement(); 4034 4035 if (getLexer().isNot(AsmToken::EndOfStatement)) 4036 return TokError("unexpected token in '.ifb' directive"); 4037 4038 Lex(); 4039 4040 TheCondState.CondMet = ExpectBlank == Str.empty(); 4041 TheCondState.Ignore = !TheCondState.CondMet; 4042 } 4043 4044 return false; 4045 } 4046 4047 /// parseDirectiveIfc 4048 /// ::= .ifc string1, string2 4049 /// ::= .ifnc string1, string2 4050 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) { 4051 TheCondStack.push_back(TheCondState); 4052 TheCondState.TheCond = AsmCond::IfCond; 4053 4054 if (TheCondState.Ignore) { 4055 eatToEndOfStatement(); 4056 } else { 4057 StringRef Str1 = parseStringToComma(); 4058 4059 if (getLexer().isNot(AsmToken::Comma)) 4060 return TokError("unexpected token in '.ifc' directive"); 4061 4062 Lex(); 4063 4064 StringRef Str2 = parseStringToEndOfStatement(); 4065 4066 if (getLexer().isNot(AsmToken::EndOfStatement)) 4067 return TokError("unexpected token in '.ifc' directive"); 4068 4069 Lex(); 4070 4071 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim()); 4072 TheCondState.Ignore = !TheCondState.CondMet; 4073 } 4074 4075 return false; 4076 } 4077 4078 /// parseDirectiveIfeqs 4079 /// ::= .ifeqs string1, string2 4080 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) { 4081 if (Lexer.isNot(AsmToken::String)) { 4082 if (ExpectEqual) 4083 TokError("expected string parameter for '.ifeqs' directive"); 4084 else 4085 TokError("expected string parameter for '.ifnes' directive"); 4086 eatToEndOfStatement(); 4087 return true; 4088 } 4089 4090 StringRef String1 = getTok().getStringContents(); 4091 Lex(); 4092 4093 if (Lexer.isNot(AsmToken::Comma)) { 4094 if (ExpectEqual) 4095 TokError("expected comma after first string for '.ifeqs' directive"); 4096 else 4097 TokError("expected comma after first string for '.ifnes' directive"); 4098 eatToEndOfStatement(); 4099 return true; 4100 } 4101 4102 Lex(); 4103 4104 if (Lexer.isNot(AsmToken::String)) { 4105 if (ExpectEqual) 4106 TokError("expected string parameter for '.ifeqs' directive"); 4107 else 4108 TokError("expected string parameter for '.ifnes' directive"); 4109 eatToEndOfStatement(); 4110 return true; 4111 } 4112 4113 StringRef String2 = getTok().getStringContents(); 4114 Lex(); 4115 4116 TheCondStack.push_back(TheCondState); 4117 TheCondState.TheCond = AsmCond::IfCond; 4118 TheCondState.CondMet = ExpectEqual == (String1 == String2); 4119 TheCondState.Ignore = !TheCondState.CondMet; 4120 4121 return false; 4122 } 4123 4124 /// parseDirectiveIfdef 4125 /// ::= .ifdef symbol 4126 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { 4127 StringRef Name; 4128 TheCondStack.push_back(TheCondState); 4129 TheCondState.TheCond = AsmCond::IfCond; 4130 4131 if (TheCondState.Ignore) { 4132 eatToEndOfStatement(); 4133 } else { 4134 if (parseIdentifier(Name)) 4135 return TokError("expected identifier after '.ifdef'"); 4136 4137 Lex(); 4138 4139 MCSymbol *Sym = getContext().lookupSymbol(Name); 4140 4141 if (expect_defined) 4142 TheCondState.CondMet = (Sym && !Sym->isUndefined()); 4143 else 4144 TheCondState.CondMet = (!Sym || Sym->isUndefined()); 4145 TheCondState.Ignore = !TheCondState.CondMet; 4146 } 4147 4148 return false; 4149 } 4150 4151 /// parseDirectiveElseIf 4152 /// ::= .elseif expression 4153 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) { 4154 if (TheCondState.TheCond != AsmCond::IfCond && 4155 TheCondState.TheCond != AsmCond::ElseIfCond) 4156 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or " 4157 " an .elseif"); 4158 TheCondState.TheCond = AsmCond::ElseIfCond; 4159 4160 bool LastIgnoreState = false; 4161 if (!TheCondStack.empty()) 4162 LastIgnoreState = TheCondStack.back().Ignore; 4163 if (LastIgnoreState || TheCondState.CondMet) { 4164 TheCondState.Ignore = true; 4165 eatToEndOfStatement(); 4166 } else { 4167 int64_t ExprValue; 4168 if (parseAbsoluteExpression(ExprValue)) 4169 return true; 4170 4171 if (getLexer().isNot(AsmToken::EndOfStatement)) 4172 return TokError("unexpected token in '.elseif' directive"); 4173 4174 Lex(); 4175 TheCondState.CondMet = ExprValue; 4176 TheCondState.Ignore = !TheCondState.CondMet; 4177 } 4178 4179 return false; 4180 } 4181 4182 /// parseDirectiveElse 4183 /// ::= .else 4184 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) { 4185 if (getLexer().isNot(AsmToken::EndOfStatement)) 4186 return TokError("unexpected token in '.else' directive"); 4187 4188 Lex(); 4189 4190 if (TheCondState.TheCond != AsmCond::IfCond && 4191 TheCondState.TheCond != AsmCond::ElseIfCond) 4192 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an " 4193 ".elseif"); 4194 TheCondState.TheCond = AsmCond::ElseCond; 4195 bool LastIgnoreState = false; 4196 if (!TheCondStack.empty()) 4197 LastIgnoreState = TheCondStack.back().Ignore; 4198 if (LastIgnoreState || TheCondState.CondMet) 4199 TheCondState.Ignore = true; 4200 else 4201 TheCondState.Ignore = false; 4202 4203 return false; 4204 } 4205 4206 /// parseDirectiveEnd 4207 /// ::= .end 4208 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { 4209 if (getLexer().isNot(AsmToken::EndOfStatement)) 4210 return TokError("unexpected token in '.end' directive"); 4211 4212 Lex(); 4213 4214 while (Lexer.isNot(AsmToken::Eof)) 4215 Lex(); 4216 4217 return false; 4218 } 4219 4220 /// parseDirectiveError 4221 /// ::= .err 4222 /// ::= .error [string] 4223 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) { 4224 if (!TheCondStack.empty()) { 4225 if (TheCondStack.back().Ignore) { 4226 eatToEndOfStatement(); 4227 return false; 4228 } 4229 } 4230 4231 if (!WithMessage) 4232 return Error(L, ".err encountered"); 4233 4234 StringRef Message = ".error directive invoked in source file"; 4235 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4236 if (Lexer.isNot(AsmToken::String)) { 4237 TokError(".error argument must be a string"); 4238 eatToEndOfStatement(); 4239 return true; 4240 } 4241 4242 Message = getTok().getStringContents(); 4243 Lex(); 4244 } 4245 4246 Error(L, Message); 4247 return true; 4248 } 4249 4250 /// parseDirectiveWarning 4251 /// ::= .warning [string] 4252 bool AsmParser::parseDirectiveWarning(SMLoc L) { 4253 if (!TheCondStack.empty()) { 4254 if (TheCondStack.back().Ignore) { 4255 eatToEndOfStatement(); 4256 return false; 4257 } 4258 } 4259 4260 StringRef Message = ".warning directive invoked in source file"; 4261 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4262 if (Lexer.isNot(AsmToken::String)) { 4263 TokError(".warning argument must be a string"); 4264 eatToEndOfStatement(); 4265 return true; 4266 } 4267 4268 Message = getTok().getStringContents(); 4269 Lex(); 4270 } 4271 4272 Warning(L, Message); 4273 return false; 4274 } 4275 4276 /// parseDirectiveEndIf 4277 /// ::= .endif 4278 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { 4279 if (getLexer().isNot(AsmToken::EndOfStatement)) 4280 return TokError("unexpected token in '.endif' directive"); 4281 4282 Lex(); 4283 4284 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) 4285 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or " 4286 ".else"); 4287 if (!TheCondStack.empty()) { 4288 TheCondState = TheCondStack.back(); 4289 TheCondStack.pop_back(); 4290 } 4291 4292 return false; 4293 } 4294 4295 void AsmParser::initializeDirectiveKindMap() { 4296 DirectiveKindMap[".set"] = DK_SET; 4297 DirectiveKindMap[".equ"] = DK_EQU; 4298 DirectiveKindMap[".equiv"] = DK_EQUIV; 4299 DirectiveKindMap[".ascii"] = DK_ASCII; 4300 DirectiveKindMap[".asciz"] = DK_ASCIZ; 4301 DirectiveKindMap[".string"] = DK_STRING; 4302 DirectiveKindMap[".byte"] = DK_BYTE; 4303 DirectiveKindMap[".short"] = DK_SHORT; 4304 DirectiveKindMap[".value"] = DK_VALUE; 4305 DirectiveKindMap[".2byte"] = DK_2BYTE; 4306 DirectiveKindMap[".long"] = DK_LONG; 4307 DirectiveKindMap[".int"] = DK_INT; 4308 DirectiveKindMap[".4byte"] = DK_4BYTE; 4309 DirectiveKindMap[".quad"] = DK_QUAD; 4310 DirectiveKindMap[".8byte"] = DK_8BYTE; 4311 DirectiveKindMap[".octa"] = DK_OCTA; 4312 DirectiveKindMap[".single"] = DK_SINGLE; 4313 DirectiveKindMap[".float"] = DK_FLOAT; 4314 DirectiveKindMap[".double"] = DK_DOUBLE; 4315 DirectiveKindMap[".align"] = DK_ALIGN; 4316 DirectiveKindMap[".align32"] = DK_ALIGN32; 4317 DirectiveKindMap[".balign"] = DK_BALIGN; 4318 DirectiveKindMap[".balignw"] = DK_BALIGNW; 4319 DirectiveKindMap[".balignl"] = DK_BALIGNL; 4320 DirectiveKindMap[".p2align"] = DK_P2ALIGN; 4321 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW; 4322 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL; 4323 DirectiveKindMap[".org"] = DK_ORG; 4324 DirectiveKindMap[".fill"] = DK_FILL; 4325 DirectiveKindMap[".zero"] = DK_ZERO; 4326 DirectiveKindMap[".extern"] = DK_EXTERN; 4327 DirectiveKindMap[".globl"] = DK_GLOBL; 4328 DirectiveKindMap[".global"] = DK_GLOBAL; 4329 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE; 4330 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP; 4331 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER; 4332 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN; 4333 DirectiveKindMap[".reference"] = DK_REFERENCE; 4334 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION; 4335 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE; 4336 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN; 4337 DirectiveKindMap[".comm"] = DK_COMM; 4338 DirectiveKindMap[".common"] = DK_COMMON; 4339 DirectiveKindMap[".lcomm"] = DK_LCOMM; 4340 DirectiveKindMap[".abort"] = DK_ABORT; 4341 DirectiveKindMap[".include"] = DK_INCLUDE; 4342 DirectiveKindMap[".incbin"] = DK_INCBIN; 4343 DirectiveKindMap[".code16"] = DK_CODE16; 4344 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC; 4345 DirectiveKindMap[".rept"] = DK_REPT; 4346 DirectiveKindMap[".rep"] = DK_REPT; 4347 DirectiveKindMap[".irp"] = DK_IRP; 4348 DirectiveKindMap[".irpc"] = DK_IRPC; 4349 DirectiveKindMap[".endr"] = DK_ENDR; 4350 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE; 4351 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK; 4352 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK; 4353 DirectiveKindMap[".if"] = DK_IF; 4354 DirectiveKindMap[".ifeq"] = DK_IFEQ; 4355 DirectiveKindMap[".ifge"] = DK_IFGE; 4356 DirectiveKindMap[".ifgt"] = DK_IFGT; 4357 DirectiveKindMap[".ifle"] = DK_IFLE; 4358 DirectiveKindMap[".iflt"] = DK_IFLT; 4359 DirectiveKindMap[".ifne"] = DK_IFNE; 4360 DirectiveKindMap[".ifb"] = DK_IFB; 4361 DirectiveKindMap[".ifnb"] = DK_IFNB; 4362 DirectiveKindMap[".ifc"] = DK_IFC; 4363 DirectiveKindMap[".ifeqs"] = DK_IFEQS; 4364 DirectiveKindMap[".ifnc"] = DK_IFNC; 4365 DirectiveKindMap[".ifnes"] = DK_IFNES; 4366 DirectiveKindMap[".ifdef"] = DK_IFDEF; 4367 DirectiveKindMap[".ifndef"] = DK_IFNDEF; 4368 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF; 4369 DirectiveKindMap[".elseif"] = DK_ELSEIF; 4370 DirectiveKindMap[".else"] = DK_ELSE; 4371 DirectiveKindMap[".end"] = DK_END; 4372 DirectiveKindMap[".endif"] = DK_ENDIF; 4373 DirectiveKindMap[".skip"] = DK_SKIP; 4374 DirectiveKindMap[".space"] = DK_SPACE; 4375 DirectiveKindMap[".file"] = DK_FILE; 4376 DirectiveKindMap[".line"] = DK_LINE; 4377 DirectiveKindMap[".loc"] = DK_LOC; 4378 DirectiveKindMap[".stabs"] = DK_STABS; 4379 DirectiveKindMap[".sleb128"] = DK_SLEB128; 4380 DirectiveKindMap[".uleb128"] = DK_ULEB128; 4381 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; 4382 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; 4383 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; 4384 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; 4385 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; 4386 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; 4387 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; 4388 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; 4389 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; 4390 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; 4391 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; 4392 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; 4393 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; 4394 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; 4395 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; 4396 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; 4397 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; 4398 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; 4399 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; 4400 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; 4401 DirectiveKindMap[".macros_on"] = DK_MACROS_ON; 4402 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF; 4403 DirectiveKindMap[".macro"] = DK_MACRO; 4404 DirectiveKindMap[".exitm"] = DK_EXITM; 4405 DirectiveKindMap[".endm"] = DK_ENDM; 4406 DirectiveKindMap[".endmacro"] = DK_ENDMACRO; 4407 DirectiveKindMap[".purgem"] = DK_PURGEM; 4408 DirectiveKindMap[".err"] = DK_ERR; 4409 DirectiveKindMap[".error"] = DK_ERROR; 4410 DirectiveKindMap[".warning"] = DK_WARNING; 4411 DirectiveKindMap[".reloc"] = DK_RELOC; 4412 } 4413 4414 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { 4415 AsmToken EndToken, StartToken = getTok(); 4416 4417 unsigned NestLevel = 0; 4418 for (;;) { 4419 // Check whether we have reached the end of the file. 4420 if (getLexer().is(AsmToken::Eof)) { 4421 Error(DirectiveLoc, "no matching '.endr' in definition"); 4422 return nullptr; 4423 } 4424 4425 if (Lexer.is(AsmToken::Identifier) && 4426 (getTok().getIdentifier() == ".rept")) { 4427 ++NestLevel; 4428 } 4429 4430 // Otherwise, check whether we have reached the .endr. 4431 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { 4432 if (NestLevel == 0) { 4433 EndToken = getTok(); 4434 Lex(); 4435 if (Lexer.isNot(AsmToken::EndOfStatement)) { 4436 TokError("unexpected token in '.endr' directive"); 4437 return nullptr; 4438 } 4439 break; 4440 } 4441 --NestLevel; 4442 } 4443 4444 // Otherwise, scan till the end of the statement. 4445 eatToEndOfStatement(); 4446 } 4447 4448 const char *BodyStart = StartToken.getLoc().getPointer(); 4449 const char *BodyEnd = EndToken.getLoc().getPointer(); 4450 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 4451 4452 // We Are Anonymous. 4453 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); 4454 return &MacroLikeBodies.back(); 4455 } 4456 4457 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 4458 raw_svector_ostream &OS) { 4459 OS << ".endr\n"; 4460 4461 std::unique_ptr<MemoryBuffer> Instantiation = 4462 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 4463 4464 // Create the macro instantiation object and add to the current macro 4465 // instantiation stack. 4466 MacroInstantiation *MI = new MacroInstantiation( 4467 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()); 4468 ActiveMacros.push_back(MI); 4469 4470 // Jump to the macro instantiation and prime the lexer. 4471 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 4472 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 4473 Lex(); 4474 } 4475 4476 /// parseDirectiveRept 4477 /// ::= .rep | .rept count 4478 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { 4479 const MCExpr *CountExpr; 4480 SMLoc CountLoc = getTok().getLoc(); 4481 if (parseExpression(CountExpr)) 4482 return true; 4483 4484 int64_t Count; 4485 if (!CountExpr->evaluateAsAbsolute(Count)) { 4486 eatToEndOfStatement(); 4487 return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); 4488 } 4489 4490 if (Count < 0) 4491 return Error(CountLoc, "Count is negative"); 4492 4493 if (Lexer.isNot(AsmToken::EndOfStatement)) 4494 return TokError("unexpected token in '" + Dir + "' directive"); 4495 4496 // Eat the end of statement. 4497 Lex(); 4498 4499 // Lex the rept definition. 4500 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 4501 if (!M) 4502 return true; 4503 4504 // Macro instantiation is lexical, unfortunately. We construct a new buffer 4505 // to hold the macro body with substitutions. 4506 SmallString<256> Buf; 4507 raw_svector_ostream OS(Buf); 4508 while (Count--) { 4509 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t). 4510 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) 4511 return true; 4512 } 4513 instantiateMacroLikeBody(M, DirectiveLoc, OS); 4514 4515 return false; 4516 } 4517 4518 /// parseDirectiveIrp 4519 /// ::= .irp symbol,values 4520 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { 4521 MCAsmMacroParameter Parameter; 4522 4523 if (parseIdentifier(Parameter.Name)) 4524 return TokError("expected identifier in '.irp' directive"); 4525 4526 if (Lexer.isNot(AsmToken::Comma)) 4527 return TokError("expected comma in '.irp' directive"); 4528 4529 Lex(); 4530 4531 MCAsmMacroArguments A; 4532 if (parseMacroArguments(nullptr, A)) 4533 return true; 4534 4535 // Eat the end of statement. 4536 Lex(); 4537 4538 // Lex the irp definition. 4539 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 4540 if (!M) 4541 return true; 4542 4543 // Macro instantiation is lexical, unfortunately. We construct a new buffer 4544 // to hold the macro body with substitutions. 4545 SmallString<256> Buf; 4546 raw_svector_ostream OS(Buf); 4547 4548 for (const MCAsmMacroArgument &Arg : A) { 4549 // Note that the AtPseudoVariable is enabled for instantiations of .irp. 4550 // This is undocumented, but GAS seems to support it. 4551 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 4552 return true; 4553 } 4554 4555 instantiateMacroLikeBody(M, DirectiveLoc, OS); 4556 4557 return false; 4558 } 4559 4560 /// parseDirectiveIrpc 4561 /// ::= .irpc symbol,values 4562 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { 4563 MCAsmMacroParameter Parameter; 4564 4565 if (parseIdentifier(Parameter.Name)) 4566 return TokError("expected identifier in '.irpc' directive"); 4567 4568 if (Lexer.isNot(AsmToken::Comma)) 4569 return TokError("expected comma in '.irpc' directive"); 4570 4571 Lex(); 4572 4573 MCAsmMacroArguments A; 4574 if (parseMacroArguments(nullptr, A)) 4575 return true; 4576 4577 if (A.size() != 1 || A.front().size() != 1) 4578 return TokError("unexpected token in '.irpc' directive"); 4579 4580 // Eat the end of statement. 4581 Lex(); 4582 4583 // Lex the irpc definition. 4584 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 4585 if (!M) 4586 return true; 4587 4588 // Macro instantiation is lexical, unfortunately. We construct a new buffer 4589 // to hold the macro body with substitutions. 4590 SmallString<256> Buf; 4591 raw_svector_ostream OS(Buf); 4592 4593 StringRef Values = A.front().front().getString(); 4594 for (std::size_t I = 0, End = Values.size(); I != End; ++I) { 4595 MCAsmMacroArgument Arg; 4596 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); 4597 4598 // Note that the AtPseudoVariable is enabled for instantiations of .irpc. 4599 // This is undocumented, but GAS seems to support it. 4600 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) 4601 return true; 4602 } 4603 4604 instantiateMacroLikeBody(M, DirectiveLoc, OS); 4605 4606 return false; 4607 } 4608 4609 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { 4610 if (ActiveMacros.empty()) 4611 return TokError("unmatched '.endr' directive"); 4612 4613 // The only .repl that should get here are the ones created by 4614 // instantiateMacroLikeBody. 4615 assert(getLexer().is(AsmToken::EndOfStatement)); 4616 4617 handleMacroExit(); 4618 return false; 4619 } 4620 4621 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, 4622 size_t Len) { 4623 const MCExpr *Value; 4624 SMLoc ExprLoc = getLexer().getLoc(); 4625 if (parseExpression(Value)) 4626 return true; 4627 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 4628 if (!MCE) 4629 return Error(ExprLoc, "unexpected expression in _emit"); 4630 uint64_t IntValue = MCE->getValue(); 4631 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) 4632 return Error(ExprLoc, "literal value out of range for directive"); 4633 4634 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); 4635 return false; 4636 } 4637 4638 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { 4639 const MCExpr *Value; 4640 SMLoc ExprLoc = getLexer().getLoc(); 4641 if (parseExpression(Value)) 4642 return true; 4643 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 4644 if (!MCE) 4645 return Error(ExprLoc, "unexpected expression in align"); 4646 uint64_t IntValue = MCE->getValue(); 4647 if (!isPowerOf2_64(IntValue)) 4648 return Error(ExprLoc, "literal value not a power of two greater then zero"); 4649 4650 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); 4651 return false; 4652 } 4653 4654 // We are comparing pointers, but the pointers are relative to a single string. 4655 // Thus, this should always be deterministic. 4656 static int rewritesSort(const AsmRewrite *AsmRewriteA, 4657 const AsmRewrite *AsmRewriteB) { 4658 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) 4659 return -1; 4660 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) 4661 return 1; 4662 4663 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output 4664 // rewrite to the same location. Make sure the SizeDirective rewrite is 4665 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This 4666 // ensures the sort algorithm is stable. 4667 if (AsmRewritePrecedence[AsmRewriteA->Kind] > 4668 AsmRewritePrecedence[AsmRewriteB->Kind]) 4669 return -1; 4670 4671 if (AsmRewritePrecedence[AsmRewriteA->Kind] < 4672 AsmRewritePrecedence[AsmRewriteB->Kind]) 4673 return 1; 4674 llvm_unreachable("Unstable rewrite sort."); 4675 } 4676 4677 bool AsmParser::parseMSInlineAsm( 4678 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, 4679 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls, 4680 SmallVectorImpl<std::string> &Constraints, 4681 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, 4682 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { 4683 SmallVector<void *, 4> InputDecls; 4684 SmallVector<void *, 4> OutputDecls; 4685 SmallVector<bool, 4> InputDeclsAddressOf; 4686 SmallVector<bool, 4> OutputDeclsAddressOf; 4687 SmallVector<std::string, 4> InputConstraints; 4688 SmallVector<std::string, 4> OutputConstraints; 4689 SmallVector<unsigned, 4> ClobberRegs; 4690 4691 SmallVector<AsmRewrite, 4> AsmStrRewrites; 4692 4693 // Prime the lexer. 4694 Lex(); 4695 4696 // While we have input, parse each statement. 4697 unsigned InputIdx = 0; 4698 unsigned OutputIdx = 0; 4699 while (getLexer().isNot(AsmToken::Eof)) { 4700 ParseStatementInfo Info(&AsmStrRewrites); 4701 if (parseStatement(Info, &SI)) 4702 return true; 4703 4704 if (Info.ParseError) 4705 return true; 4706 4707 if (Info.Opcode == ~0U) 4708 continue; 4709 4710 const MCInstrDesc &Desc = MII->get(Info.Opcode); 4711 4712 // Build the list of clobbers, outputs and inputs. 4713 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { 4714 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; 4715 4716 // Immediate. 4717 if (Operand.isImm()) 4718 continue; 4719 4720 // Register operand. 4721 if (Operand.isReg() && !Operand.needAddressOf() && 4722 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { 4723 unsigned NumDefs = Desc.getNumDefs(); 4724 // Clobber. 4725 if (NumDefs && Operand.getMCOperandNum() < NumDefs) 4726 ClobberRegs.push_back(Operand.getReg()); 4727 continue; 4728 } 4729 4730 // Expr/Input or Output. 4731 StringRef SymName = Operand.getSymName(); 4732 if (SymName.empty()) 4733 continue; 4734 4735 void *OpDecl = Operand.getOpDecl(); 4736 if (!OpDecl) 4737 continue; 4738 4739 bool isOutput = (i == 1) && Desc.mayStore(); 4740 SMLoc Start = SMLoc::getFromPointer(SymName.data()); 4741 if (isOutput) { 4742 ++InputIdx; 4743 OutputDecls.push_back(OpDecl); 4744 OutputDeclsAddressOf.push_back(Operand.needAddressOf()); 4745 OutputConstraints.push_back(("=" + Operand.getConstraint()).str()); 4746 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); 4747 } else { 4748 InputDecls.push_back(OpDecl); 4749 InputDeclsAddressOf.push_back(Operand.needAddressOf()); 4750 InputConstraints.push_back(Operand.getConstraint().str()); 4751 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); 4752 } 4753 } 4754 4755 // Consider implicit defs to be clobbers. Think of cpuid and push. 4756 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(), 4757 Desc.getNumImplicitDefs()); 4758 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); 4759 } 4760 4761 // Set the number of Outputs and Inputs. 4762 NumOutputs = OutputDecls.size(); 4763 NumInputs = InputDecls.size(); 4764 4765 // Set the unique clobbers. 4766 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); 4767 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), 4768 ClobberRegs.end()); 4769 Clobbers.assign(ClobberRegs.size(), std::string()); 4770 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { 4771 raw_string_ostream OS(Clobbers[I]); 4772 IP->printRegName(OS, ClobberRegs[I]); 4773 } 4774 4775 // Merge the various outputs and inputs. Output are expected first. 4776 if (NumOutputs || NumInputs) { 4777 unsigned NumExprs = NumOutputs + NumInputs; 4778 OpDecls.resize(NumExprs); 4779 Constraints.resize(NumExprs); 4780 for (unsigned i = 0; i < NumOutputs; ++i) { 4781 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); 4782 Constraints[i] = OutputConstraints[i]; 4783 } 4784 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { 4785 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); 4786 Constraints[j] = InputConstraints[i]; 4787 } 4788 } 4789 4790 // Build the IR assembly string. 4791 std::string AsmStringIR; 4792 raw_string_ostream OS(AsmStringIR); 4793 StringRef ASMString = 4794 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); 4795 const char *AsmStart = ASMString.begin(); 4796 const char *AsmEnd = ASMString.end(); 4797 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); 4798 for (const AsmRewrite &AR : AsmStrRewrites) { 4799 AsmRewriteKind Kind = AR.Kind; 4800 if (Kind == AOK_Delete) 4801 continue; 4802 4803 const char *Loc = AR.Loc.getPointer(); 4804 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); 4805 4806 // Emit everything up to the immediate/expression. 4807 if (unsigned Len = Loc - AsmStart) 4808 OS << StringRef(AsmStart, Len); 4809 4810 // Skip the original expression. 4811 if (Kind == AOK_Skip) { 4812 AsmStart = Loc + AR.Len; 4813 continue; 4814 } 4815 4816 unsigned AdditionalSkip = 0; 4817 // Rewrite expressions in $N notation. 4818 switch (Kind) { 4819 default: 4820 break; 4821 case AOK_Imm: 4822 OS << "$$" << AR.Val; 4823 break; 4824 case AOK_ImmPrefix: 4825 OS << "$$"; 4826 break; 4827 case AOK_Label: 4828 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; 4829 break; 4830 case AOK_Input: 4831 OS << '$' << InputIdx++; 4832 break; 4833 case AOK_Output: 4834 OS << '$' << OutputIdx++; 4835 break; 4836 case AOK_SizeDirective: 4837 switch (AR.Val) { 4838 default: break; 4839 case 8: OS << "byte ptr "; break; 4840 case 16: OS << "word ptr "; break; 4841 case 32: OS << "dword ptr "; break; 4842 case 64: OS << "qword ptr "; break; 4843 case 80: OS << "xword ptr "; break; 4844 case 128: OS << "xmmword ptr "; break; 4845 case 256: OS << "ymmword ptr "; break; 4846 } 4847 break; 4848 case AOK_Emit: 4849 OS << ".byte"; 4850 break; 4851 case AOK_Align: { 4852 // MS alignment directives are measured in bytes. If the native assembler 4853 // measures alignment in bytes, we can pass it straight through. 4854 OS << ".align"; 4855 if (getContext().getAsmInfo()->getAlignmentIsInBytes()) 4856 break; 4857 4858 // Alignment is in log2 form, so print that instead and skip the original 4859 // immediate. 4860 unsigned Val = AR.Val; 4861 OS << ' ' << Val; 4862 assert(Val < 10 && "Expected alignment less then 2^10."); 4863 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; 4864 break; 4865 } 4866 case AOK_DotOperator: 4867 // Insert the dot if the user omitted it. 4868 OS.flush(); 4869 if (AsmStringIR.back() != '.') 4870 OS << '.'; 4871 OS << AR.Val; 4872 break; 4873 } 4874 4875 // Skip the original expression. 4876 AsmStart = Loc + AR.Len + AdditionalSkip; 4877 } 4878 4879 // Emit the remainder of the asm string. 4880 if (AsmStart != AsmEnd) 4881 OS << StringRef(AsmStart, AsmEnd - AsmStart); 4882 4883 AsmString = OS.str(); 4884 return false; 4885 } 4886 4887 namespace llvm { 4888 namespace MCParserUtils { 4889 4890 /// Returns whether the given symbol is used anywhere in the given expression, 4891 /// or subexpressions. 4892 static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) { 4893 switch (Value->getKind()) { 4894 case MCExpr::Binary: { 4895 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value); 4896 return isSymbolUsedInExpression(Sym, BE->getLHS()) || 4897 isSymbolUsedInExpression(Sym, BE->getRHS()); 4898 } 4899 case MCExpr::Target: 4900 case MCExpr::Constant: 4901 return false; 4902 case MCExpr::SymbolRef: { 4903 const MCSymbol &S = 4904 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol(); 4905 if (S.isVariable()) 4906 return isSymbolUsedInExpression(Sym, S.getVariableValue()); 4907 return &S == Sym; 4908 } 4909 case MCExpr::Unary: 4910 return isSymbolUsedInExpression( 4911 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr()); 4912 } 4913 4914 llvm_unreachable("Unknown expr kind!"); 4915 } 4916 4917 bool parseAssignmentExpression(StringRef Name, bool allow_redef, 4918 MCAsmParser &Parser, MCSymbol *&Sym, 4919 const MCExpr *&Value) { 4920 MCAsmLexer &Lexer = Parser.getLexer(); 4921 4922 // FIXME: Use better location, we should use proper tokens. 4923 SMLoc EqualLoc = Lexer.getLoc(); 4924 4925 if (Parser.parseExpression(Value)) { 4926 Parser.TokError("missing expression"); 4927 Parser.eatToEndOfStatement(); 4928 return true; 4929 } 4930 4931 // Note: we don't count b as used in "a = b". This is to allow 4932 // a = b 4933 // b = c 4934 4935 if (Lexer.isNot(AsmToken::EndOfStatement)) 4936 return Parser.TokError("unexpected token in assignment"); 4937 4938 // Eat the end of statement marker. 4939 Parser.Lex(); 4940 4941 // Validate that the LHS is allowed to be a variable (either it has not been 4942 // used as a symbol, or it is an absolute symbol). 4943 Sym = Parser.getContext().lookupSymbol(Name); 4944 if (Sym) { 4945 // Diagnose assignment to a label. 4946 // 4947 // FIXME: Diagnostics. Note the location of the definition as a label. 4948 // FIXME: Diagnose assignment to protected identifier (e.g., register name). 4949 if (isSymbolUsedInExpression(Sym, Value)) 4950 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'"); 4951 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() && 4952 !Sym->isVariable()) 4953 ; // Allow redefinitions of undefined symbols only used in directives. 4954 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef) 4955 ; // Allow redefinitions of variables that haven't yet been used. 4956 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef)) 4957 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'"); 4958 else if (!Sym->isVariable()) 4959 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'"); 4960 else if (!isa<MCConstantExpr>(Sym->getVariableValue())) 4961 return Parser.Error(EqualLoc, 4962 "invalid reassignment of non-absolute variable '" + 4963 Name + "'"); 4964 } else if (Name == ".") { 4965 Parser.getStreamer().emitValueToOffset(Value, 0); 4966 return false; 4967 } else 4968 Sym = Parser.getContext().getOrCreateSymbol(Name); 4969 4970 Sym->setRedefinable(allow_redef); 4971 4972 return false; 4973 } 4974 4975 } // namespace MCParserUtils 4976 } // namespace llvm 4977 4978 /// \brief Create an MCAsmParser instance. 4979 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C, 4980 MCStreamer &Out, const MCAsmInfo &MAI) { 4981 return new AsmParser(SM, C, Out, MAI); 4982 } 4983