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