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