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