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