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