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