1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This class implements the parser for assembly files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/StringSwitch.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/BinaryFormat/Dwarf.h" 26 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCCodeView.h" 29 #include "llvm/MC/MCContext.h" 30 #include "llvm/MC/MCDirectives.h" 31 #include "llvm/MC/MCDwarf.h" 32 #include "llvm/MC/MCExpr.h" 33 #include "llvm/MC/MCInstPrinter.h" 34 #include "llvm/MC/MCInstrDesc.h" 35 #include "llvm/MC/MCInstrInfo.h" 36 #include "llvm/MC/MCObjectFileInfo.h" 37 #include "llvm/MC/MCParser/AsmCond.h" 38 #include "llvm/MC/MCParser/AsmLexer.h" 39 #include "llvm/MC/MCParser/MCAsmLexer.h" 40 #include "llvm/MC/MCParser/MCAsmParser.h" 41 #include "llvm/MC/MCParser/MCAsmParserExtension.h" 42 #include "llvm/MC/MCParser/MCAsmParserUtils.h" 43 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 44 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 45 #include "llvm/MC/MCRegisterInfo.h" 46 #include "llvm/MC/MCSection.h" 47 #include "llvm/MC/MCStreamer.h" 48 #include "llvm/MC/MCSymbol.h" 49 #include "llvm/MC/MCTargetOptions.h" 50 #include "llvm/MC/MCValue.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/Format.h" 55 #include "llvm/Support/MD5.h" 56 #include "llvm/Support/MathExtras.h" 57 #include "llvm/Support/MemoryBuffer.h" 58 #include "llvm/Support/SMLoc.h" 59 #include "llvm/Support/SourceMgr.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include <algorithm> 62 #include <cassert> 63 #include <cctype> 64 #include <climits> 65 #include <cstddef> 66 #include <cstdint> 67 #include <deque> 68 #include <memory> 69 #include <sstream> 70 #include <string> 71 #include <tuple> 72 #include <utility> 73 #include <vector> 74 75 using namespace llvm; 76 77 extern cl::opt<unsigned> AsmMacroMaxNestingDepth; 78 79 namespace { 80 81 /// Helper types for tracking macro definitions. 82 typedef std::vector<AsmToken> MCAsmMacroArgument; 83 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments; 84 85 /// Helper class for storing information about an active macro instantiation. 86 struct MacroInstantiation { 87 /// The location of the instantiation. 88 SMLoc InstantiationLoc; 89 90 /// The buffer where parsing should resume upon instantiation completion. 91 unsigned ExitBuffer; 92 93 /// The location where parsing should resume upon instantiation completion. 94 SMLoc ExitLoc; 95 96 /// The depth of TheCondStack at the start of the instantiation. 97 size_t CondStackDepth; 98 }; 99 100 struct ParseStatementInfo { 101 /// The parsed operands from the last parsed statement. 102 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands; 103 104 /// The opcode from the last parsed instruction. 105 unsigned Opcode = ~0U; 106 107 /// Was there an error parsing the inline assembly? 108 bool ParseError = false; 109 110 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr; 111 112 ParseStatementInfo() = delete; 113 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites) 114 : AsmRewrites(rewrites) {} 115 }; 116 117 enum FieldType { 118 FT_INTEGRAL, // Initializer: integer expression, stored as an MCExpr. 119 FT_REAL, // Initializer: real number, stored as an APInt. 120 FT_STRUCT // Initializer: struct initializer, stored recursively. 121 }; 122 123 struct FieldInfo; 124 struct StructInfo { 125 StringRef Name; 126 bool IsUnion = false; 127 unsigned Alignment = 0; 128 unsigned Size = 0; 129 unsigned AlignmentSize = 0; 130 std::vector<FieldInfo> Fields; 131 StringMap<size_t> FieldsByName; 132 133 FieldInfo &addField(StringRef FieldName, FieldType FT, 134 unsigned FieldAlignmentSize); 135 136 StructInfo() = default; 137 138 StructInfo(StringRef StructName, bool Union, unsigned AlignmentValue) 139 : Name(StructName), IsUnion(Union), Alignment(AlignmentValue) {} 140 }; 141 142 // FIXME: This should probably use a class hierarchy, raw pointers between the 143 // objects, and dynamic type resolution instead of a union. On the other hand, 144 // ownership then becomes much more complicated; the obvious thing would be to 145 // use BumpPtrAllocator, but the lack of a destructor makes that messy. 146 147 struct StructInitializer; 148 struct IntFieldInfo { 149 SmallVector<const MCExpr *, 1> Values; 150 151 IntFieldInfo() = default; 152 IntFieldInfo(const SmallVector<const MCExpr *, 1> &V) { Values = V; } 153 IntFieldInfo(SmallVector<const MCExpr *, 1> &&V) { Values = V; } 154 }; 155 struct RealFieldInfo { 156 SmallVector<APInt, 1> AsIntValues; 157 158 RealFieldInfo() = default; 159 RealFieldInfo(const SmallVector<APInt, 1> &V) { AsIntValues = V; } 160 RealFieldInfo(SmallVector<APInt, 1> &&V) { AsIntValues = V; } 161 }; 162 struct StructFieldInfo { 163 std::vector<StructInitializer> Initializers; 164 StructInfo Structure; 165 166 StructFieldInfo() = default; 167 StructFieldInfo(const std::vector<StructInitializer> &V, StructInfo S) { 168 Initializers = V; 169 Structure = S; 170 } 171 StructFieldInfo(std::vector<StructInitializer> &&V, StructInfo S) { 172 Initializers = V; 173 Structure = S; 174 } 175 }; 176 177 class FieldInitializer { 178 public: 179 FieldType FT; 180 union { 181 IntFieldInfo IntInfo; 182 RealFieldInfo RealInfo; 183 StructFieldInfo StructInfo; 184 }; 185 186 ~FieldInitializer() { 187 switch (FT) { 188 case FT_INTEGRAL: 189 IntInfo.~IntFieldInfo(); 190 break; 191 case FT_REAL: 192 RealInfo.~RealFieldInfo(); 193 break; 194 case FT_STRUCT: 195 StructInfo.~StructFieldInfo(); 196 break; 197 } 198 } 199 200 FieldInitializer(FieldType FT) : FT(FT) { 201 switch (FT) { 202 case FT_INTEGRAL: 203 new (&IntInfo) IntFieldInfo(); 204 break; 205 case FT_REAL: 206 new (&RealInfo) RealFieldInfo(); 207 break; 208 case FT_STRUCT: 209 new (&StructInfo) StructFieldInfo(); 210 break; 211 } 212 } 213 214 FieldInitializer(SmallVector<const MCExpr *, 1> &&Values) : FT(FT_INTEGRAL) { 215 new (&IntInfo) IntFieldInfo(Values); 216 } 217 218 FieldInitializer(SmallVector<APInt, 1> &&AsIntValues) : FT(FT_REAL) { 219 new (&RealInfo) RealFieldInfo(AsIntValues); 220 } 221 222 FieldInitializer(std::vector<StructInitializer> &&Initializers, 223 struct StructInfo Structure) 224 : FT(FT_STRUCT) { 225 new (&StructInfo) StructFieldInfo(Initializers, Structure); 226 } 227 228 FieldInitializer(const FieldInitializer &Initializer) : FT(Initializer.FT) { 229 switch (FT) { 230 case FT_INTEGRAL: 231 new (&IntInfo) IntFieldInfo(Initializer.IntInfo); 232 break; 233 case FT_REAL: 234 new (&RealInfo) RealFieldInfo(Initializer.RealInfo); 235 break; 236 case FT_STRUCT: 237 new (&StructInfo) StructFieldInfo(Initializer.StructInfo); 238 break; 239 } 240 } 241 242 FieldInitializer(FieldInitializer &&Initializer) : FT(Initializer.FT) { 243 switch (FT) { 244 case FT_INTEGRAL: 245 new (&IntInfo) IntFieldInfo(Initializer.IntInfo); 246 break; 247 case FT_REAL: 248 new (&RealInfo) RealFieldInfo(Initializer.RealInfo); 249 break; 250 case FT_STRUCT: 251 new (&StructInfo) StructFieldInfo(Initializer.StructInfo); 252 break; 253 } 254 } 255 256 FieldInitializer &operator=(const FieldInitializer &Initializer) { 257 if (FT != Initializer.FT) { 258 switch (FT) { 259 case FT_INTEGRAL: 260 IntInfo.~IntFieldInfo(); 261 break; 262 case FT_REAL: 263 RealInfo.~RealFieldInfo(); 264 break; 265 case FT_STRUCT: 266 StructInfo.~StructFieldInfo(); 267 break; 268 } 269 } 270 FT = Initializer.FT; 271 switch (FT) { 272 case FT_INTEGRAL: 273 IntInfo = Initializer.IntInfo; 274 break; 275 case FT_REAL: 276 RealInfo = Initializer.RealInfo; 277 break; 278 case FT_STRUCT: 279 StructInfo = Initializer.StructInfo; 280 break; 281 } 282 return *this; 283 } 284 285 FieldInitializer &operator=(FieldInitializer &&Initializer) { 286 if (FT != Initializer.FT) { 287 switch (FT) { 288 case FT_INTEGRAL: 289 IntInfo.~IntFieldInfo(); 290 break; 291 case FT_REAL: 292 RealInfo.~RealFieldInfo(); 293 break; 294 case FT_STRUCT: 295 StructInfo.~StructFieldInfo(); 296 break; 297 } 298 } 299 FT = Initializer.FT; 300 switch (FT) { 301 case FT_INTEGRAL: 302 IntInfo = Initializer.IntInfo; 303 break; 304 case FT_REAL: 305 RealInfo = Initializer.RealInfo; 306 break; 307 case FT_STRUCT: 308 StructInfo = Initializer.StructInfo; 309 break; 310 } 311 return *this; 312 } 313 }; 314 315 struct StructInitializer { 316 std::vector<FieldInitializer> FieldInitializers; 317 }; 318 319 struct FieldInfo { 320 // Offset of the field within the containing STRUCT. 321 size_t Offset = 0; 322 323 // Total size of the field (= LengthOf * Type). 324 unsigned SizeOf = 0; 325 326 // Number of elements in the field (1 if scalar, >1 if an array). 327 unsigned LengthOf = 0; 328 329 // Size of a single entry in this field, in bytes ("type" in MASM standards). 330 unsigned Type = 0; 331 332 FieldInitializer Contents; 333 334 FieldInfo(FieldType FT) : Contents(FT) {} 335 }; 336 337 FieldInfo &StructInfo::addField(StringRef FieldName, FieldType FT, 338 unsigned FieldAlignmentSize) { 339 if (!FieldName.empty()) 340 FieldsByName[FieldName.lower()] = Fields.size(); 341 Fields.emplace_back(FT); 342 FieldInfo &Field = Fields.back(); 343 if (IsUnion) { 344 Field.Offset = 0; 345 } else { 346 Size = llvm::alignTo(Size, std::min(Alignment, FieldAlignmentSize)); 347 Field.Offset = Size; 348 } 349 AlignmentSize = std::max(AlignmentSize, FieldAlignmentSize); 350 return Field; 351 } 352 353 /// The concrete assembly parser instance. 354 // Note that this is a full MCAsmParser, not an MCAsmParserExtension! 355 // It's a peer of AsmParser, not of COFFAsmParser, WasmAsmParser, etc. 356 class MasmParser : public MCAsmParser { 357 private: 358 AsmLexer Lexer; 359 MCContext &Ctx; 360 MCStreamer &Out; 361 const MCAsmInfo &MAI; 362 SourceMgr &SrcMgr; 363 SourceMgr::DiagHandlerTy SavedDiagHandler; 364 void *SavedDiagContext; 365 std::unique_ptr<MCAsmParserExtension> PlatformParser; 366 367 /// This is the current buffer index we're lexing from as managed by the 368 /// SourceMgr object. 369 unsigned CurBuffer; 370 371 AsmCond TheCondState; 372 std::vector<AsmCond> TheCondStack; 373 374 /// maps directive names to handler methods in parser 375 /// extensions. Extensions register themselves in this map by calling 376 /// addDirectiveHandler. 377 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap; 378 379 /// maps assembly-time variable names to variables. 380 struct Variable { 381 StringRef Name; 382 bool Redefinable = true; 383 bool IsText = false; 384 int64_t NumericValue = 0; 385 std::string TextValue; 386 }; 387 StringMap<Variable> Variables; 388 389 /// Stack of active struct definitions. 390 SmallVector<StructInfo, 1> StructInProgress; 391 392 /// Maps struct tags to struct definitions. 393 StringMap<StructInfo> Structs; 394 395 /// Maps data location names to types. 396 StringMap<AsmTypeInfo> KnownType; 397 398 /// Stack of active macro instantiations. 399 std::vector<MacroInstantiation*> ActiveMacros; 400 401 /// List of bodies of anonymous macros. 402 std::deque<MCAsmMacro> MacroLikeBodies; 403 404 /// Keeps track of how many .macro's have been instantiated. 405 unsigned NumOfMacroInstantiations; 406 407 /// The values from the last parsed cpp hash file line comment if any. 408 struct CppHashInfoTy { 409 StringRef Filename; 410 int64_t LineNumber; 411 SMLoc Loc; 412 unsigned Buf; 413 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {} 414 }; 415 CppHashInfoTy CppHashInfo; 416 417 /// The filename from the first cpp hash file line comment, if any. 418 StringRef FirstCppHashFilename; 419 420 /// List of forward directional labels for diagnosis at the end. 421 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels; 422 423 /// AssemblerDialect. ~OU means unset value and use value provided by MAI. 424 /// Defaults to 1U, meaning Intel. 425 unsigned AssemblerDialect = 1U; 426 427 /// is Darwin compatibility enabled? 428 bool IsDarwin = false; 429 430 /// Are we parsing ms-style inline assembly? 431 bool ParsingMSInlineAsm = false; 432 433 /// Did we already inform the user about inconsistent MD5 usage? 434 bool ReportedInconsistentMD5 = false; 435 436 // Current <...> expression depth. 437 unsigned AngleBracketDepth = 0U; 438 439 // Number of locals defined. 440 uint16_t LocalCounter = 0; 441 442 public: 443 MasmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 444 const MCAsmInfo &MAI, unsigned CB); 445 MasmParser(const MasmParser &) = delete; 446 MasmParser &operator=(const MasmParser &) = delete; 447 ~MasmParser() override; 448 449 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override; 450 451 void addDirectiveHandler(StringRef Directive, 452 ExtensionDirectiveHandler Handler) override { 453 ExtensionDirectiveMap[Directive] = Handler; 454 if (DirectiveKindMap.find(Directive) == DirectiveKindMap.end()) { 455 DirectiveKindMap[Directive] = DK_HANDLER_DIRECTIVE; 456 } 457 } 458 459 void addAliasForDirective(StringRef Directive, StringRef Alias) override { 460 DirectiveKindMap[Directive] = DirectiveKindMap[Alias]; 461 } 462 463 /// @name MCAsmParser Interface 464 /// { 465 466 SourceMgr &getSourceManager() override { return SrcMgr; } 467 MCAsmLexer &getLexer() override { return Lexer; } 468 MCContext &getContext() override { return Ctx; } 469 MCStreamer &getStreamer() override { return Out; } 470 471 CodeViewContext &getCVContext() { return Ctx.getCVContext(); } 472 473 unsigned getAssemblerDialect() override { 474 if (AssemblerDialect == ~0U) 475 return MAI.getAssemblerDialect(); 476 else 477 return AssemblerDialect; 478 } 479 void setAssemblerDialect(unsigned i) override { 480 AssemblerDialect = i; 481 } 482 483 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override; 484 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override; 485 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override; 486 487 const AsmToken &Lex() override; 488 489 void setParsingMSInlineAsm(bool V) override { 490 ParsingMSInlineAsm = V; 491 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and 492 // hex integer literals. 493 Lexer.setLexMasmIntegers(V); 494 } 495 bool isParsingMSInlineAsm() override { return ParsingMSInlineAsm; } 496 497 bool isParsingMasm() const override { return true; } 498 499 bool lookUpField(StringRef Name, AsmFieldInfo &Info) const override; 500 bool lookUpField(StringRef Base, StringRef Member, 501 AsmFieldInfo &Info) const override; 502 503 bool lookUpType(StringRef Name, AsmTypeInfo &Info) const override; 504 505 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString, 506 unsigned &NumOutputs, unsigned &NumInputs, 507 SmallVectorImpl<std::pair<void *,bool>> &OpDecls, 508 SmallVectorImpl<std::string> &Constraints, 509 SmallVectorImpl<std::string> &Clobbers, 510 const MCInstrInfo *MII, const MCInstPrinter *IP, 511 MCAsmParserSemaCallback &SI) override; 512 513 bool parseExpression(const MCExpr *&Res); 514 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 515 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc, 516 AsmTypeInfo *TypeInfo) override; 517 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override; 518 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 519 SMLoc &EndLoc) override; 520 bool parseAbsoluteExpression(int64_t &Res) override; 521 522 /// Parse a floating point expression using the float \p Semantics 523 /// and set \p Res to the value. 524 bool parseRealValue(const fltSemantics &Semantics, APInt &Res); 525 526 /// Parse an identifier or string (as a quoted identifier) 527 /// and set \p Res to the identifier contents. 528 bool parseIdentifier(StringRef &Res) override; 529 void eatToEndOfStatement() override; 530 531 bool checkForValidSection() override; 532 533 /// } 534 535 private: 536 bool parseStatement(ParseStatementInfo &Info, 537 MCAsmParserSemaCallback *SI); 538 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites); 539 bool parseCppHashLineFilenameComment(SMLoc L); 540 541 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body, 542 ArrayRef<MCAsmMacroParameter> Parameters); 543 bool expandMacro(raw_svector_ostream &OS, StringRef Body, 544 ArrayRef<MCAsmMacroParameter> Parameters, 545 ArrayRef<MCAsmMacroArgument> A, 546 const std::vector<std::string> &Locals, SMLoc L); 547 548 /// Are we inside a macro instantiation? 549 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();} 550 551 /// Handle entry to macro instantiation. 552 /// 553 /// \param M The macro. 554 /// \param NameLoc Instantiation location. 555 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc); 556 557 /// Handle exit from macro instantiation. 558 void handleMacroExit(); 559 560 /// Extract AsmTokens for a macro argument. 561 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg); 562 563 /// Parse all macro arguments for a given macro. 564 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A); 565 566 void printMacroInstantiations(); 567 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg, 568 SMRange Range = None) const { 569 ArrayRef<SMRange> Ranges(Range); 570 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges); 571 } 572 static void DiagHandler(const SMDiagnostic &Diag, void *Context); 573 574 bool lookUpField(const StructInfo &Structure, StringRef Member, 575 AsmFieldInfo &Info) const; 576 577 /// Should we emit DWARF describing this assembler source? (Returns false if 578 /// the source has .file directives, which means we don't want to generate 579 /// info describing the assembler source itself.) 580 bool enabledGenDwarfForAssembly(); 581 582 /// Enter the specified file. This returns true on failure. 583 bool enterIncludeFile(const std::string &Filename); 584 585 /// Reset the current lexer position to that given by \p Loc. The 586 /// current token is not set; clients should ensure Lex() is called 587 /// subsequently. 588 /// 589 /// \param InBuffer If not 0, should be the known buffer id that contains the 590 /// location. 591 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0); 592 593 /// Parse up to the end of statement and a return the contents from the 594 /// current token until the end of the statement; the current token on exit 595 /// will be either the EndOfStatement or EOF. 596 StringRef parseStringToEndOfStatement() override; 597 598 bool parseTextItem(std::string &Data); 599 600 unsigned getBinOpPrecedence(AsmToken::TokenKind K, 601 MCBinaryExpr::Opcode &Kind); 602 603 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc); 604 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc); 605 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc); 606 607 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc); 608 609 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName); 610 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName); 611 612 // Generic (target and platform independent) directive parsing. 613 enum DirectiveKind { 614 DK_NO_DIRECTIVE, // Placeholder 615 DK_HANDLER_DIRECTIVE, 616 DK_ASSIGN, 617 DK_EQU, 618 DK_TEXTEQU, 619 DK_ASCII, 620 DK_ASCIZ, 621 DK_STRING, 622 DK_BYTE, 623 DK_SBYTE, 624 DK_WORD, 625 DK_SWORD, 626 DK_DWORD, 627 DK_SDWORD, 628 DK_FWORD, 629 DK_QWORD, 630 DK_SQWORD, 631 DK_DB, 632 DK_DD, 633 DK_DF, 634 DK_DQ, 635 DK_DW, 636 DK_REAL4, 637 DK_REAL8, 638 DK_REAL10, 639 DK_ALIGN, 640 DK_ORG, 641 DK_ENDR, 642 DK_EXTERN, 643 DK_PUBLIC, 644 DK_COMM, 645 DK_COMMENT, 646 DK_INCLUDE, 647 DK_REPT, 648 DK_IRP, 649 DK_IRPC, 650 DK_IF, 651 DK_IFE, 652 DK_IFB, 653 DK_IFNB, 654 DK_IFDEF, 655 DK_IFNDEF, 656 DK_IFDIF, 657 DK_IFDIFI, 658 DK_IFIDN, 659 DK_IFIDNI, 660 DK_ELSEIF, 661 DK_ELSEIFE, 662 DK_ELSEIFB, 663 DK_ELSEIFNB, 664 DK_ELSEIFDEF, 665 DK_ELSEIFNDEF, 666 DK_ELSEIFDIF, 667 DK_ELSEIFDIFI, 668 DK_ELSEIFIDN, 669 DK_ELSEIFIDNI, 670 DK_ELSE, 671 DK_ENDIF, 672 DK_FILE, 673 DK_LINE, 674 DK_LOC, 675 DK_STABS, 676 DK_CV_FILE, 677 DK_CV_FUNC_ID, 678 DK_CV_INLINE_SITE_ID, 679 DK_CV_LOC, 680 DK_CV_LINETABLE, 681 DK_CV_INLINE_LINETABLE, 682 DK_CV_DEF_RANGE, 683 DK_CV_STRINGTABLE, 684 DK_CV_STRING, 685 DK_CV_FILECHECKSUMS, 686 DK_CV_FILECHECKSUM_OFFSET, 687 DK_CV_FPO_DATA, 688 DK_CFI_SECTIONS, 689 DK_CFI_STARTPROC, 690 DK_CFI_ENDPROC, 691 DK_CFI_DEF_CFA, 692 DK_CFI_DEF_CFA_OFFSET, 693 DK_CFI_ADJUST_CFA_OFFSET, 694 DK_CFI_DEF_CFA_REGISTER, 695 DK_CFI_OFFSET, 696 DK_CFI_REL_OFFSET, 697 DK_CFI_PERSONALITY, 698 DK_CFI_LSDA, 699 DK_CFI_REMEMBER_STATE, 700 DK_CFI_RESTORE_STATE, 701 DK_CFI_SAME_VALUE, 702 DK_CFI_RESTORE, 703 DK_CFI_ESCAPE, 704 DK_CFI_RETURN_COLUMN, 705 DK_CFI_SIGNAL_FRAME, 706 DK_CFI_UNDEFINED, 707 DK_CFI_REGISTER, 708 DK_CFI_WINDOW_SAVE, 709 DK_CFI_B_KEY_FRAME, 710 DK_MACRO, 711 DK_EXITM, 712 DK_ENDM, 713 DK_PURGEM, 714 DK_ERR, 715 DK_ERRB, 716 DK_ERRNB, 717 DK_ERRDEF, 718 DK_ERRNDEF, 719 DK_ERRDIF, 720 DK_ERRDIFI, 721 DK_ERRIDN, 722 DK_ERRIDNI, 723 DK_ERRE, 724 DK_ERRNZ, 725 DK_ECHO, 726 DK_STRUCT, 727 DK_UNION, 728 DK_ENDS, 729 DK_END, 730 DK_PUSHFRAME, 731 DK_PUSHREG, 732 DK_SAVEREG, 733 DK_SAVEXMM128, 734 DK_SETFRAME, 735 DK_RADIX, 736 }; 737 738 /// Maps directive name --> DirectiveKind enum, for directives parsed by this 739 /// class. 740 StringMap<DirectiveKind> DirectiveKindMap; 741 742 // Codeview def_range type parsing. 743 enum CVDefRangeType { 744 CVDR_DEFRANGE = 0, // Placeholder 745 CVDR_DEFRANGE_REGISTER, 746 CVDR_DEFRANGE_FRAMEPOINTER_REL, 747 CVDR_DEFRANGE_SUBFIELD_REGISTER, 748 CVDR_DEFRANGE_REGISTER_REL 749 }; 750 751 /// Maps Codeview def_range types --> CVDefRangeType enum, for Codeview 752 /// def_range types parsed by this class. 753 StringMap<CVDefRangeType> CVDefRangeTypeMap; 754 755 bool parseInitValue(unsigned Size); 756 757 // ".ascii", ".asciz", ".string" 758 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated); 759 760 // "byte", "word", ... 761 bool emitIntValue(const MCExpr *Value, unsigned Size); 762 bool parseScalarInitializer(unsigned Size, 763 SmallVectorImpl<const MCExpr *> &Values, 764 unsigned StringPadLength = 0); 765 bool parseScalarInstList( 766 unsigned Size, SmallVectorImpl<const MCExpr *> &Values, 767 const AsmToken::TokenKind EndToken = AsmToken::EndOfStatement); 768 bool emitIntegralValues(unsigned Size, unsigned *Count = nullptr); 769 bool addIntegralField(StringRef Name, unsigned Size); 770 bool parseDirectiveValue(StringRef IDVal, unsigned Size); 771 bool parseDirectiveNamedValue(StringRef TypeName, unsigned Size, 772 StringRef Name, SMLoc NameLoc); 773 774 // "real4", "real8", "real10" 775 bool emitRealValues(const fltSemantics &Semantics, unsigned *Count = nullptr); 776 bool addRealField(StringRef Name, const fltSemantics &Semantics, size_t Size); 777 bool parseDirectiveRealValue(StringRef IDVal, const fltSemantics &Semantics, 778 size_t Size); 779 bool parseRealInstList( 780 const fltSemantics &Semantics, SmallVectorImpl<APInt> &Values, 781 const AsmToken::TokenKind EndToken = AsmToken::EndOfStatement); 782 bool parseDirectiveNamedRealValue(StringRef TypeName, 783 const fltSemantics &Semantics, 784 unsigned Size, StringRef Name, 785 SMLoc NameLoc); 786 787 bool parseOptionalAngleBracketOpen(); 788 bool parseAngleBracketClose(const Twine &Msg = "expected '>'"); 789 790 bool parseFieldInitializer(const FieldInfo &Field, 791 FieldInitializer &Initializer); 792 bool parseFieldInitializer(const FieldInfo &Field, 793 const IntFieldInfo &Contents, 794 FieldInitializer &Initializer); 795 bool parseFieldInitializer(const FieldInfo &Field, 796 const RealFieldInfo &Contents, 797 FieldInitializer &Initializer); 798 bool parseFieldInitializer(const FieldInfo &Field, 799 const StructFieldInfo &Contents, 800 FieldInitializer &Initializer); 801 802 bool parseStructInitializer(const StructInfo &Structure, 803 StructInitializer &Initializer); 804 bool parseStructInstList( 805 const StructInfo &Structure, std::vector<StructInitializer> &Initializers, 806 const AsmToken::TokenKind EndToken = AsmToken::EndOfStatement); 807 808 bool emitFieldValue(const FieldInfo &Field); 809 bool emitFieldValue(const FieldInfo &Field, const IntFieldInfo &Contents); 810 bool emitFieldValue(const FieldInfo &Field, const RealFieldInfo &Contents); 811 bool emitFieldValue(const FieldInfo &Field, const StructFieldInfo &Contents); 812 813 bool emitFieldInitializer(const FieldInfo &Field, 814 const FieldInitializer &Initializer); 815 bool emitFieldInitializer(const FieldInfo &Field, 816 const IntFieldInfo &Contents, 817 const IntFieldInfo &Initializer); 818 bool emitFieldInitializer(const FieldInfo &Field, 819 const RealFieldInfo &Contents, 820 const RealFieldInfo &Initializer); 821 bool emitFieldInitializer(const FieldInfo &Field, 822 const StructFieldInfo &Contents, 823 const StructFieldInfo &Initializer); 824 825 bool emitStructInitializer(const StructInfo &Structure, 826 const StructInitializer &Initializer); 827 828 // User-defined types (structs, unions): 829 bool emitStructValues(const StructInfo &Structure, unsigned *Count = nullptr); 830 bool addStructField(StringRef Name, const StructInfo &Structure); 831 bool parseDirectiveStructValue(const StructInfo &Structure, 832 StringRef Directive, SMLoc DirLoc); 833 bool parseDirectiveNamedStructValue(const StructInfo &Structure, 834 StringRef Directive, SMLoc DirLoc, 835 StringRef Name); 836 837 // "=", "equ", "textequ" 838 bool parseDirectiveEquate(StringRef IDVal, StringRef Name, 839 DirectiveKind DirKind); 840 841 bool parseDirectiveOrg(); // ".org" 842 bool parseDirectiveAlign(); // "align" 843 844 // ".file", ".line", ".loc", ".stabs" 845 bool parseDirectiveFile(SMLoc DirectiveLoc); 846 bool parseDirectiveLine(); 847 bool parseDirectiveLoc(); 848 bool parseDirectiveStabs(); 849 850 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable", 851 // ".cv_inline_linetable", ".cv_def_range", ".cv_string" 852 bool parseDirectiveCVFile(); 853 bool parseDirectiveCVFuncId(); 854 bool parseDirectiveCVInlineSiteId(); 855 bool parseDirectiveCVLoc(); 856 bool parseDirectiveCVLinetable(); 857 bool parseDirectiveCVInlineLinetable(); 858 bool parseDirectiveCVDefRange(); 859 bool parseDirectiveCVString(); 860 bool parseDirectiveCVStringTable(); 861 bool parseDirectiveCVFileChecksums(); 862 bool parseDirectiveCVFileChecksumOffset(); 863 bool parseDirectiveCVFPOData(); 864 865 // .cfi directives 866 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc); 867 bool parseDirectiveCFIWindowSave(); 868 bool parseDirectiveCFISections(); 869 bool parseDirectiveCFIStartProc(); 870 bool parseDirectiveCFIEndProc(); 871 bool parseDirectiveCFIDefCfaOffset(); 872 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc); 873 bool parseDirectiveCFIAdjustCfaOffset(); 874 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc); 875 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc); 876 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc); 877 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality); 878 bool parseDirectiveCFIRememberState(); 879 bool parseDirectiveCFIRestoreState(); 880 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc); 881 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc); 882 bool parseDirectiveCFIEscape(); 883 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc); 884 bool parseDirectiveCFISignalFrame(); 885 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc); 886 887 // macro directives 888 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc); 889 bool parseDirectiveExitMacro(StringRef Directive); 890 bool parseDirectiveEndMacro(StringRef Directive); 891 bool parseDirectiveMacro(StringRef Name, SMLoc NameLoc); 892 893 bool parseDirectiveStruct(StringRef Directive, DirectiveKind DirKind, 894 StringRef Name, SMLoc NameLoc); 895 bool parseDirectiveNestedStruct(StringRef Directive, DirectiveKind DirKind); 896 bool parseDirectiveEnds(StringRef Name, SMLoc NameLoc); 897 bool parseDirectiveNestedEnds(); 898 899 /// Parse a directive like ".globl" which accepts a single symbol (which 900 /// should be a label or an external). 901 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr); 902 903 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm" 904 905 bool parseDirectiveComment(SMLoc DirectiveLoc); // "comment" 906 907 bool parseDirectiveInclude(); // "include" 908 909 // "if" or "ife" 910 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 911 // "ifb" or "ifnb", depending on ExpectBlank. 912 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank); 913 // "ifidn", "ifdif", "ifidni", or "ifdifi", depending on ExpectEqual and 914 // CaseInsensitive. 915 bool parseDirectiveIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 916 bool CaseInsensitive); 917 // "ifdef" or "ifndef", depending on expect_defined 918 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined); 919 // "elseif" or "elseife" 920 bool parseDirectiveElseIf(SMLoc DirectiveLoc, DirectiveKind DirKind); 921 // "elseifb" or "elseifnb", depending on ExpectBlank. 922 bool parseDirectiveElseIfb(SMLoc DirectiveLoc, bool ExpectBlank); 923 // ".elseifdef" or ".elseifndef", depending on expect_defined 924 bool parseDirectiveElseIfdef(SMLoc DirectiveLoc, bool expect_defined); 925 // "elseifidn", "elseifdif", "elseifidni", or "elseifdifi", depending on 926 // ExpectEqual and CaseInsensitive. 927 bool parseDirectiveElseIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 928 bool CaseInsensitive); 929 bool parseDirectiveElse(SMLoc DirectiveLoc); // "else" 930 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // "endif" 931 bool parseEscapedString(std::string &Data) override; 932 bool parseAngleBracketString(std::string &Data) override; 933 934 // Macro-like directives 935 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc); 936 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 937 raw_svector_ostream &OS); 938 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive); 939 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp" 940 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc" 941 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr" 942 943 // "_emit" or "__emit" 944 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info, 945 size_t Len); 946 947 // "align" 948 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info); 949 950 // "end" 951 bool parseDirectiveEnd(SMLoc DirectiveLoc); 952 953 // ".err" 954 bool parseDirectiveError(SMLoc DirectiveLoc); 955 // ".errb" or ".errnb", depending on ExpectBlank. 956 bool parseDirectiveErrorIfb(SMLoc DirectiveLoc, bool ExpectBlank); 957 // ".errdef" or ".errndef", depending on ExpectBlank. 958 bool parseDirectiveErrorIfdef(SMLoc DirectiveLoc, bool ExpectDefined); 959 // ".erridn", ".errdif", ".erridni", or ".errdifi", depending on ExpectEqual 960 // and CaseInsensitive. 961 bool parseDirectiveErrorIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 962 bool CaseInsensitive); 963 // ".erre" or ".errnz", depending on ExpectZero. 964 bool parseDirectiveErrorIfe(SMLoc DirectiveLoc, bool ExpectZero); 965 966 // ".radix" 967 bool parseDirectiveRadix(SMLoc DirectiveLoc); 968 969 // "echo" 970 bool parseDirectiveEcho(); 971 972 void initializeDirectiveKindMap(); 973 void initializeCVDefRangeTypeMap(); 974 }; 975 976 } // end anonymous namespace 977 978 namespace llvm { 979 980 extern MCAsmParserExtension *createCOFFMasmParser(); 981 982 } // end namespace llvm 983 984 enum { DEFAULT_ADDRSPACE = 0 }; 985 986 MasmParser::MasmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out, 987 const MCAsmInfo &MAI, unsigned CB = 0) 988 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM), 989 CurBuffer(CB ? CB : SM.getMainFileID()) { 990 HadError = false; 991 // Save the old handler. 992 SavedDiagHandler = SrcMgr.getDiagHandler(); 993 SavedDiagContext = SrcMgr.getDiagContext(); 994 // Set our own handler which calls the saved handler. 995 SrcMgr.setDiagHandler(DiagHandler, this); 996 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 997 998 // Initialize the platform / file format parser. 999 switch (Ctx.getObjectFileInfo()->getObjectFileType()) { 1000 case MCObjectFileInfo::IsCOFF: 1001 PlatformParser.reset(createCOFFMasmParser()); 1002 break; 1003 default: 1004 report_fatal_error("llvm-ml currently supports only COFF output."); 1005 break; 1006 } 1007 1008 initializeDirectiveKindMap(); 1009 PlatformParser->Initialize(*this); 1010 initializeCVDefRangeTypeMap(); 1011 1012 NumOfMacroInstantiations = 0; 1013 } 1014 1015 MasmParser::~MasmParser() { 1016 assert((HadError || ActiveMacros.empty()) && 1017 "Unexpected active macro instantiation!"); 1018 1019 // Restore the saved diagnostics handler and context for use during 1020 // finalization. 1021 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext); 1022 } 1023 1024 void MasmParser::printMacroInstantiations() { 1025 // Print the active macro instantiation stack. 1026 for (std::vector<MacroInstantiation *>::const_reverse_iterator 1027 it = ActiveMacros.rbegin(), 1028 ie = ActiveMacros.rend(); 1029 it != ie; ++it) 1030 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note, 1031 "while in macro instantiation"); 1032 } 1033 1034 void MasmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) { 1035 printPendingErrors(); 1036 printMessage(L, SourceMgr::DK_Note, Msg, Range); 1037 printMacroInstantiations(); 1038 } 1039 1040 bool MasmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) { 1041 if (getTargetParser().getTargetOptions().MCNoWarn) 1042 return false; 1043 if (getTargetParser().getTargetOptions().MCFatalWarnings) 1044 return Error(L, Msg, Range); 1045 printMessage(L, SourceMgr::DK_Warning, Msg, Range); 1046 printMacroInstantiations(); 1047 return false; 1048 } 1049 1050 bool MasmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) { 1051 HadError = true; 1052 printMessage(L, SourceMgr::DK_Error, Msg, Range); 1053 printMacroInstantiations(); 1054 return true; 1055 } 1056 1057 bool MasmParser::enterIncludeFile(const std::string &Filename) { 1058 std::string IncludedFile; 1059 unsigned NewBuf = 1060 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile); 1061 if (!NewBuf) 1062 return true; 1063 1064 CurBuffer = NewBuf; 1065 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 1066 return false; 1067 } 1068 1069 void MasmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) { 1070 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc); 1071 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), 1072 Loc.getPointer()); 1073 } 1074 1075 const AsmToken &MasmParser::Lex() { 1076 if (Lexer.getTok().is(AsmToken::Error)) 1077 Error(Lexer.getErrLoc(), Lexer.getErr()); 1078 1079 // if it's a end of statement with a comment in it 1080 if (getTok().is(AsmToken::EndOfStatement)) { 1081 // if this is a line comment output it. 1082 if (!getTok().getString().empty() && getTok().getString().front() != '\n' && 1083 getTok().getString().front() != '\r' && MAI.preserveAsmComments()) 1084 Out.addExplicitComment(Twine(getTok().getString())); 1085 } 1086 1087 const AsmToken *tok = &Lexer.Lex(); 1088 1089 while (tok->is(AsmToken::Identifier)) { 1090 auto it = Variables.find(tok->getIdentifier()); 1091 if (it != Variables.end() && it->second.IsText) { 1092 std::unique_ptr<MemoryBuffer> Instantiation = 1093 MemoryBuffer::getMemBufferCopy(it->second.TextValue, 1094 "<instantiation>"); 1095 1096 // Jump to the macro instantiation and prime the lexer. 1097 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), 1098 getTok().getEndLoc()); 1099 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(), nullptr, 1100 /*EndStatementAtEOF=*/false); 1101 tok = &Lexer.Lex(); 1102 } else { 1103 break; 1104 } 1105 } 1106 1107 // Parse comments here to be deferred until end of next statement. 1108 while (tok->is(AsmToken::Comment)) { 1109 if (MAI.preserveAsmComments()) 1110 Out.addExplicitComment(Twine(tok->getString())); 1111 tok = &Lexer.Lex(); 1112 } 1113 1114 // Recognize and bypass line continuations. 1115 while (tok->is(AsmToken::BackSlash) && 1116 Lexer.peekTok().is(AsmToken::EndOfStatement)) { 1117 // Eat both the backslash and the end of statement. 1118 Lexer.Lex(); 1119 tok = &Lexer.Lex(); 1120 } 1121 1122 if (tok->is(AsmToken::Eof)) { 1123 // If this is the end of an included file, pop the parent file off the 1124 // include stack. 1125 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); 1126 if (ParentIncludeLoc != SMLoc()) { 1127 jumpToLoc(ParentIncludeLoc); 1128 return Lex(); 1129 } 1130 } 1131 1132 return *tok; 1133 } 1134 1135 bool MasmParser::enabledGenDwarfForAssembly() { 1136 // Check whether the user specified -g. 1137 if (!getContext().getGenDwarfForAssembly()) 1138 return false; 1139 // If we haven't encountered any .file directives (which would imply that 1140 // the assembler source was produced with debug info already) then emit one 1141 // describing the assembler source file itself. 1142 if (getContext().getGenDwarfFileNumber() == 0) { 1143 // Use the first #line directive for this, if any. It's preprocessed, so 1144 // there is no checksum, and of course no source directive. 1145 if (!FirstCppHashFilename.empty()) 1146 getContext().setMCLineTableRootFile(/*CUID=*/0, 1147 getContext().getCompilationDir(), 1148 FirstCppHashFilename, 1149 /*Cksum=*/None, /*Source=*/None); 1150 const MCDwarfFile &RootFile = 1151 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile(); 1152 getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective( 1153 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name, 1154 RootFile.Checksum, RootFile.Source)); 1155 } 1156 return true; 1157 } 1158 1159 bool MasmParser::Run(bool NoInitialTextSection, bool NoFinalize) { 1160 // Create the initial section, if requested. 1161 if (!NoInitialTextSection) 1162 Out.InitSections(false); 1163 1164 // Prime the lexer. 1165 Lex(); 1166 1167 HadError = false; 1168 AsmCond StartingCondState = TheCondState; 1169 SmallVector<AsmRewrite, 4> AsmStrRewrites; 1170 1171 // If we are generating dwarf for assembly source files save the initial text 1172 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't 1173 // emitting any actual debug info yet and haven't had a chance to parse any 1174 // embedded .file directives.) 1175 if (getContext().getGenDwarfForAssembly()) { 1176 MCSection *Sec = getStreamer().getCurrentSectionOnly(); 1177 if (!Sec->getBeginSymbol()) { 1178 MCSymbol *SectionStartSym = getContext().createTempSymbol(); 1179 getStreamer().emitLabel(SectionStartSym); 1180 Sec->setBeginSymbol(SectionStartSym); 1181 } 1182 bool InsertResult = getContext().addGenDwarfSection(Sec); 1183 assert(InsertResult && ".text section should not have debug info yet"); 1184 (void)InsertResult; 1185 } 1186 1187 // While we have input, parse each statement. 1188 while (Lexer.isNot(AsmToken::Eof)) { 1189 ParseStatementInfo Info(&AsmStrRewrites); 1190 bool Parsed = parseStatement(Info, nullptr); 1191 1192 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error 1193 // for printing ErrMsg via Lex() only if no (presumably better) parser error 1194 // exists. 1195 if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) { 1196 Lex(); 1197 } 1198 1199 // parseStatement returned true so may need to emit an error. 1200 printPendingErrors(); 1201 1202 // Skipping to the next line if needed. 1203 if (Parsed && !getLexer().isAtStartOfStatement()) 1204 eatToEndOfStatement(); 1205 } 1206 1207 getTargetParser().onEndOfFile(); 1208 printPendingErrors(); 1209 1210 // All errors should have been emitted. 1211 assert(!hasPendingError() && "unexpected error from parseStatement"); 1212 1213 getTargetParser().flushPendingInstructions(getStreamer()); 1214 1215 if (TheCondState.TheCond != StartingCondState.TheCond || 1216 TheCondState.Ignore != StartingCondState.Ignore) 1217 printError(getTok().getLoc(), "unmatched .ifs or .elses"); 1218 // Check to see there are no empty DwarfFile slots. 1219 const auto &LineTables = getContext().getMCDwarfLineTables(); 1220 if (!LineTables.empty()) { 1221 unsigned Index = 0; 1222 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) { 1223 if (File.Name.empty() && Index != 0) 1224 printError(getTok().getLoc(), "unassigned file number: " + 1225 Twine(Index) + 1226 " for .file directives"); 1227 ++Index; 1228 } 1229 } 1230 1231 // Check to see that all assembler local symbols were actually defined. 1232 // Targets that don't do subsections via symbols may not want this, though, 1233 // so conservatively exclude them. Only do this if we're finalizing, though, 1234 // as otherwise we won't necessarilly have seen everything yet. 1235 if (!NoFinalize) { 1236 if (MAI.hasSubsectionsViaSymbols()) { 1237 for (const auto &TableEntry : getContext().getSymbols()) { 1238 MCSymbol *Sym = TableEntry.getValue(); 1239 // Variable symbols may not be marked as defined, so check those 1240 // explicitly. If we know it's a variable, we have a definition for 1241 // the purposes of this check. 1242 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) 1243 // FIXME: We would really like to refer back to where the symbol was 1244 // first referenced for a source location. We need to add something 1245 // to track that. Currently, we just point to the end of the file. 1246 printError(getTok().getLoc(), "assembler local symbol '" + 1247 Sym->getName() + "' not defined"); 1248 } 1249 } 1250 1251 // Temporary symbols like the ones for directional jumps don't go in the 1252 // symbol table. They also need to be diagnosed in all (final) cases. 1253 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) { 1254 if (std::get<2>(LocSym)->isUndefined()) { 1255 // Reset the state of any "# line file" directives we've seen to the 1256 // context as it was at the diagnostic site. 1257 CppHashInfo = std::get<1>(LocSym); 1258 printError(std::get<0>(LocSym), "directional label undefined"); 1259 } 1260 } 1261 } 1262 1263 // Finalize the output stream if there are no errors and if the client wants 1264 // us to. 1265 if (!HadError && !NoFinalize) 1266 Out.Finish(); 1267 1268 return HadError || getContext().hadError(); 1269 } 1270 1271 bool MasmParser::checkForValidSection() { 1272 if (!ParsingMSInlineAsm && !getStreamer().getCurrentSectionOnly()) { 1273 Out.InitSections(false); 1274 return Error(getTok().getLoc(), 1275 "expected section directive before assembly directive"); 1276 } 1277 return false; 1278 } 1279 1280 /// Throw away the rest of the line for testing purposes. 1281 void MasmParser::eatToEndOfStatement() { 1282 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 1283 Lexer.Lex(); 1284 1285 // Eat EOL. 1286 if (Lexer.is(AsmToken::EndOfStatement)) 1287 Lexer.Lex(); 1288 } 1289 1290 StringRef MasmParser::parseStringToEndOfStatement() { 1291 const char *Start = getTok().getLoc().getPointer(); 1292 1293 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) 1294 Lexer.Lex(); 1295 1296 const char *End = getTok().getLoc().getPointer(); 1297 return StringRef(Start, End - Start); 1298 } 1299 1300 /// Parse a paren expression and return it. 1301 /// NOTE: This assumes the leading '(' has already been consumed. 1302 /// 1303 /// parenexpr ::= expr) 1304 /// 1305 bool MasmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1306 if (parseExpression(Res)) 1307 return true; 1308 if (Lexer.isNot(AsmToken::RParen)) 1309 return TokError("expected ')' in parentheses expression"); 1310 EndLoc = Lexer.getTok().getEndLoc(); 1311 Lex(); 1312 return false; 1313 } 1314 1315 /// Parse a bracket expression and return it. 1316 /// NOTE: This assumes the leading '[' has already been consumed. 1317 /// 1318 /// bracketexpr ::= expr] 1319 /// 1320 bool MasmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) { 1321 if (parseExpression(Res)) 1322 return true; 1323 EndLoc = getTok().getEndLoc(); 1324 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression")) 1325 return true; 1326 return false; 1327 } 1328 1329 /// Parse a primary expression and return it. 1330 /// primaryexpr ::= (parenexpr 1331 /// primaryexpr ::= symbol 1332 /// primaryexpr ::= number 1333 /// primaryexpr ::= '.' 1334 /// primaryexpr ::= ~,+,-,'not' primaryexpr 1335 /// primaryexpr ::= string 1336 /// (a string is interpreted as a 64-bit number in big-endian base-256) 1337 bool MasmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc, 1338 AsmTypeInfo *TypeInfo) { 1339 SMLoc FirstTokenLoc = getLexer().getLoc(); 1340 AsmToken::TokenKind FirstTokenKind = Lexer.getKind(); 1341 switch (FirstTokenKind) { 1342 default: 1343 return TokError("unknown token in expression"); 1344 // If we have an error assume that we've already handled it. 1345 case AsmToken::Error: 1346 return true; 1347 case AsmToken::Exclaim: 1348 Lex(); // Eat the operator. 1349 if (parsePrimaryExpr(Res, EndLoc, nullptr)) 1350 return true; 1351 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc); 1352 return false; 1353 case AsmToken::Dollar: 1354 case AsmToken::At: 1355 case AsmToken::Identifier: { 1356 StringRef Identifier; 1357 if (parseIdentifier(Identifier)) { 1358 // We may have failed but $ may be a valid token. 1359 if (getTok().is(AsmToken::Dollar)) { 1360 if (Lexer.getMAI().getDollarIsPC()) { 1361 Lex(); 1362 // This is a '$' reference, which references the current PC. Emit a 1363 // temporary label to the streamer and refer to it. 1364 MCSymbol *Sym = Ctx.createTempSymbol(); 1365 Out.emitLabel(Sym); 1366 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, 1367 getContext()); 1368 EndLoc = FirstTokenLoc; 1369 return false; 1370 } 1371 return Error(FirstTokenLoc, "invalid token in expression"); 1372 } 1373 } 1374 // Parse named bitwise negation. 1375 if (Identifier.equals_lower("not")) { 1376 if (parsePrimaryExpr(Res, EndLoc, nullptr)) 1377 return true; 1378 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc); 1379 return false; 1380 } 1381 // Parse symbol variant. 1382 std::pair<StringRef, StringRef> Split; 1383 if (!MAI.useParensForSymbolVariant()) { 1384 if (FirstTokenKind == AsmToken::String) { 1385 if (Lexer.is(AsmToken::At)) { 1386 Lex(); // eat @ 1387 SMLoc AtLoc = getLexer().getLoc(); 1388 StringRef VName; 1389 if (parseIdentifier(VName)) 1390 return Error(AtLoc, "expected symbol variant after '@'"); 1391 1392 Split = std::make_pair(Identifier, VName); 1393 } 1394 } else { 1395 Split = Identifier.split('@'); 1396 } 1397 } else if (Lexer.is(AsmToken::LParen)) { 1398 Lex(); // eat '('. 1399 StringRef VName; 1400 parseIdentifier(VName); 1401 // eat ')'. 1402 if (parseToken(AsmToken::RParen, 1403 "unexpected token in variant, expected ')'")) 1404 return true; 1405 Split = std::make_pair(Identifier, VName); 1406 } 1407 1408 EndLoc = SMLoc::getFromPointer(Identifier.end()); 1409 1410 // This is a symbol reference. 1411 StringRef SymbolName = Identifier; 1412 if (SymbolName.empty()) 1413 return Error(getLexer().getLoc(), "expected a symbol reference"); 1414 1415 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1416 1417 // Look up the symbol variant if used. 1418 if (!Split.second.empty()) { 1419 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1420 if (Variant != MCSymbolRefExpr::VK_Invalid) { 1421 SymbolName = Split.first; 1422 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) { 1423 Variant = MCSymbolRefExpr::VK_None; 1424 } else { 1425 return Error(SMLoc::getFromPointer(Split.second.begin()), 1426 "invalid variant '" + Split.second + "'"); 1427 } 1428 } 1429 1430 // Find the field offset if used. 1431 AsmFieldInfo Info; 1432 Split = SymbolName.split('.'); 1433 if (Split.second.empty()) { 1434 } else { 1435 SymbolName = Split.first; 1436 if (lookUpField(SymbolName, Split.second, Info)) { 1437 std::pair<StringRef, StringRef> BaseMember = Split.second.split('.'); 1438 StringRef Base = BaseMember.first, Member = BaseMember.second; 1439 lookUpField(Base, Member, Info); 1440 } else if (Structs.count(SymbolName.lower())) { 1441 // This is actually a reference to a field offset. 1442 Res = MCConstantExpr::create(Info.Offset, getContext()); 1443 return false; 1444 } 1445 } 1446 1447 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName); 1448 if (!Sym) 1449 Sym = getContext().getOrCreateSymbol(SymbolName); 1450 1451 // If this is an absolute variable reference, substitute it now to preserve 1452 // semantics in the face of reassignment. 1453 if (Sym->isVariable()) { 1454 auto V = Sym->getVariableValue(/*SetUsed*/ false); 1455 bool DoInline = isa<MCConstantExpr>(V) && !Variant; 1456 if (auto TV = dyn_cast<MCTargetExpr>(V)) 1457 DoInline = TV->inlineAssignedExpr(); 1458 if (DoInline) { 1459 if (Variant) 1460 return Error(EndLoc, "unexpected modifier on variable reference"); 1461 Res = Sym->getVariableValue(/*SetUsed*/ false); 1462 return false; 1463 } 1464 } 1465 1466 // Otherwise create a symbol ref. 1467 const MCExpr *SymRef = 1468 MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc); 1469 if (Info.Offset) { 1470 Res = MCBinaryExpr::create( 1471 MCBinaryExpr::Add, SymRef, 1472 MCConstantExpr::create(Info.Offset, getContext()), getContext()); 1473 } else { 1474 Res = SymRef; 1475 } 1476 if (TypeInfo) { 1477 if (Info.Type.Name.empty()) { 1478 auto TypeIt = KnownType.find(Identifier.lower()); 1479 if (TypeIt != KnownType.end()) { 1480 Info.Type = TypeIt->second; 1481 } 1482 } 1483 1484 *TypeInfo = Info.Type; 1485 } 1486 return false; 1487 } 1488 case AsmToken::BigNum: 1489 return TokError("literal value out of range for directive"); 1490 case AsmToken::Integer: { 1491 SMLoc Loc = getTok().getLoc(); 1492 int64_t IntVal = getTok().getIntVal(); 1493 Res = MCConstantExpr::create(IntVal, getContext()); 1494 EndLoc = Lexer.getTok().getEndLoc(); 1495 Lex(); // Eat token. 1496 // Look for 'b' or 'f' following an Integer as a directional label. 1497 if (Lexer.getKind() == AsmToken::Identifier) { 1498 StringRef IDVal = getTok().getString(); 1499 // Look up the symbol variant if used. 1500 std::pair<StringRef, StringRef> Split = IDVal.split('@'); 1501 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1502 if (Split.first.size() != IDVal.size()) { 1503 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second); 1504 if (Variant == MCSymbolRefExpr::VK_Invalid) 1505 return TokError("invalid variant '" + Split.second + "'"); 1506 IDVal = Split.first; 1507 } 1508 if (IDVal == "f" || IDVal == "b") { 1509 MCSymbol *Sym = 1510 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b"); 1511 Res = MCSymbolRefExpr::create(Sym, Variant, getContext()); 1512 if (IDVal == "b" && Sym->isUndefined()) 1513 return Error(Loc, "directional label undefined"); 1514 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym)); 1515 EndLoc = Lexer.getTok().getEndLoc(); 1516 Lex(); // Eat identifier. 1517 } 1518 } 1519 return false; 1520 } 1521 case AsmToken::String: { 1522 // MASM strings (used as constants) are interpreted as big-endian base-256. 1523 SMLoc ValueLoc = getTok().getLoc(); 1524 std::string Value; 1525 if (parseEscapedString(Value)) 1526 return true; 1527 if (Value.size() > 8) 1528 return Error(ValueLoc, "literal value out of range"); 1529 uint64_t IntValue = 0; 1530 for (const unsigned char CharVal : Value) 1531 IntValue = (IntValue << 8) | CharVal; 1532 Res = MCConstantExpr::create(IntValue, getContext()); 1533 return false; 1534 } 1535 case AsmToken::Real: { 1536 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString()); 1537 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue(); 1538 Res = MCConstantExpr::create(IntVal, getContext()); 1539 EndLoc = Lexer.getTok().getEndLoc(); 1540 Lex(); // Eat token. 1541 return false; 1542 } 1543 case AsmToken::Dot: { 1544 // This is a '.' reference, which references the current PC. Emit a 1545 // temporary label to the streamer and refer to it. 1546 MCSymbol *Sym = Ctx.createTempSymbol(); 1547 Out.emitLabel(Sym); 1548 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); 1549 EndLoc = Lexer.getTok().getEndLoc(); 1550 Lex(); // Eat identifier. 1551 return false; 1552 } 1553 case AsmToken::LParen: 1554 Lex(); // Eat the '('. 1555 return parseParenExpr(Res, EndLoc); 1556 case AsmToken::LBrac: 1557 if (!PlatformParser->HasBracketExpressions()) 1558 return TokError("brackets expression not supported on this target"); 1559 Lex(); // Eat the '['. 1560 return parseBracketExpr(Res, EndLoc); 1561 case AsmToken::Minus: 1562 Lex(); // Eat the operator. 1563 if (parsePrimaryExpr(Res, EndLoc, nullptr)) 1564 return true; 1565 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc); 1566 return false; 1567 case AsmToken::Plus: 1568 Lex(); // Eat the operator. 1569 if (parsePrimaryExpr(Res, EndLoc, nullptr)) 1570 return true; 1571 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc); 1572 return false; 1573 case AsmToken::Tilde: 1574 Lex(); // Eat the operator. 1575 if (parsePrimaryExpr(Res, EndLoc, nullptr)) 1576 return true; 1577 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc); 1578 return false; 1579 // MIPS unary expression operators. The lexer won't generate these tokens if 1580 // MCAsmInfo::HasMipsExpressions is false for the target. 1581 case AsmToken::PercentCall16: 1582 case AsmToken::PercentCall_Hi: 1583 case AsmToken::PercentCall_Lo: 1584 case AsmToken::PercentDtprel_Hi: 1585 case AsmToken::PercentDtprel_Lo: 1586 case AsmToken::PercentGot: 1587 case AsmToken::PercentGot_Disp: 1588 case AsmToken::PercentGot_Hi: 1589 case AsmToken::PercentGot_Lo: 1590 case AsmToken::PercentGot_Ofst: 1591 case AsmToken::PercentGot_Page: 1592 case AsmToken::PercentGottprel: 1593 case AsmToken::PercentGp_Rel: 1594 case AsmToken::PercentHi: 1595 case AsmToken::PercentHigher: 1596 case AsmToken::PercentHighest: 1597 case AsmToken::PercentLo: 1598 case AsmToken::PercentNeg: 1599 case AsmToken::PercentPcrel_Hi: 1600 case AsmToken::PercentPcrel_Lo: 1601 case AsmToken::PercentTlsgd: 1602 case AsmToken::PercentTlsldm: 1603 case AsmToken::PercentTprel_Hi: 1604 case AsmToken::PercentTprel_Lo: 1605 Lex(); // Eat the operator. 1606 if (Lexer.isNot(AsmToken::LParen)) 1607 return TokError("expected '(' after operator"); 1608 Lex(); // Eat the operator. 1609 if (parseExpression(Res, EndLoc)) 1610 return true; 1611 if (Lexer.isNot(AsmToken::RParen)) 1612 return TokError("expected ')'"); 1613 Lex(); // Eat the operator. 1614 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx); 1615 return !Res; 1616 } 1617 } 1618 1619 bool MasmParser::parseExpression(const MCExpr *&Res) { 1620 SMLoc EndLoc; 1621 return parseExpression(Res, EndLoc); 1622 } 1623 1624 /// This function checks if the next token is <string> type or arithmetic. 1625 /// string that begin with character '<' must end with character '>'. 1626 /// otherwise it is arithmetics. 1627 /// If the function returns a 'true' value, 1628 /// the End argument will be filled with the last location pointed to the '>' 1629 /// character. 1630 static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) { 1631 assert((StrLoc.getPointer() != nullptr) && 1632 "Argument to the function cannot be a NULL value"); 1633 const char *CharPtr = StrLoc.getPointer(); 1634 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') && 1635 (*CharPtr != '\0')) { 1636 if (*CharPtr == '!') 1637 CharPtr++; 1638 CharPtr++; 1639 } 1640 if (*CharPtr == '>') { 1641 EndLoc = StrLoc.getFromPointer(CharPtr + 1); 1642 return true; 1643 } 1644 return false; 1645 } 1646 1647 /// creating a string without the escape characters '!'. 1648 static std::string angleBracketString(StringRef BracketContents) { 1649 std::string Res; 1650 for (size_t Pos = 0; Pos < BracketContents.size(); Pos++) { 1651 if (BracketContents[Pos] == '!') 1652 Pos++; 1653 Res += BracketContents[Pos]; 1654 } 1655 return Res; 1656 } 1657 1658 /// Parse an expression and return it. 1659 /// 1660 /// expr ::= expr &&,|| expr -> lowest. 1661 /// expr ::= expr |,^,&,! expr 1662 /// expr ::= expr ==,!=,<>,<,<=,>,>= expr 1663 /// expr ::= expr <<,>> expr 1664 /// expr ::= expr +,- expr 1665 /// expr ::= expr *,/,% expr -> highest. 1666 /// expr ::= primaryexpr 1667 /// 1668 bool MasmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1669 // Parse the expression. 1670 Res = nullptr; 1671 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) || 1672 parseBinOpRHS(1, Res, EndLoc)) 1673 return true; 1674 1675 // Try to constant fold it up front, if possible. Do not exploit 1676 // assembler here. 1677 int64_t Value; 1678 if (Res->evaluateAsAbsolute(Value)) 1679 Res = MCConstantExpr::create(Value, getContext()); 1680 1681 return false; 1682 } 1683 1684 bool MasmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) { 1685 Res = nullptr; 1686 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc); 1687 } 1688 1689 bool MasmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res, 1690 SMLoc &EndLoc) { 1691 if (parseParenExpr(Res, EndLoc)) 1692 return true; 1693 1694 for (; ParenDepth > 0; --ParenDepth) { 1695 if (parseBinOpRHS(1, Res, EndLoc)) 1696 return true; 1697 1698 // We don't Lex() the last RParen. 1699 // This is the same behavior as parseParenExpression(). 1700 if (ParenDepth - 1 > 0) { 1701 EndLoc = getTok().getEndLoc(); 1702 if (parseToken(AsmToken::RParen, 1703 "expected ')' in parentheses expression")) 1704 return true; 1705 } 1706 } 1707 return false; 1708 } 1709 1710 bool MasmParser::parseAbsoluteExpression(int64_t &Res) { 1711 const MCExpr *Expr; 1712 1713 SMLoc StartLoc = Lexer.getLoc(); 1714 if (parseExpression(Expr)) 1715 return true; 1716 1717 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr())) 1718 return Error(StartLoc, "expected absolute expression"); 1719 1720 return false; 1721 } 1722 1723 static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K, 1724 MCBinaryExpr::Opcode &Kind, 1725 bool ShouldUseLogicalShr, 1726 bool EndExpressionAtGreater) { 1727 switch (K) { 1728 default: 1729 return 0; // not a binop. 1730 1731 // Lowest Precedence: &&, || 1732 case AsmToken::AmpAmp: 1733 Kind = MCBinaryExpr::LAnd; 1734 return 2; 1735 case AsmToken::PipePipe: 1736 Kind = MCBinaryExpr::LOr; 1737 return 1; 1738 1739 // Low Precedence: ==, !=, <>, <, <=, >, >= 1740 case AsmToken::EqualEqual: 1741 Kind = MCBinaryExpr::EQ; 1742 return 3; 1743 case AsmToken::ExclaimEqual: 1744 case AsmToken::LessGreater: 1745 Kind = MCBinaryExpr::NE; 1746 return 3; 1747 case AsmToken::Less: 1748 Kind = MCBinaryExpr::LT; 1749 return 3; 1750 case AsmToken::LessEqual: 1751 Kind = MCBinaryExpr::LTE; 1752 return 3; 1753 case AsmToken::Greater: 1754 if (EndExpressionAtGreater) 1755 return 0; 1756 Kind = MCBinaryExpr::GT; 1757 return 3; 1758 case AsmToken::GreaterEqual: 1759 Kind = MCBinaryExpr::GTE; 1760 return 3; 1761 1762 // Low Intermediate Precedence: +, - 1763 case AsmToken::Plus: 1764 Kind = MCBinaryExpr::Add; 1765 return 4; 1766 case AsmToken::Minus: 1767 Kind = MCBinaryExpr::Sub; 1768 return 4; 1769 1770 // High Intermediate Precedence: |, &, ^ 1771 case AsmToken::Pipe: 1772 Kind = MCBinaryExpr::Or; 1773 return 5; 1774 case AsmToken::Caret: 1775 Kind = MCBinaryExpr::Xor; 1776 return 5; 1777 case AsmToken::Amp: 1778 Kind = MCBinaryExpr::And; 1779 return 5; 1780 1781 // Highest Precedence: *, /, %, <<, >> 1782 case AsmToken::Star: 1783 Kind = MCBinaryExpr::Mul; 1784 return 6; 1785 case AsmToken::Slash: 1786 Kind = MCBinaryExpr::Div; 1787 return 6; 1788 case AsmToken::Percent: 1789 Kind = MCBinaryExpr::Mod; 1790 return 6; 1791 case AsmToken::LessLess: 1792 Kind = MCBinaryExpr::Shl; 1793 return 6; 1794 case AsmToken::GreaterGreater: 1795 if (EndExpressionAtGreater) 1796 return 0; 1797 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr; 1798 return 6; 1799 } 1800 } 1801 1802 unsigned MasmParser::getBinOpPrecedence(AsmToken::TokenKind K, 1803 MCBinaryExpr::Opcode &Kind) { 1804 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr(); 1805 return getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr, 1806 AngleBracketDepth > 0); 1807 } 1808 1809 /// Parse all binary operators with precedence >= 'Precedence'. 1810 /// Res contains the LHS of the expression on input. 1811 bool MasmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, 1812 SMLoc &EndLoc) { 1813 SMLoc StartLoc = Lexer.getLoc(); 1814 while (true) { 1815 AsmToken::TokenKind TokKind = Lexer.getKind(); 1816 if (Lexer.getKind() == AsmToken::Identifier) { 1817 StringRef Identifier = Lexer.getTok().getString(); 1818 if (Identifier.equals_lower("and")) 1819 TokKind = AsmToken::Amp; 1820 else if (Identifier.equals_lower("not")) 1821 TokKind = AsmToken::Exclaim; 1822 else if (Identifier.equals_lower("or")) 1823 TokKind = AsmToken::Pipe; 1824 } 1825 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add; 1826 unsigned TokPrec = getBinOpPrecedence(TokKind, Kind); 1827 1828 // If the next token is lower precedence than we are allowed to eat, return 1829 // successfully with what we ate already. 1830 if (TokPrec < Precedence) 1831 return false; 1832 1833 Lex(); 1834 1835 // Eat the next primary expression. 1836 const MCExpr *RHS; 1837 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc)) 1838 return true; 1839 1840 // If BinOp binds less tightly with RHS than the operator after RHS, let 1841 // the pending operator take RHS as its LHS. 1842 MCBinaryExpr::Opcode Dummy; 1843 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy); 1844 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc)) 1845 return true; 1846 1847 // Merge LHS and RHS according to operator. 1848 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc); 1849 } 1850 } 1851 1852 /// ParseStatement: 1853 /// ::= EndOfStatement 1854 /// ::= Label* Directive ...Operands... EndOfStatement 1855 /// ::= Label* Identifier OperandList* EndOfStatement 1856 bool MasmParser::parseStatement(ParseStatementInfo &Info, 1857 MCAsmParserSemaCallback *SI) { 1858 assert(!hasPendingError() && "parseStatement started with pending error"); 1859 // Eat initial spaces and comments. 1860 while (Lexer.is(AsmToken::Space)) 1861 Lex(); 1862 if (Lexer.is(AsmToken::EndOfStatement)) { 1863 // If this is a line comment we can drop it safely. 1864 if (getTok().getString().empty() || getTok().getString().front() == '\r' || 1865 getTok().getString().front() == '\n') 1866 Out.AddBlankLine(); 1867 Lex(); 1868 return false; 1869 } 1870 // Statements always start with an identifier, unless we're dealing with a 1871 // processor directive (.386, .686, etc.) that lexes as a real. 1872 AsmToken ID = getTok(); 1873 SMLoc IDLoc = ID.getLoc(); 1874 StringRef IDVal; 1875 int64_t LocalLabelVal = -1; 1876 if (Lexer.is(AsmToken::HashDirective)) 1877 return parseCppHashLineFilenameComment(IDLoc); 1878 // Allow an integer followed by a ':' as a directional local label. 1879 if (Lexer.is(AsmToken::Integer)) { 1880 LocalLabelVal = getTok().getIntVal(); 1881 if (LocalLabelVal < 0) { 1882 if (!TheCondState.Ignore) { 1883 Lex(); // always eat a token 1884 return Error(IDLoc, "unexpected token at start of statement"); 1885 } 1886 IDVal = ""; 1887 } else { 1888 IDVal = getTok().getString(); 1889 Lex(); // Consume the integer token to be used as an identifier token. 1890 if (Lexer.getKind() != AsmToken::Colon) { 1891 if (!TheCondState.Ignore) { 1892 Lex(); // always eat a token 1893 return Error(IDLoc, "unexpected token at start of statement"); 1894 } 1895 } 1896 } 1897 } else if (Lexer.is(AsmToken::Dot)) { 1898 // Treat '.' as a valid identifier in this context. 1899 Lex(); 1900 IDVal = "."; 1901 } else if (Lexer.is(AsmToken::LCurly)) { 1902 // Treat '{' as a valid identifier in this context. 1903 Lex(); 1904 IDVal = "{"; 1905 1906 } else if (Lexer.is(AsmToken::RCurly)) { 1907 // Treat '}' as a valid identifier in this context. 1908 Lex(); 1909 IDVal = "}"; 1910 } else if (Lexer.is(AsmToken::Star) && 1911 getTargetParser().starIsStartOfStatement()) { 1912 // Accept '*' as a valid start of statement. 1913 Lex(); 1914 IDVal = "*"; 1915 } else if (Lexer.is(AsmToken::Real)) { 1916 // Treat ".<number>" as a valid identifier in this context. 1917 IDVal = getTok().getString(); 1918 Lex(); // always eat a token 1919 if (!IDVal.startswith(".")) 1920 return Error(IDLoc, "unexpected token at start of statement"); 1921 } else if (parseIdentifier(IDVal)) { 1922 if (!TheCondState.Ignore) { 1923 Lex(); // always eat a token 1924 return Error(IDLoc, "unexpected token at start of statement"); 1925 } 1926 IDVal = ""; 1927 } 1928 1929 // Handle conditional assembly here before checking for skipping. We 1930 // have to do this so that .endif isn't skipped in a ".if 0" block for 1931 // example. 1932 StringMap<DirectiveKind>::const_iterator DirKindIt = 1933 DirectiveKindMap.find(IDVal.lower()); 1934 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end()) 1935 ? DK_NO_DIRECTIVE 1936 : DirKindIt->getValue(); 1937 switch (DirKind) { 1938 default: 1939 break; 1940 case DK_IF: 1941 case DK_IFE: 1942 return parseDirectiveIf(IDLoc, DirKind); 1943 case DK_IFB: 1944 return parseDirectiveIfb(IDLoc, true); 1945 case DK_IFNB: 1946 return parseDirectiveIfb(IDLoc, false); 1947 case DK_IFDEF: 1948 return parseDirectiveIfdef(IDLoc, true); 1949 case DK_IFNDEF: 1950 return parseDirectiveIfdef(IDLoc, false); 1951 case DK_IFDIF: 1952 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/false, 1953 /*CaseInsensitive=*/false); 1954 case DK_IFDIFI: 1955 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/false, 1956 /*CaseInsensitive=*/true); 1957 case DK_IFIDN: 1958 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/true, 1959 /*CaseInsensitive=*/false); 1960 case DK_IFIDNI: 1961 return parseDirectiveIfidn(IDLoc, /*ExpectEqual=*/true, 1962 /*CaseInsensitive=*/true); 1963 case DK_ELSEIF: 1964 case DK_ELSEIFE: 1965 return parseDirectiveElseIf(IDLoc, DirKind); 1966 case DK_ELSEIFB: 1967 return parseDirectiveElseIfb(IDLoc, true); 1968 case DK_ELSEIFNB: 1969 return parseDirectiveElseIfb(IDLoc, false); 1970 case DK_ELSEIFDEF: 1971 return parseDirectiveElseIfdef(IDLoc, true); 1972 case DK_ELSEIFNDEF: 1973 return parseDirectiveElseIfdef(IDLoc, false); 1974 case DK_ELSEIFDIF: 1975 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/false, 1976 /*CaseInsensitive=*/false); 1977 case DK_ELSEIFDIFI: 1978 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/false, 1979 /*CaseInsensitive=*/true); 1980 case DK_ELSEIFIDN: 1981 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/true, 1982 /*CaseInsensitive=*/false); 1983 case DK_ELSEIFIDNI: 1984 return parseDirectiveElseIfidn(IDLoc, /*ExpectEqual=*/true, 1985 /*CaseInsensitive=*/true); 1986 case DK_ELSE: 1987 return parseDirectiveElse(IDLoc); 1988 case DK_ENDIF: 1989 return parseDirectiveEndIf(IDLoc); 1990 } 1991 1992 // Ignore the statement if in the middle of inactive conditional 1993 // (e.g. ".if 0"). 1994 if (TheCondState.Ignore) { 1995 eatToEndOfStatement(); 1996 return false; 1997 } 1998 1999 // FIXME: Recurse on local labels? 2000 2001 // See what kind of statement we have. 2002 switch (Lexer.getKind()) { 2003 case AsmToken::Colon: { 2004 if (!getTargetParser().isLabel(ID)) 2005 break; 2006 if (checkForValidSection()) 2007 return true; 2008 2009 // identifier ':' -> Label. 2010 Lex(); 2011 2012 // Diagnose attempt to use '.' as a label. 2013 if (IDVal == ".") 2014 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label"); 2015 2016 // Diagnose attempt to use a variable as a label. 2017 // 2018 // FIXME: Diagnostics. Note the location of the definition as a label. 2019 // FIXME: This doesn't diagnose assignment to a symbol which has been 2020 // implicitly marked as external. 2021 MCSymbol *Sym; 2022 if (LocalLabelVal == -1) { 2023 if (ParsingMSInlineAsm && SI) { 2024 StringRef RewrittenLabel = 2025 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true); 2026 assert(!RewrittenLabel.empty() && 2027 "We should have an internal name here."); 2028 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(), 2029 RewrittenLabel); 2030 IDVal = RewrittenLabel; 2031 } 2032 Sym = getContext().getOrCreateSymbol(IDVal); 2033 } else 2034 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal); 2035 // End of Labels should be treated as end of line for lexing 2036 // purposes but that information is not available to the Lexer who 2037 // does not understand Labels. This may cause us to see a Hash 2038 // here instead of a preprocessor line comment. 2039 if (getTok().is(AsmToken::Hash)) { 2040 StringRef CommentStr = parseStringToEndOfStatement(); 2041 Lexer.Lex(); 2042 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr)); 2043 } 2044 2045 // Consume any end of statement token, if present, to avoid spurious 2046 // AddBlankLine calls(). 2047 if (getTok().is(AsmToken::EndOfStatement)) { 2048 Lex(); 2049 } 2050 2051 getTargetParser().doBeforeLabelEmit(Sym); 2052 2053 // Emit the label. 2054 if (!getTargetParser().isParsingMSInlineAsm()) 2055 Out.emitLabel(Sym, IDLoc); 2056 2057 // If we are generating dwarf for assembly source files then gather the 2058 // info to make a dwarf label entry for this label if needed. 2059 if (enabledGenDwarfForAssembly()) 2060 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(), 2061 IDLoc); 2062 2063 getTargetParser().onLabelParsed(Sym); 2064 2065 return false; 2066 } 2067 2068 default: // Normal instruction or directive. 2069 break; 2070 } 2071 2072 // If macros are enabled, check to see if this is a macro instantiation. 2073 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) { 2074 return handleMacroEntry(M, IDLoc); 2075 } 2076 2077 // Otherwise, we have a normal instruction or directive. 2078 2079 if (DirKind != DK_NO_DIRECTIVE) { 2080 // There are several entities interested in parsing directives: 2081 // 2082 // 1. Asm parser extensions. For example, platform-specific parsers 2083 // (like the ELF parser) register themselves as extensions. 2084 // 2. The target-specific assembly parser. Some directives are target 2085 // specific or may potentially behave differently on certain targets. 2086 // 3. The generic directive parser implemented by this class. These are 2087 // all the directives that behave in a target and platform independent 2088 // manner, or at least have a default behavior that's shared between 2089 // all targets and platforms. 2090 2091 getTargetParser().flushPendingInstructions(getStreamer()); 2092 2093 // Special-case handling of structure-end directives at higher priority, 2094 // since ENDS is overloaded as a segment-end directive. 2095 if (IDVal.equals_lower("ends") && StructInProgress.size() > 1 && 2096 getTok().is(AsmToken::EndOfStatement)) { 2097 return parseDirectiveNestedEnds(); 2098 } 2099 2100 // First, check the extension directive map to see if any extension has 2101 // registered itself to parse this directive. 2102 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 2103 ExtensionDirectiveMap.lookup(IDVal.lower()); 2104 if (Handler.first) 2105 return (*Handler.second)(Handler.first, IDVal, IDLoc); 2106 2107 // Next, let the target-specific assembly parser try. 2108 SMLoc StartTokLoc = getTok().getLoc(); 2109 bool TPDirectiveReturn = 2110 ID.is(AsmToken::Identifier) && getTargetParser().ParseDirective(ID); 2111 2112 if (hasPendingError()) 2113 return true; 2114 // Currently the return value should be true if we are 2115 // uninterested but as this is at odds with the standard parsing 2116 // convention (return true = error) we have instances of a parsed 2117 // directive that fails returning true as an error. Catch these 2118 // cases as best as possible errors here. 2119 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc()) 2120 return true; 2121 // Return if we did some parsing or believe we succeeded. 2122 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc()) 2123 return false; 2124 2125 // Finally, if no one else is interested in this directive, it must be 2126 // generic and familiar to this class. 2127 switch (DirKind) { 2128 default: 2129 break; 2130 case DK_ASCII: 2131 return parseDirectiveAscii(IDVal, false); 2132 case DK_ASCIZ: 2133 case DK_STRING: 2134 return parseDirectiveAscii(IDVal, true); 2135 case DK_BYTE: 2136 case DK_SBYTE: 2137 case DK_DB: 2138 return parseDirectiveValue(IDVal, 1); 2139 case DK_WORD: 2140 case DK_SWORD: 2141 case DK_DW: 2142 return parseDirectiveValue(IDVal, 2); 2143 case DK_DWORD: 2144 case DK_SDWORD: 2145 case DK_DD: 2146 return parseDirectiveValue(IDVal, 4); 2147 case DK_FWORD: 2148 case DK_DF: 2149 return parseDirectiveValue(IDVal, 6); 2150 case DK_QWORD: 2151 case DK_SQWORD: 2152 case DK_DQ: 2153 return parseDirectiveValue(IDVal, 8); 2154 case DK_REAL4: 2155 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle(), 4); 2156 case DK_REAL8: 2157 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble(), 8); 2158 case DK_REAL10: 2159 return parseDirectiveRealValue(IDVal, APFloat::x87DoubleExtended(), 10); 2160 case DK_STRUCT: 2161 case DK_UNION: 2162 return parseDirectiveNestedStruct(IDVal, DirKind); 2163 case DK_ENDS: 2164 return parseDirectiveNestedEnds(); 2165 case DK_ALIGN: 2166 return parseDirectiveAlign(); 2167 case DK_ORG: 2168 return parseDirectiveOrg(); 2169 case DK_EXTERN: 2170 eatToEndOfStatement(); // .extern is the default, ignore it. 2171 return false; 2172 case DK_PUBLIC: 2173 return parseDirectiveSymbolAttribute(MCSA_Global); 2174 case DK_COMM: 2175 return parseDirectiveComm(/*IsLocal=*/false); 2176 case DK_COMMENT: 2177 return parseDirectiveComment(IDLoc); 2178 case DK_INCLUDE: 2179 return parseDirectiveInclude(); 2180 case DK_REPT: 2181 return parseDirectiveRept(IDLoc, IDVal); 2182 case DK_IRP: 2183 return parseDirectiveIrp(IDLoc); 2184 case DK_IRPC: 2185 return parseDirectiveIrpc(IDLoc); 2186 case DK_ENDR: 2187 return parseDirectiveEndr(IDLoc); 2188 case DK_FILE: 2189 return parseDirectiveFile(IDLoc); 2190 case DK_LINE: 2191 return parseDirectiveLine(); 2192 case DK_LOC: 2193 return parseDirectiveLoc(); 2194 case DK_STABS: 2195 return parseDirectiveStabs(); 2196 case DK_CV_FILE: 2197 return parseDirectiveCVFile(); 2198 case DK_CV_FUNC_ID: 2199 return parseDirectiveCVFuncId(); 2200 case DK_CV_INLINE_SITE_ID: 2201 return parseDirectiveCVInlineSiteId(); 2202 case DK_CV_LOC: 2203 return parseDirectiveCVLoc(); 2204 case DK_CV_LINETABLE: 2205 return parseDirectiveCVLinetable(); 2206 case DK_CV_INLINE_LINETABLE: 2207 return parseDirectiveCVInlineLinetable(); 2208 case DK_CV_DEF_RANGE: 2209 return parseDirectiveCVDefRange(); 2210 case DK_CV_STRING: 2211 return parseDirectiveCVString(); 2212 case DK_CV_STRINGTABLE: 2213 return parseDirectiveCVStringTable(); 2214 case DK_CV_FILECHECKSUMS: 2215 return parseDirectiveCVFileChecksums(); 2216 case DK_CV_FILECHECKSUM_OFFSET: 2217 return parseDirectiveCVFileChecksumOffset(); 2218 case DK_CV_FPO_DATA: 2219 return parseDirectiveCVFPOData(); 2220 case DK_CFI_SECTIONS: 2221 return parseDirectiveCFISections(); 2222 case DK_CFI_STARTPROC: 2223 return parseDirectiveCFIStartProc(); 2224 case DK_CFI_ENDPROC: 2225 return parseDirectiveCFIEndProc(); 2226 case DK_CFI_DEF_CFA: 2227 return parseDirectiveCFIDefCfa(IDLoc); 2228 case DK_CFI_DEF_CFA_OFFSET: 2229 return parseDirectiveCFIDefCfaOffset(); 2230 case DK_CFI_ADJUST_CFA_OFFSET: 2231 return parseDirectiveCFIAdjustCfaOffset(); 2232 case DK_CFI_DEF_CFA_REGISTER: 2233 return parseDirectiveCFIDefCfaRegister(IDLoc); 2234 case DK_CFI_OFFSET: 2235 return parseDirectiveCFIOffset(IDLoc); 2236 case DK_CFI_REL_OFFSET: 2237 return parseDirectiveCFIRelOffset(IDLoc); 2238 case DK_CFI_PERSONALITY: 2239 return parseDirectiveCFIPersonalityOrLsda(true); 2240 case DK_CFI_LSDA: 2241 return parseDirectiveCFIPersonalityOrLsda(false); 2242 case DK_CFI_REMEMBER_STATE: 2243 return parseDirectiveCFIRememberState(); 2244 case DK_CFI_RESTORE_STATE: 2245 return parseDirectiveCFIRestoreState(); 2246 case DK_CFI_SAME_VALUE: 2247 return parseDirectiveCFISameValue(IDLoc); 2248 case DK_CFI_RESTORE: 2249 return parseDirectiveCFIRestore(IDLoc); 2250 case DK_CFI_ESCAPE: 2251 return parseDirectiveCFIEscape(); 2252 case DK_CFI_RETURN_COLUMN: 2253 return parseDirectiveCFIReturnColumn(IDLoc); 2254 case DK_CFI_SIGNAL_FRAME: 2255 return parseDirectiveCFISignalFrame(); 2256 case DK_CFI_UNDEFINED: 2257 return parseDirectiveCFIUndefined(IDLoc); 2258 case DK_CFI_REGISTER: 2259 return parseDirectiveCFIRegister(IDLoc); 2260 case DK_CFI_WINDOW_SAVE: 2261 return parseDirectiveCFIWindowSave(); 2262 case DK_EXITM: 2263 return parseDirectiveExitMacro(IDVal); 2264 case DK_ENDM: 2265 return parseDirectiveEndMacro(IDVal); 2266 case DK_PURGEM: 2267 return parseDirectivePurgeMacro(IDLoc); 2268 case DK_END: 2269 return parseDirectiveEnd(IDLoc); 2270 case DK_ERR: 2271 return parseDirectiveError(IDLoc); 2272 case DK_ERRB: 2273 return parseDirectiveErrorIfb(IDLoc, true); 2274 case DK_ERRNB: 2275 return parseDirectiveErrorIfb(IDLoc, false); 2276 case DK_ERRDEF: 2277 return parseDirectiveErrorIfdef(IDLoc, true); 2278 case DK_ERRNDEF: 2279 return parseDirectiveErrorIfdef(IDLoc, false); 2280 case DK_ERRDIF: 2281 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/false, 2282 /*CaseInsensitive=*/false); 2283 case DK_ERRDIFI: 2284 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/false, 2285 /*CaseInsensitive=*/true); 2286 case DK_ERRIDN: 2287 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/true, 2288 /*CaseInsensitive=*/false); 2289 case DK_ERRIDNI: 2290 return parseDirectiveErrorIfidn(IDLoc, /*ExpectEqual=*/true, 2291 /*CaseInsensitive=*/true); 2292 case DK_ERRE: 2293 return parseDirectiveErrorIfe(IDLoc, true); 2294 case DK_ERRNZ: 2295 return parseDirectiveErrorIfe(IDLoc, false); 2296 case DK_RADIX: 2297 return parseDirectiveRadix(IDLoc); 2298 case DK_ECHO: 2299 return parseDirectiveEcho(); 2300 } 2301 2302 return Error(IDLoc, "unknown directive"); 2303 } 2304 2305 // We also check if this is allocating memory with user-defined type. 2306 auto IDIt = Structs.find(IDVal.lower()); 2307 if (IDIt != Structs.end()) 2308 return parseDirectiveStructValue(/*Structure=*/IDIt->getValue(), IDVal, 2309 IDLoc); 2310 2311 // Non-conditional Microsoft directives sometimes follow their first argument. 2312 const AsmToken nextTok = getTok(); 2313 const StringRef nextVal = nextTok.getString(); 2314 const SMLoc nextLoc = nextTok.getLoc(); 2315 2316 // There are several entities interested in parsing infix directives: 2317 // 2318 // 1. Asm parser extensions. For example, platform-specific parsers 2319 // (like the ELF parser) register themselves as extensions. 2320 // 2. The generic directive parser implemented by this class. These are 2321 // all the directives that behave in a target and platform independent 2322 // manner, or at least have a default behavior that's shared between 2323 // all targets and platforms. 2324 2325 getTargetParser().flushPendingInstructions(getStreamer()); 2326 2327 // Special-case handling of structure-end directives at higher priority, since 2328 // ENDS is overloaded as a segment-end directive. 2329 if (nextVal.equals_lower("ends") && StructInProgress.size() == 1) { 2330 Lex(); 2331 return parseDirectiveEnds(IDVal, IDLoc); 2332 } 2333 2334 // First, check the extension directive map to see if any extension has 2335 // registered itself to parse this directive. 2336 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler = 2337 ExtensionDirectiveMap.lookup(nextVal.lower()); 2338 if (Handler.first) { 2339 Lex(); 2340 Lexer.UnLex(ID); 2341 return (*Handler.second)(Handler.first, nextVal, nextLoc); 2342 } 2343 2344 // If no one else is interested in this directive, it must be 2345 // generic and familiar to this class. 2346 DirKindIt = DirectiveKindMap.find(nextVal.lower()); 2347 DirKind = (DirKindIt == DirectiveKindMap.end()) 2348 ? DK_NO_DIRECTIVE 2349 : DirKindIt->getValue(); 2350 switch (DirKind) { 2351 default: 2352 break; 2353 case DK_ASSIGN: 2354 case DK_EQU: 2355 case DK_TEXTEQU: 2356 Lex(); 2357 return parseDirectiveEquate(nextVal, IDVal, DirKind); 2358 case DK_BYTE: 2359 case DK_SBYTE: 2360 case DK_DB: 2361 Lex(); 2362 return parseDirectiveNamedValue(nextVal, 1, IDVal, IDLoc); 2363 case DK_WORD: 2364 case DK_SWORD: 2365 case DK_DW: 2366 Lex(); 2367 return parseDirectiveNamedValue(nextVal, 2, IDVal, IDLoc); 2368 case DK_DWORD: 2369 case DK_SDWORD: 2370 case DK_DD: 2371 Lex(); 2372 return parseDirectiveNamedValue(nextVal, 4, IDVal, IDLoc); 2373 case DK_FWORD: 2374 case DK_DF: 2375 Lex(); 2376 return parseDirectiveNamedValue(nextVal, 6, IDVal, IDLoc); 2377 case DK_QWORD: 2378 case DK_SQWORD: 2379 case DK_DQ: 2380 Lex(); 2381 return parseDirectiveNamedValue(nextVal, 8, IDVal, IDLoc); 2382 case DK_REAL4: 2383 Lex(); 2384 return parseDirectiveNamedRealValue(nextVal, APFloat::IEEEsingle(), 4, 2385 IDVal, IDLoc); 2386 case DK_REAL8: 2387 Lex(); 2388 return parseDirectiveNamedRealValue(nextVal, APFloat::IEEEdouble(), 8, 2389 IDVal, IDLoc); 2390 case DK_REAL10: 2391 Lex(); 2392 return parseDirectiveNamedRealValue(nextVal, APFloat::x87DoubleExtended(), 2393 10, IDVal, IDLoc); 2394 case DK_STRUCT: 2395 case DK_UNION: 2396 Lex(); 2397 return parseDirectiveStruct(nextVal, DirKind, IDVal, IDLoc); 2398 case DK_ENDS: 2399 Lex(); 2400 return parseDirectiveEnds(IDVal, IDLoc); 2401 case DK_MACRO: 2402 Lex(); 2403 return parseDirectiveMacro(IDVal, IDLoc); 2404 } 2405 2406 // Finally, we check if this is allocating a variable with user-defined type. 2407 auto NextIt = Structs.find(nextVal.lower()); 2408 if (NextIt != Structs.end()) { 2409 Lex(); 2410 return parseDirectiveNamedStructValue(/*Structure=*/NextIt->getValue(), 2411 nextVal, nextLoc, IDVal); 2412 } 2413 2414 // __asm _emit or __asm __emit 2415 if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" || 2416 IDVal == "_EMIT" || IDVal == "__EMIT")) 2417 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size()); 2418 2419 // __asm align 2420 if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN")) 2421 return parseDirectiveMSAlign(IDLoc, Info); 2422 2423 if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN")) 2424 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4); 2425 if (checkForValidSection()) 2426 return true; 2427 2428 // Canonicalize the opcode to lower case. 2429 std::string OpcodeStr = IDVal.lower(); 2430 ParseInstructionInfo IInfo(Info.AsmRewrites); 2431 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID, 2432 Info.ParsedOperands); 2433 Info.ParseError = ParseHadError; 2434 2435 // Dump the parsed representation, if requested. 2436 if (getShowParsedOperands()) { 2437 SmallString<256> Str; 2438 raw_svector_ostream OS(Str); 2439 OS << "parsed instruction: ["; 2440 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) { 2441 if (i != 0) 2442 OS << ", "; 2443 Info.ParsedOperands[i]->print(OS); 2444 } 2445 OS << "]"; 2446 2447 printMessage(IDLoc, SourceMgr::DK_Note, OS.str()); 2448 } 2449 2450 // Fail even if ParseInstruction erroneously returns false. 2451 if (hasPendingError() || ParseHadError) 2452 return true; 2453 2454 // If we are generating dwarf for the current section then generate a .loc 2455 // directive for the instruction. 2456 if (!ParseHadError && enabledGenDwarfForAssembly() && 2457 getContext().getGenDwarfSectionSyms().count( 2458 getStreamer().getCurrentSectionOnly())) { 2459 unsigned Line; 2460 if (ActiveMacros.empty()) 2461 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer); 2462 else 2463 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc, 2464 ActiveMacros.front()->ExitBuffer); 2465 2466 // If we previously parsed a cpp hash file line comment then make sure the 2467 // current Dwarf File is for the CppHashFilename if not then emit the 2468 // Dwarf File table for it and adjust the line number for the .loc. 2469 if (!CppHashInfo.Filename.empty()) { 2470 unsigned FileNumber = getStreamer().emitDwarfFileDirective( 2471 0, StringRef(), CppHashInfo.Filename); 2472 getContext().setGenDwarfFileNumber(FileNumber); 2473 2474 unsigned CppHashLocLineNo = 2475 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf); 2476 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo); 2477 } 2478 2479 getStreamer().emitDwarfLocDirective( 2480 getContext().getGenDwarfFileNumber(), Line, 0, 2481 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0, 2482 StringRef()); 2483 } 2484 2485 // If parsing succeeded, match the instruction. 2486 if (!ParseHadError) { 2487 uint64_t ErrorInfo; 2488 if (getTargetParser().MatchAndEmitInstruction( 2489 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo, 2490 getTargetParser().isParsingMSInlineAsm())) 2491 return true; 2492 } 2493 return false; 2494 } 2495 2496 // Parse and erase curly braces marking block start/end. 2497 bool MasmParser::parseCurlyBlockScope( 2498 SmallVectorImpl<AsmRewrite> &AsmStrRewrites) { 2499 // Identify curly brace marking block start/end. 2500 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly)) 2501 return false; 2502 2503 SMLoc StartLoc = Lexer.getLoc(); 2504 Lex(); // Eat the brace. 2505 if (Lexer.is(AsmToken::EndOfStatement)) 2506 Lex(); // Eat EndOfStatement following the brace. 2507 2508 // Erase the block start/end brace from the output asm string. 2509 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() - 2510 StartLoc.getPointer()); 2511 return true; 2512 } 2513 2514 /// parseCppHashLineFilenameComment as this: 2515 /// ::= # number "filename" 2516 bool MasmParser::parseCppHashLineFilenameComment(SMLoc L) { 2517 Lex(); // Eat the hash token. 2518 // Lexer only ever emits HashDirective if it fully formed if it's 2519 // done the checking already so this is an internal error. 2520 assert(getTok().is(AsmToken::Integer) && 2521 "Lexing Cpp line comment: Expected Integer"); 2522 int64_t LineNumber = getTok().getIntVal(); 2523 Lex(); 2524 assert(getTok().is(AsmToken::String) && 2525 "Lexing Cpp line comment: Expected String"); 2526 StringRef Filename = getTok().getString(); 2527 Lex(); 2528 2529 // Get rid of the enclosing quotes. 2530 Filename = Filename.substr(1, Filename.size() - 2); 2531 2532 // Save the SMLoc, Filename and LineNumber for later use by diagnostics 2533 // and possibly DWARF file info. 2534 CppHashInfo.Loc = L; 2535 CppHashInfo.Filename = Filename; 2536 CppHashInfo.LineNumber = LineNumber; 2537 CppHashInfo.Buf = CurBuffer; 2538 if (FirstCppHashFilename.empty()) 2539 FirstCppHashFilename = Filename; 2540 return false; 2541 } 2542 2543 /// will use the last parsed cpp hash line filename comment 2544 /// for the Filename and LineNo if any in the diagnostic. 2545 void MasmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) { 2546 const MasmParser *Parser = static_cast<const MasmParser *>(Context); 2547 raw_ostream &OS = errs(); 2548 2549 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr(); 2550 SMLoc DiagLoc = Diag.getLoc(); 2551 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2552 unsigned CppHashBuf = 2553 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc); 2554 2555 // Like SourceMgr::printMessage() we need to print the include stack if any 2556 // before printing the message. 2557 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc); 2558 if (!Parser->SavedDiagHandler && DiagCurBuffer && 2559 DiagCurBuffer != DiagSrcMgr.getMainFileID()) { 2560 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer); 2561 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS); 2562 } 2563 2564 // If we have not parsed a cpp hash line filename comment or the source 2565 // manager changed or buffer changed (like in a nested include) then just 2566 // print the normal diagnostic using its Filename and LineNo. 2567 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr || 2568 DiagBuf != CppHashBuf) { 2569 if (Parser->SavedDiagHandler) 2570 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext); 2571 else 2572 Diag.print(nullptr, OS); 2573 return; 2574 } 2575 2576 // Use the CppHashFilename and calculate a line number based on the 2577 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc 2578 // for the diagnostic. 2579 const std::string &Filename = std::string(Parser->CppHashInfo.Filename); 2580 2581 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf); 2582 int CppHashLocLineNo = 2583 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf); 2584 int LineNo = 2585 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo); 2586 2587 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo, 2588 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(), 2589 Diag.getLineContents(), Diag.getRanges()); 2590 2591 if (Parser->SavedDiagHandler) 2592 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext); 2593 else 2594 NewDiag.print(nullptr, OS); 2595 } 2596 2597 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The 2598 // difference being that that function accepts '@' as part of identifiers and 2599 // we can't do that. AsmLexer.cpp should probably be changed to handle 2600 // '@' as a special case when needed. 2601 static bool isIdentifierChar(char c) { 2602 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' || 2603 c == '.'; 2604 } 2605 2606 bool MasmParser::expandMacro(raw_svector_ostream &OS, StringRef Body, 2607 ArrayRef<MCAsmMacroParameter> Parameters, 2608 ArrayRef<MCAsmMacroArgument> A, 2609 const std::vector<std::string> &Locals, SMLoc L) { 2610 unsigned NParameters = Parameters.size(); 2611 bool HasVararg = NParameters ? Parameters.back().Vararg : false; 2612 if (NParameters != A.size()) 2613 return Error(L, "Wrong number of arguments"); 2614 StringMap<std::string> LocalSymbols; 2615 std::string Name; 2616 Name.reserve(6); 2617 for (StringRef Local : Locals) { 2618 raw_string_ostream LocalName(Name); 2619 LocalName << "??" 2620 << format_hex_no_prefix(LocalCounter++, 4, /*Upper=*/true); 2621 LocalSymbols.insert({Local, LocalName.str()}); 2622 Name.clear(); 2623 } 2624 2625 while (!Body.empty()) { 2626 // Scan for the next substitution. 2627 std::size_t End = Body.size(), Pos = 0; 2628 for (; Pos != End; ++Pos) { 2629 // Find the next possible identifier 2630 if (Body[Pos] == '&' || isIdentifierChar(Body[Pos])) 2631 break; 2632 } 2633 2634 // Add the prefix. 2635 OS << Body.slice(0, Pos); 2636 2637 // Check if we reached the end. 2638 if (Pos == End) 2639 break; 2640 2641 unsigned I = Pos; 2642 bool InitialAmpersand = (Body[I] == '&'); 2643 if (InitialAmpersand) { 2644 ++I; 2645 ++Pos; 2646 } 2647 while (isIdentifierChar(Body[I]) && I + 1 != End) 2648 ++I; 2649 2650 const char *Begin = Body.data() + Pos; 2651 StringRef Argument(Begin, I - Pos); 2652 unsigned Index = 0; 2653 2654 for (; Index < NParameters; ++Index) 2655 if (Parameters[Index].Name == Argument) 2656 break; 2657 2658 if (Index == NParameters) { 2659 if (InitialAmpersand) 2660 OS << '&'; 2661 auto it = LocalSymbols.find(Argument.lower()); 2662 if (it != LocalSymbols.end()) 2663 OS << it->second; 2664 else 2665 OS << Argument; 2666 Pos = I; 2667 } else { 2668 bool VarargParameter = HasVararg && Index == (NParameters - 1); 2669 for (const AsmToken &Token : A[Index]) { 2670 // In MASM, you can write '%expr'. 2671 // The prefix '%' evaluates the expression 'expr' 2672 // and uses the result as a string (e.g. replace %(1+2) with the 2673 // string "3"). 2674 // Here, we identify the integer token which is the result of the 2675 // absolute expression evaluation and replace it with its string 2676 // representation. 2677 if (Token.getString().front() == '%' && Token.is(AsmToken::Integer)) 2678 // Emit an integer value to the buffer. 2679 OS << Token.getIntVal(); 2680 // We expect no quotes around the string's contents when 2681 // parsing for varargs. 2682 else if (Token.isNot(AsmToken::String) || VarargParameter) 2683 OS << Token.getString(); 2684 else 2685 OS << Token.getStringContents(); 2686 } 2687 2688 Pos += Argument.size(); 2689 if (Pos < End && Body[Pos] == '&') { 2690 ++Pos; 2691 } 2692 } 2693 // Update the scan point. 2694 Body = Body.substr(Pos); 2695 } 2696 2697 return false; 2698 } 2699 2700 static bool isOperator(AsmToken::TokenKind kind) { 2701 switch (kind) { 2702 default: 2703 return false; 2704 case AsmToken::Plus: 2705 case AsmToken::Minus: 2706 case AsmToken::Tilde: 2707 case AsmToken::Slash: 2708 case AsmToken::Star: 2709 case AsmToken::Dot: 2710 case AsmToken::Equal: 2711 case AsmToken::EqualEqual: 2712 case AsmToken::Pipe: 2713 case AsmToken::PipePipe: 2714 case AsmToken::Caret: 2715 case AsmToken::Amp: 2716 case AsmToken::AmpAmp: 2717 case AsmToken::Exclaim: 2718 case AsmToken::ExclaimEqual: 2719 case AsmToken::Less: 2720 case AsmToken::LessEqual: 2721 case AsmToken::LessLess: 2722 case AsmToken::LessGreater: 2723 case AsmToken::Greater: 2724 case AsmToken::GreaterEqual: 2725 case AsmToken::GreaterGreater: 2726 return true; 2727 } 2728 } 2729 2730 namespace { 2731 2732 class AsmLexerSkipSpaceRAII { 2733 public: 2734 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) { 2735 Lexer.setSkipSpace(SkipSpace); 2736 } 2737 2738 ~AsmLexerSkipSpaceRAII() { 2739 Lexer.setSkipSpace(true); 2740 } 2741 2742 private: 2743 AsmLexer &Lexer; 2744 }; 2745 2746 } // end anonymous namespace 2747 2748 bool MasmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) { 2749 if (Vararg) { 2750 if (Lexer.isNot(AsmToken::EndOfStatement)) { 2751 StringRef Str = parseStringToEndOfStatement(); 2752 MA.emplace_back(AsmToken::String, Str); 2753 } 2754 return false; 2755 } 2756 2757 SMLoc StrLoc = Lexer.getLoc(), EndLoc; 2758 if (Lexer.is(AsmToken::Less) && isAngleBracketString(StrLoc, EndLoc)) { 2759 const char *StrChar = StrLoc.getPointer(); 2760 const char *EndChar = EndLoc.getPointer(); 2761 jumpToLoc(EndLoc, CurBuffer); 2762 /// Eat from '<' to '>'. 2763 Lex(); 2764 MA.emplace_back(AsmToken::String, StringRef(StrChar, EndChar - StrChar)); 2765 return false; 2766 } 2767 2768 unsigned ParenLevel = 0; 2769 2770 // Darwin doesn't use spaces to delmit arguments. 2771 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin); 2772 2773 bool SpaceEaten; 2774 2775 while (true) { 2776 SpaceEaten = false; 2777 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) 2778 return TokError("unexpected token in macro instantiation"); 2779 2780 if (ParenLevel == 0) { 2781 if (Lexer.is(AsmToken::Comma)) 2782 break; 2783 2784 if (Lexer.is(AsmToken::Space)) { 2785 SpaceEaten = true; 2786 Lexer.Lex(); // Eat spaces. 2787 } 2788 2789 // Spaces can delimit parameters, but could also be part an expression. 2790 // If the token after a space is an operator, add the token and the next 2791 // one into this argument 2792 if (!IsDarwin) { 2793 if (isOperator(Lexer.getKind())) { 2794 MA.push_back(getTok()); 2795 Lexer.Lex(); 2796 2797 // Whitespace after an operator can be ignored. 2798 if (Lexer.is(AsmToken::Space)) 2799 Lexer.Lex(); 2800 2801 continue; 2802 } 2803 } 2804 if (SpaceEaten) 2805 break; 2806 } 2807 2808 // handleMacroEntry relies on not advancing the lexer here 2809 // to be able to fill in the remaining default parameter values 2810 if (Lexer.is(AsmToken::EndOfStatement)) 2811 break; 2812 2813 // Adjust the current parentheses level. 2814 if (Lexer.is(AsmToken::LParen)) 2815 ++ParenLevel; 2816 else if (Lexer.is(AsmToken::RParen) && ParenLevel) 2817 --ParenLevel; 2818 2819 // Append the token to the current argument list. 2820 MA.push_back(getTok()); 2821 Lexer.Lex(); 2822 } 2823 2824 if (ParenLevel != 0) 2825 return TokError("unbalanced parentheses in macro argument"); 2826 return false; 2827 } 2828 2829 // Parse the macro instantiation arguments. 2830 bool MasmParser::parseMacroArguments(const MCAsmMacro *M, 2831 MCAsmMacroArguments &A) { 2832 const unsigned NParameters = M ? M->Parameters.size() : 0; 2833 bool NamedParametersFound = false; 2834 SmallVector<SMLoc, 4> FALocs; 2835 2836 A.resize(NParameters); 2837 FALocs.resize(NParameters); 2838 2839 // Parse two kinds of macro invocations: 2840 // - macros defined without any parameters accept an arbitrary number of them 2841 // - macros defined with parameters accept at most that many of them 2842 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false; 2843 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters; 2844 ++Parameter) { 2845 SMLoc IDLoc = Lexer.getLoc(); 2846 MCAsmMacroParameter FA; 2847 2848 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) { 2849 if (parseIdentifier(FA.Name)) 2850 return Error(IDLoc, "invalid argument identifier for formal argument"); 2851 2852 if (Lexer.isNot(AsmToken::Equal)) 2853 return TokError("expected '=' after formal parameter identifier"); 2854 2855 Lex(); 2856 2857 NamedParametersFound = true; 2858 } 2859 bool Vararg = HasVararg && Parameter == (NParameters - 1); 2860 2861 if (NamedParametersFound && FA.Name.empty()) 2862 return Error(IDLoc, "cannot mix positional and keyword arguments"); 2863 2864 SMLoc StrLoc = Lexer.getLoc(); 2865 SMLoc EndLoc; 2866 if (Lexer.is(AsmToken::Percent)) { 2867 const MCExpr *AbsoluteExp; 2868 int64_t Value; 2869 /// Eat '%'. 2870 Lex(); 2871 if (parseExpression(AbsoluteExp, EndLoc)) 2872 return false; 2873 if (!AbsoluteExp->evaluateAsAbsolute(Value, 2874 getStreamer().getAssemblerPtr())) 2875 return Error(StrLoc, "expected absolute expression"); 2876 const char *StrChar = StrLoc.getPointer(); 2877 const char *EndChar = EndLoc.getPointer(); 2878 AsmToken newToken(AsmToken::Integer, 2879 StringRef(StrChar, EndChar - StrChar), Value); 2880 FA.Value.push_back(newToken); 2881 } else if (parseMacroArgument(FA.Value, Vararg)) 2882 return true; 2883 2884 unsigned PI = Parameter; 2885 if (!FA.Name.empty()) { 2886 unsigned FAI = 0; 2887 for (FAI = 0; FAI < NParameters; ++FAI) 2888 if (M->Parameters[FAI].Name == FA.Name) 2889 break; 2890 2891 if (FAI >= NParameters) { 2892 assert(M && "expected macro to be defined"); 2893 return Error(IDLoc, "parameter named '" + FA.Name + 2894 "' does not exist for macro '" + M->Name + "'"); 2895 } 2896 PI = FAI; 2897 } 2898 2899 if (!FA.Value.empty()) { 2900 if (A.size() <= PI) 2901 A.resize(PI + 1); 2902 A[PI] = FA.Value; 2903 2904 if (FALocs.size() <= PI) 2905 FALocs.resize(PI + 1); 2906 2907 FALocs[PI] = Lexer.getLoc(); 2908 } 2909 2910 // At the end of the statement, fill in remaining arguments that have 2911 // default values. If there aren't any, then the next argument is 2912 // required but missing 2913 if (Lexer.is(AsmToken::EndOfStatement)) { 2914 bool Failure = false; 2915 for (unsigned FAI = 0; FAI < NParameters; ++FAI) { 2916 if (A[FAI].empty()) { 2917 if (M->Parameters[FAI].Required) { 2918 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(), 2919 "missing value for required parameter " 2920 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'"); 2921 Failure = true; 2922 } 2923 2924 if (!M->Parameters[FAI].Value.empty()) 2925 A[FAI] = M->Parameters[FAI].Value; 2926 } 2927 } 2928 return Failure; 2929 } 2930 2931 if (Lexer.is(AsmToken::Comma)) 2932 Lex(); 2933 } 2934 2935 return TokError("too many positional arguments"); 2936 } 2937 2938 bool MasmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) { 2939 // Arbitrarily limit macro nesting depth (default matches 'as'). We can 2940 // eliminate this, although we should protect against infinite loops. 2941 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth; 2942 if (ActiveMacros.size() == MaxNestingDepth) { 2943 std::ostringstream MaxNestingDepthError; 2944 MaxNestingDepthError << "macros cannot be nested more than " 2945 << MaxNestingDepth << " levels deep." 2946 << " Use -asm-macro-max-nesting-depth to increase " 2947 "this limit."; 2948 return TokError(MaxNestingDepthError.str()); 2949 } 2950 2951 MCAsmMacroArguments A; 2952 if (parseMacroArguments(M, A)) 2953 return true; 2954 2955 // Macro instantiation is lexical, unfortunately. We construct a new buffer 2956 // to hold the macro body with substitutions. 2957 SmallString<256> Buf; 2958 StringRef Body = M->Body; 2959 raw_svector_ostream OS(Buf); 2960 2961 if (expandMacro(OS, Body, M->Parameters, A, M->Locals, getTok().getLoc())) 2962 return true; 2963 2964 // We include the endm in the buffer as our cue to exit the macro 2965 // instantiation. 2966 OS << "endm\n"; 2967 2968 std::unique_ptr<MemoryBuffer> Instantiation = 2969 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 2970 2971 // Create the macro instantiation object and add to the current macro 2972 // instantiation stack. 2973 MacroInstantiation *MI = new MacroInstantiation{ 2974 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 2975 ActiveMacros.push_back(MI); 2976 2977 ++NumOfMacroInstantiations; 2978 2979 // Jump to the macro instantiation and prime the lexer. 2980 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 2981 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 2982 Lex(); 2983 2984 return false; 2985 } 2986 2987 void MasmParser::handleMacroExit() { 2988 // Jump to the EndOfStatement we should return to, and consume it. 2989 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer); 2990 Lex(); 2991 2992 // Pop the instantiation entry. 2993 delete ActiveMacros.back(); 2994 ActiveMacros.pop_back(); 2995 } 2996 2997 /// parseIdentifier: 2998 /// ::= identifier 2999 /// ::= string 3000 bool MasmParser::parseIdentifier(StringRef &Res) { 3001 // The assembler has relaxed rules for accepting identifiers, in particular we 3002 // allow things like '.globl $foo' and '.def @feat.00', which would normally 3003 // be separate tokens. At this level, we have already lexed so we cannot 3004 // (currently) handle this as a context dependent token, instead we detect 3005 // adjacent tokens and return the combined identifier. 3006 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) { 3007 SMLoc PrefixLoc = getLexer().getLoc(); 3008 3009 // Consume the prefix character, and check for a following identifier. 3010 3011 AsmToken Buf[1]; 3012 Lexer.peekTokens(Buf, false); 3013 3014 if (Buf[0].isNot(AsmToken::Identifier)) 3015 return true; 3016 3017 // We have a '$' or '@' followed by an identifier, make sure they are adjacent. 3018 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer()) 3019 return true; 3020 3021 // eat $ or @ 3022 Lexer.Lex(); // Lexer's Lex guarantees consecutive token. 3023 // Construct the joined identifier and consume the token. 3024 Res = 3025 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1); 3026 Lex(); // Parser Lex to maintain invariants. 3027 return false; 3028 } 3029 3030 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) 3031 return true; 3032 3033 Res = getTok().getIdentifier(); 3034 3035 Lex(); // Consume the identifier token. 3036 3037 return false; 3038 } 3039 3040 /// parseDirectiveEquate: 3041 /// ::= name "=" expression 3042 /// | name "equ" expression (not redefinable) 3043 /// | name "equ" text-list 3044 /// | name "textequ" text-list 3045 bool MasmParser::parseDirectiveEquate(StringRef IDVal, StringRef Name, 3046 DirectiveKind DirKind) { 3047 Variable &Var = Variables[Name]; 3048 if (Var.Name.empty()) { 3049 Var.Name = Name; 3050 } else if (!Var.Redefinable) { 3051 return TokError("invalid variable redefinition"); 3052 } 3053 Var.Redefinable = (DirKind != DK_EQU); 3054 3055 if (DirKind == DK_EQU || DirKind == DK_TEXTEQU) { 3056 // "equ" and "textequ" both allow text expressions. 3057 std::string Value; 3058 if (!parseTextItem(Value)) { 3059 Var.IsText = true; 3060 Var.TextValue = Value; 3061 3062 // Accept a text-list, not just one text-item. 3063 auto parseItem = [&]() -> bool { 3064 if (parseTextItem(Value)) 3065 return true; 3066 Var.TextValue += Value; 3067 return false; 3068 }; 3069 if (parseOptionalToken(AsmToken::Comma) && parseMany(parseItem)) 3070 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3071 3072 return false; 3073 } 3074 } 3075 if (DirKind == DK_TEXTEQU) 3076 return TokError("expected <text> in '" + Twine(IDVal) + "' directive"); 3077 3078 // Parse as expression assignment. 3079 const MCExpr *Expr; 3080 SMLoc EndLoc, StartLoc = Lexer.getLoc(); 3081 if (parseExpression(Expr, EndLoc)) 3082 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3083 MCSymbol *Sym = getContext().getOrCreateSymbol(Var.Name); 3084 Sym->setRedefinable(Var.Redefinable); 3085 Sym->setVariableValue(Expr); 3086 Sym->setExternal(false); 3087 3088 if (Expr->evaluateAsAbsolute(Var.NumericValue, 3089 getStreamer().getAssemblerPtr())) 3090 return false; 3091 3092 // Not an absolute expression; define as a text replacement. 3093 Var.IsText = true; 3094 Var.TextValue = StringRef(StartLoc.getPointer(), 3095 EndLoc.getPointer() - StartLoc.getPointer()).str(); 3096 return false; 3097 } 3098 3099 bool MasmParser::parseEscapedString(std::string &Data) { 3100 if (check(getTok().isNot(AsmToken::String), "expected string")) 3101 return true; 3102 3103 Data = ""; 3104 char Quote = getTok().getString().front(); 3105 StringRef Str = getTok().getStringContents(); 3106 Data.reserve(Str.size()); 3107 for (size_t i = 0, e = Str.size(); i != e; ++i) { 3108 Data.push_back(Str[i]); 3109 if (Str[i] == Quote) { 3110 // MASM treats doubled delimiting quotes as an escaped delimiting quote. 3111 // If we're escaping the string's trailing delimiter, we're definitely 3112 // missing a quotation mark. 3113 if (i + 1 == Str.size()) 3114 return Error(getTok().getLoc(), "missing quotation mark in string"); 3115 if (Str[i + 1] == Quote) 3116 ++i; 3117 } 3118 } 3119 3120 Lex(); 3121 return false; 3122 } 3123 3124 bool MasmParser::parseAngleBracketString(std::string &Data) { 3125 SMLoc EndLoc, StartLoc = getTok().getLoc(); 3126 if (isAngleBracketString(StartLoc, EndLoc)) { 3127 const char *StartChar = StartLoc.getPointer() + 1; 3128 const char *EndChar = EndLoc.getPointer() - 1; 3129 jumpToLoc(EndLoc, CurBuffer); 3130 // Eat from '<' to '>'. 3131 Lex(); 3132 3133 Data = angleBracketString(StringRef(StartChar, EndChar - StartChar)); 3134 return false; 3135 } 3136 return true; 3137 } 3138 3139 /// textItem ::= textLiteral | textMacroID | % constExpr 3140 bool MasmParser::parseTextItem(std::string &Data) { 3141 // TODO(epastor): Support textMacroID and % expansion of expressions. 3142 return parseAngleBracketString(Data); 3143 } 3144 3145 /// parseDirectiveAscii: 3146 /// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ] 3147 bool MasmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) { 3148 auto parseOp = [&]() -> bool { 3149 std::string Data; 3150 if (checkForValidSection() || parseEscapedString(Data)) 3151 return true; 3152 getStreamer().emitBytes(Data); 3153 if (ZeroTerminated) 3154 getStreamer().emitBytes(StringRef("\0", 1)); 3155 return false; 3156 }; 3157 3158 if (parseMany(parseOp)) 3159 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3160 return false; 3161 } 3162 3163 bool MasmParser::emitIntValue(const MCExpr *Value, unsigned Size) { 3164 // Special case constant expressions to match code generator. 3165 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 3166 assert(Size <= 8 && "Invalid size"); 3167 int64_t IntValue = MCE->getValue(); 3168 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 3169 return Error(MCE->getLoc(), "out of range literal value"); 3170 getStreamer().emitIntValue(IntValue, Size); 3171 } else { 3172 const MCSymbolRefExpr *MSE = dyn_cast<MCSymbolRefExpr>(Value); 3173 if (MSE && MSE->getSymbol().getName() == "?") { 3174 // ? initializer; treat as 0. 3175 getStreamer().emitIntValue(0, Size); 3176 } else { 3177 getStreamer().emitValue(Value, Size, Value->getLoc()); 3178 } 3179 } 3180 return false; 3181 } 3182 3183 bool MasmParser::parseScalarInitializer(unsigned Size, 3184 SmallVectorImpl<const MCExpr *> &Values, 3185 unsigned StringPadLength) { 3186 if (Size == 1 && getTok().is(AsmToken::String)) { 3187 std::string Value; 3188 if (parseEscapedString(Value)) 3189 return true; 3190 // Treat each character as an initializer. 3191 for (const unsigned char CharVal : Value) 3192 Values.push_back(MCConstantExpr::create(CharVal, getContext())); 3193 3194 // Pad the string with spaces to the specified length. 3195 for (size_t i = Value.size(); i < StringPadLength; ++i) 3196 Values.push_back(MCConstantExpr::create(' ', getContext())); 3197 } else { 3198 const MCExpr *Value; 3199 if (parseExpression(Value)) 3200 return true; 3201 if (getTok().is(AsmToken::Identifier) && 3202 getTok().getString().equals_lower("dup")) { 3203 Lex(); // Eat 'dup'. 3204 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 3205 if (!MCE) 3206 return Error(Value->getLoc(), 3207 "cannot repeat value a non-constant number of times"); 3208 const int64_t Repetitions = MCE->getValue(); 3209 if (Repetitions < 0) 3210 return Error(Value->getLoc(), 3211 "cannot repeat value a negative number of times"); 3212 3213 SmallVector<const MCExpr *, 1> DuplicatedValues; 3214 if (parseToken(AsmToken::LParen, 3215 "parentheses required for 'dup' contents") || 3216 parseScalarInstList(Size, DuplicatedValues) || 3217 parseToken(AsmToken::RParen, "unmatched parentheses")) 3218 return true; 3219 3220 for (int i = 0; i < Repetitions; ++i) 3221 Values.append(DuplicatedValues.begin(), DuplicatedValues.end()); 3222 } else { 3223 Values.push_back(Value); 3224 } 3225 } 3226 return false; 3227 } 3228 3229 bool MasmParser::parseScalarInstList(unsigned Size, 3230 SmallVectorImpl<const MCExpr *> &Values, 3231 const AsmToken::TokenKind EndToken) { 3232 while (getTok().isNot(EndToken) && 3233 (EndToken != AsmToken::Greater || 3234 getTok().isNot(AsmToken::GreaterGreater))) { 3235 parseScalarInitializer(Size, Values); 3236 3237 // If we see a comma, continue, and allow line continuation. 3238 if (!parseOptionalToken(AsmToken::Comma)) 3239 break; 3240 parseOptionalToken(AsmToken::EndOfStatement); 3241 } 3242 return false; 3243 } 3244 3245 bool MasmParser::emitIntegralValues(unsigned Size, unsigned *Count) { 3246 SmallVector<const MCExpr *, 1> Values; 3247 if (checkForValidSection() || parseScalarInstList(Size, Values)) 3248 return true; 3249 3250 for (auto Value : Values) { 3251 emitIntValue(Value, Size); 3252 } 3253 if (Count) 3254 *Count = Values.size(); 3255 return false; 3256 } 3257 3258 // Add a field to the current structure. 3259 bool MasmParser::addIntegralField(StringRef Name, unsigned Size) { 3260 StructInfo &Struct = StructInProgress.back(); 3261 FieldInfo &Field = Struct.addField(Name, FT_INTEGRAL, Size); 3262 IntFieldInfo &IntInfo = Field.Contents.IntInfo; 3263 3264 Field.Type = Size; 3265 3266 if (parseScalarInstList(Size, IntInfo.Values)) 3267 return true; 3268 3269 Field.SizeOf = Field.Type * IntInfo.Values.size(); 3270 Field.LengthOf = IntInfo.Values.size(); 3271 if (Struct.IsUnion) 3272 Struct.Size = std::max(Struct.Size, Field.SizeOf); 3273 else 3274 Struct.Size += Field.SizeOf; 3275 return false; 3276 } 3277 3278 /// parseDirectiveValue 3279 /// ::= (byte | word | ... ) [ expression (, expression)* ] 3280 bool MasmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) { 3281 if (StructInProgress.empty()) { 3282 // Initialize data value. 3283 if (emitIntegralValues(Size)) 3284 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3285 } else if (addIntegralField("", Size)) { 3286 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3287 } 3288 3289 return false; 3290 } 3291 3292 /// parseDirectiveNamedValue 3293 /// ::= name (byte | word | ... ) [ expression (, expression)* ] 3294 bool MasmParser::parseDirectiveNamedValue(StringRef TypeName, unsigned Size, 3295 StringRef Name, SMLoc NameLoc) { 3296 if (StructInProgress.empty()) { 3297 // Initialize named data value. 3298 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3299 getStreamer().emitLabel(Sym); 3300 unsigned Count; 3301 if (emitIntegralValues(Size, &Count)) 3302 return addErrorSuffix(" in '" + Twine(TypeName) + "' directive"); 3303 3304 AsmTypeInfo Type; 3305 Type.Name = TypeName; 3306 Type.Size = Size * Count; 3307 Type.ElementSize = Size; 3308 Type.Length = Count; 3309 KnownType[Name.lower()] = Type; 3310 } else if (addIntegralField(Name, Size)) { 3311 return addErrorSuffix(" in '" + Twine(TypeName) + "' directive"); 3312 } 3313 3314 return false; 3315 } 3316 3317 static bool parseHexOcta(MasmParser &Asm, uint64_t &hi, uint64_t &lo) { 3318 if (Asm.getTok().isNot(AsmToken::Integer) && 3319 Asm.getTok().isNot(AsmToken::BigNum)) 3320 return Asm.TokError("unknown token in expression"); 3321 SMLoc ExprLoc = Asm.getTok().getLoc(); 3322 APInt IntValue = Asm.getTok().getAPIntVal(); 3323 Asm.Lex(); 3324 if (!IntValue.isIntN(128)) 3325 return Asm.Error(ExprLoc, "out of range literal value"); 3326 if (!IntValue.isIntN(64)) { 3327 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue(); 3328 lo = IntValue.getLoBits(64).getZExtValue(); 3329 } else { 3330 hi = 0; 3331 lo = IntValue.getZExtValue(); 3332 } 3333 return false; 3334 } 3335 3336 bool MasmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) { 3337 // We don't truly support arithmetic on floating point expressions, so we 3338 // have to manually parse unary prefixes. 3339 bool IsNeg = false; 3340 SMLoc SignLoc; 3341 if (getLexer().is(AsmToken::Minus)) { 3342 SignLoc = getLexer().getLoc(); 3343 Lexer.Lex(); 3344 IsNeg = true; 3345 } else if (getLexer().is(AsmToken::Plus)) { 3346 SignLoc = getLexer().getLoc(); 3347 Lexer.Lex(); 3348 } 3349 3350 if (Lexer.is(AsmToken::Error)) 3351 return TokError(Lexer.getErr()); 3352 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) && 3353 Lexer.isNot(AsmToken::Identifier)) 3354 return TokError("unexpected token in directive"); 3355 3356 // Convert to an APFloat. 3357 APFloat Value(Semantics); 3358 StringRef IDVal = getTok().getString(); 3359 if (getLexer().is(AsmToken::Identifier)) { 3360 if (IDVal.equals_lower("infinity") || IDVal.equals_lower("inf")) 3361 Value = APFloat::getInf(Semantics); 3362 else if (IDVal.equals_lower("nan")) 3363 Value = APFloat::getNaN(Semantics, false, ~0); 3364 else if (IDVal.equals_lower("?")) 3365 Value = APFloat::getZero(Semantics); 3366 else 3367 return TokError("invalid floating point literal"); 3368 } else if (IDVal.consume_back("r") || IDVal.consume_back("R")) { 3369 // MASM hexadecimal floating-point literal; no APFloat conversion needed. 3370 // To match ML64.exe, ignore the initial sign. 3371 unsigned SizeInBits = Value.getSizeInBits(Semantics); 3372 if (SizeInBits != (IDVal.size() << 2)) 3373 return TokError("invalid floating point literal"); 3374 3375 // Consume the numeric token. 3376 Lex(); 3377 3378 Res = APInt(SizeInBits, IDVal, 16); 3379 if (SignLoc.isValid()) 3380 return Warning(SignLoc, "MASM-style hex floats ignore explicit sign"); 3381 return false; 3382 } else if (errorToBool( 3383 Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) 3384 .takeError())) { 3385 return TokError("invalid floating point literal"); 3386 } 3387 if (IsNeg) 3388 Value.changeSign(); 3389 3390 // Consume the numeric token. 3391 Lex(); 3392 3393 Res = Value.bitcastToAPInt(); 3394 3395 return false; 3396 } 3397 3398 bool MasmParser::parseRealInstList(const fltSemantics &Semantics, 3399 SmallVectorImpl<APInt> &ValuesAsInt, 3400 const AsmToken::TokenKind EndToken) { 3401 while (getTok().isNot(EndToken) || 3402 (EndToken == AsmToken::Greater && 3403 getTok().isNot(AsmToken::GreaterGreater))) { 3404 const AsmToken NextTok = Lexer.peekTok(); 3405 if (NextTok.is(AsmToken::Identifier) && 3406 NextTok.getString().equals_lower("dup")) { 3407 const MCExpr *Value; 3408 if (parseExpression(Value) || parseToken(AsmToken::Identifier)) 3409 return true; 3410 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 3411 if (!MCE) 3412 return Error(Value->getLoc(), 3413 "cannot repeat value a non-constant number of times"); 3414 const int64_t Repetitions = MCE->getValue(); 3415 if (Repetitions < 0) 3416 return Error(Value->getLoc(), 3417 "cannot repeat value a negative number of times"); 3418 3419 SmallVector<APInt, 1> DuplicatedValues; 3420 if (parseToken(AsmToken::LParen, 3421 "parentheses required for 'dup' contents") || 3422 parseRealInstList(Semantics, DuplicatedValues) || 3423 parseToken(AsmToken::RParen, "unmatched parentheses")) 3424 return true; 3425 3426 for (int i = 0; i < Repetitions; ++i) 3427 ValuesAsInt.append(DuplicatedValues.begin(), DuplicatedValues.end()); 3428 } else { 3429 APInt AsInt; 3430 if (parseRealValue(Semantics, AsInt)) 3431 return true; 3432 ValuesAsInt.push_back(AsInt); 3433 } 3434 3435 // Continue if we see a comma. (Also, allow line continuation.) 3436 if (!parseOptionalToken(AsmToken::Comma)) 3437 break; 3438 parseOptionalToken(AsmToken::EndOfStatement); 3439 } 3440 3441 return false; 3442 } 3443 3444 // Initialize real data values. 3445 bool MasmParser::emitRealValues(const fltSemantics &Semantics, 3446 unsigned *Count) { 3447 if (checkForValidSection()) 3448 return true; 3449 3450 SmallVector<APInt, 1> ValuesAsInt; 3451 if (parseRealInstList(Semantics, ValuesAsInt)) 3452 return true; 3453 3454 for (const APInt &AsInt : ValuesAsInt) { 3455 getStreamer().emitIntValue(AsInt); 3456 } 3457 if (Count) 3458 *Count = ValuesAsInt.size(); 3459 return false; 3460 } 3461 3462 // Add a real field to the current struct. 3463 bool MasmParser::addRealField(StringRef Name, const fltSemantics &Semantics, 3464 size_t Size) { 3465 StructInfo &Struct = StructInProgress.back(); 3466 FieldInfo &Field = Struct.addField(Name, FT_REAL, Size); 3467 RealFieldInfo &RealInfo = Field.Contents.RealInfo; 3468 3469 Field.SizeOf = 0; 3470 3471 if (parseRealInstList(Semantics, RealInfo.AsIntValues)) 3472 return true; 3473 3474 Field.Type = RealInfo.AsIntValues.back().getBitWidth() / 8; 3475 Field.LengthOf = RealInfo.AsIntValues.size(); 3476 Field.SizeOf = Field.Type * Field.LengthOf; 3477 if (Struct.IsUnion) 3478 Struct.Size = std::max(Struct.Size, Field.SizeOf); 3479 else 3480 Struct.Size += Field.SizeOf; 3481 return false; 3482 } 3483 3484 /// parseDirectiveRealValue 3485 /// ::= (real4 | real8 | real10) [ expression (, expression)* ] 3486 bool MasmParser::parseDirectiveRealValue(StringRef IDVal, 3487 const fltSemantics &Semantics, 3488 size_t Size) { 3489 if (StructInProgress.empty()) { 3490 // Initialize data value. 3491 if (emitRealValues(Semantics)) 3492 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3493 } else if (addRealField("", Semantics, Size)) { 3494 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive"); 3495 } 3496 return false; 3497 } 3498 3499 /// parseDirectiveNamedRealValue 3500 /// ::= name (real4 | real8 | real10) [ expression (, expression)* ] 3501 bool MasmParser::parseDirectiveNamedRealValue(StringRef TypeName, 3502 const fltSemantics &Semantics, 3503 unsigned Size, StringRef Name, 3504 SMLoc NameLoc) { 3505 if (StructInProgress.empty()) { 3506 // Initialize named data value. 3507 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 3508 getStreamer().emitLabel(Sym); 3509 unsigned Count; 3510 if (emitRealValues(Semantics, &Count)) 3511 return addErrorSuffix(" in '" + TypeName + "' directive"); 3512 3513 AsmTypeInfo Type; 3514 Type.Name = TypeName; 3515 Type.Size = Size * Count; 3516 Type.ElementSize = Size; 3517 Type.Length = Count; 3518 KnownType[Name.lower()] = Type; 3519 } else if (addRealField(Name, Semantics, Size)) { 3520 return addErrorSuffix(" in '" + TypeName + "' directive"); 3521 } 3522 return false; 3523 } 3524 3525 bool MasmParser::parseOptionalAngleBracketOpen() { 3526 const AsmToken Tok = getTok(); 3527 if (parseOptionalToken(AsmToken::LessLess)) { 3528 AngleBracketDepth++; 3529 Lexer.UnLex(AsmToken(AsmToken::Less, Tok.getString().substr(1))); 3530 return true; 3531 } else if (parseOptionalToken(AsmToken::LessGreater)) { 3532 AngleBracketDepth++; 3533 Lexer.UnLex(AsmToken(AsmToken::Greater, Tok.getString().substr(1))); 3534 return true; 3535 } else if (parseOptionalToken(AsmToken::Less)) { 3536 AngleBracketDepth++; 3537 return true; 3538 } 3539 3540 return false; 3541 } 3542 3543 bool MasmParser::parseAngleBracketClose(const Twine &Msg) { 3544 const AsmToken Tok = getTok(); 3545 if (parseOptionalToken(AsmToken::GreaterGreater)) { 3546 Lexer.UnLex(AsmToken(AsmToken::Greater, Tok.getString().substr(1))); 3547 } else if (parseToken(AsmToken::Greater, Msg)) { 3548 return true; 3549 } 3550 AngleBracketDepth--; 3551 return false; 3552 } 3553 3554 bool MasmParser::parseFieldInitializer(const FieldInfo &Field, 3555 const IntFieldInfo &Contents, 3556 FieldInitializer &Initializer) { 3557 SMLoc Loc = getTok().getLoc(); 3558 3559 SmallVector<const MCExpr *, 1> Values; 3560 if (parseOptionalToken(AsmToken::LCurly)) { 3561 if (Field.LengthOf == 1 && Field.Type > 1) 3562 return Error(Loc, "Cannot initialize scalar field with array value"); 3563 if (parseScalarInstList(Field.Type, Values, AsmToken::RCurly) || 3564 parseToken(AsmToken::RCurly)) 3565 return true; 3566 } else if (parseOptionalAngleBracketOpen()) { 3567 if (Field.LengthOf == 1 && Field.Type > 1) 3568 return Error(Loc, "Cannot initialize scalar field with array value"); 3569 if (parseScalarInstList(Field.Type, Values, AsmToken::Greater) || 3570 parseAngleBracketClose()) 3571 return true; 3572 } else if (Field.LengthOf > 1 && Field.Type > 1) { 3573 return Error(Loc, "Cannot initialize array field with scalar value"); 3574 } else if (parseScalarInitializer(Field.Type, Values, 3575 /*StringPadLength=*/Field.LengthOf)) { 3576 return true; 3577 } 3578 3579 if (Values.size() > Field.LengthOf) { 3580 return Error(Loc, "Initializer too long for field; expected at most " + 3581 std::to_string(Field.LengthOf) + " elements, got " + 3582 std::to_string(Values.size())); 3583 } 3584 // Default-initialize all remaining values. 3585 Values.append(Contents.Values.begin() + Values.size(), Contents.Values.end()); 3586 3587 Initializer = FieldInitializer(std::move(Values)); 3588 return false; 3589 } 3590 3591 bool MasmParser::parseFieldInitializer(const FieldInfo &Field, 3592 const RealFieldInfo &Contents, 3593 FieldInitializer &Initializer) { 3594 const fltSemantics *Semantics; 3595 switch (Field.Type) { 3596 case 4: 3597 Semantics = &APFloat::IEEEsingle(); 3598 break; 3599 case 8: 3600 Semantics = &APFloat::IEEEdouble(); 3601 break; 3602 case 10: 3603 Semantics = &APFloat::x87DoubleExtended(); 3604 break; 3605 default: 3606 llvm_unreachable("unknown real field type"); 3607 } 3608 3609 SMLoc Loc = getTok().getLoc(); 3610 3611 SmallVector<APInt, 1> AsIntValues; 3612 if (parseOptionalToken(AsmToken::LCurly)) { 3613 if (Field.LengthOf == 1) 3614 return Error(Loc, "Cannot initialize scalar field with array value"); 3615 if (parseRealInstList(*Semantics, AsIntValues, AsmToken::RCurly) || 3616 parseToken(AsmToken::RCurly)) 3617 return true; 3618 } else if (parseOptionalAngleBracketOpen()) { 3619 if (Field.LengthOf == 1) 3620 return Error(Loc, "Cannot initialize scalar field with array value"); 3621 if (parseRealInstList(*Semantics, AsIntValues, AsmToken::Greater) || 3622 parseAngleBracketClose()) 3623 return true; 3624 } else if (Field.LengthOf > 1) { 3625 return Error(Loc, "Cannot initialize array field with scalar value"); 3626 } else { 3627 AsIntValues.emplace_back(); 3628 if (parseRealValue(*Semantics, AsIntValues.back())) 3629 return true; 3630 } 3631 3632 if (AsIntValues.size() > Field.LengthOf) { 3633 return Error(Loc, "Initializer too long for field; expected at most " + 3634 std::to_string(Field.LengthOf) + " elements, got " + 3635 std::to_string(AsIntValues.size())); 3636 } 3637 // Default-initialize all remaining values. 3638 AsIntValues.append(Contents.AsIntValues.begin() + AsIntValues.size(), 3639 Contents.AsIntValues.end()); 3640 3641 Initializer = FieldInitializer(std::move(AsIntValues)); 3642 return false; 3643 } 3644 3645 bool MasmParser::parseFieldInitializer(const FieldInfo &Field, 3646 const StructFieldInfo &Contents, 3647 FieldInitializer &Initializer) { 3648 SMLoc Loc = getTok().getLoc(); 3649 3650 std::vector<StructInitializer> Initializers; 3651 if (Field.LengthOf > 1) { 3652 if (parseOptionalToken(AsmToken::LCurly)) { 3653 if (parseStructInstList(Contents.Structure, Initializers, 3654 AsmToken::RCurly) || 3655 parseToken(AsmToken::RCurly)) 3656 return true; 3657 } else if (parseOptionalAngleBracketOpen()) { 3658 if (parseStructInstList(Contents.Structure, Initializers, 3659 AsmToken::Greater) || 3660 parseAngleBracketClose()) 3661 return true; 3662 } else { 3663 return Error(Loc, "Cannot initialize array field with scalar value"); 3664 } 3665 } else { 3666 Initializers.emplace_back(); 3667 if (parseStructInitializer(Contents.Structure, Initializers.back())) 3668 return true; 3669 } 3670 3671 if (Initializers.size() > Field.LengthOf) { 3672 return Error(Loc, "Initializer too long for field; expected at most " + 3673 std::to_string(Field.LengthOf) + " elements, got " + 3674 std::to_string(Initializers.size())); 3675 } 3676 // Default-initialize all remaining values. 3677 Initializers.insert(Initializers.end(), 3678 Contents.Initializers.begin() + Initializers.size(), 3679 Contents.Initializers.end()); 3680 3681 Initializer = FieldInitializer(std::move(Initializers), Contents.Structure); 3682 return false; 3683 } 3684 3685 bool MasmParser::parseFieldInitializer(const FieldInfo &Field, 3686 FieldInitializer &Initializer) { 3687 switch (Field.Contents.FT) { 3688 case FT_INTEGRAL: 3689 return parseFieldInitializer(Field, Field.Contents.IntInfo, Initializer); 3690 case FT_REAL: 3691 return parseFieldInitializer(Field, Field.Contents.RealInfo, Initializer); 3692 case FT_STRUCT: 3693 return parseFieldInitializer(Field, Field.Contents.StructInfo, Initializer); 3694 } 3695 llvm_unreachable("Unhandled FieldType enum"); 3696 } 3697 3698 bool MasmParser::parseStructInitializer(const StructInfo &Structure, 3699 StructInitializer &Initializer) { 3700 const AsmToken FirstToken = getTok(); 3701 3702 Optional<AsmToken::TokenKind> EndToken; 3703 if (parseOptionalToken(AsmToken::LCurly)) { 3704 EndToken = AsmToken::RCurly; 3705 } else if (parseOptionalAngleBracketOpen()) { 3706 EndToken = AsmToken::Greater; 3707 AngleBracketDepth++; 3708 } else if (FirstToken.is(AsmToken::Identifier) && 3709 FirstToken.getString() == "?") { 3710 // ? initializer; leave EndToken uninitialized to treat as empty. 3711 if (parseToken(AsmToken::Identifier)) 3712 return true; 3713 } else { 3714 return Error(FirstToken.getLoc(), "Expected struct initializer"); 3715 } 3716 3717 auto &FieldInitializers = Initializer.FieldInitializers; 3718 size_t FieldIndex = 0; 3719 if (EndToken.hasValue()) { 3720 // Initialize all fields with given initializers. 3721 while (getTok().isNot(EndToken.getValue()) && 3722 FieldIndex < Structure.Fields.size()) { 3723 const FieldInfo &Field = Structure.Fields[FieldIndex++]; 3724 if (parseOptionalToken(AsmToken::Comma)) { 3725 // Empty initializer; use the default and continue. (Also, allow line 3726 // continuation.) 3727 FieldInitializers.push_back(Field.Contents); 3728 parseOptionalToken(AsmToken::EndOfStatement); 3729 continue; 3730 } 3731 FieldInitializers.emplace_back(Field.Contents.FT); 3732 if (parseFieldInitializer(Field, FieldInitializers.back())) 3733 return true; 3734 3735 // Continue if we see a comma. (Also, allow line continuation.) 3736 SMLoc CommaLoc = getTok().getLoc(); 3737 if (!parseOptionalToken(AsmToken::Comma)) 3738 break; 3739 if (FieldIndex == Structure.Fields.size()) 3740 return Error(CommaLoc, "'" + Structure.Name + 3741 "' initializer initializes too many fields"); 3742 parseOptionalToken(AsmToken::EndOfStatement); 3743 } 3744 } 3745 // Default-initialize all remaining fields. 3746 for (auto It = Structure.Fields.begin() + FieldIndex; 3747 It != Structure.Fields.end(); ++It) { 3748 const FieldInfo &Field = *It; 3749 FieldInitializers.push_back(Field.Contents); 3750 } 3751 3752 if (EndToken.hasValue()) { 3753 if (EndToken.getValue() == AsmToken::Greater) 3754 return parseAngleBracketClose(); 3755 3756 return parseToken(EndToken.getValue()); 3757 } 3758 3759 return false; 3760 } 3761 3762 bool MasmParser::parseStructInstList( 3763 const StructInfo &Structure, std::vector<StructInitializer> &Initializers, 3764 const AsmToken::TokenKind EndToken) { 3765 while (getTok().isNot(EndToken) || 3766 (EndToken == AsmToken::Greater && 3767 getTok().isNot(AsmToken::GreaterGreater))) { 3768 const AsmToken NextTok = Lexer.peekTok(); 3769 if (NextTok.is(AsmToken::Identifier) && 3770 NextTok.getString().equals_lower("dup")) { 3771 const MCExpr *Value; 3772 if (parseExpression(Value) || parseToken(AsmToken::Identifier)) 3773 return true; 3774 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 3775 if (!MCE) 3776 return Error(Value->getLoc(), 3777 "cannot repeat value a non-constant number of times"); 3778 const int64_t Repetitions = MCE->getValue(); 3779 if (Repetitions < 0) 3780 return Error(Value->getLoc(), 3781 "cannot repeat value a negative number of times"); 3782 3783 std::vector<StructInitializer> DuplicatedValues; 3784 if (parseToken(AsmToken::LParen, 3785 "parentheses required for 'dup' contents") || 3786 parseStructInstList(Structure, DuplicatedValues) || 3787 parseToken(AsmToken::RParen, "unmatched parentheses")) 3788 return true; 3789 3790 for (int i = 0; i < Repetitions; ++i) 3791 Initializers.insert(Initializers.end(), DuplicatedValues.begin(), 3792 DuplicatedValues.end()); 3793 } else { 3794 Initializers.emplace_back(); 3795 if (parseStructInitializer(Structure, Initializers.back())) 3796 return true; 3797 } 3798 3799 // Continue if we see a comma. (Also, allow line continuation.) 3800 if (!parseOptionalToken(AsmToken::Comma)) 3801 break; 3802 parseOptionalToken(AsmToken::EndOfStatement); 3803 } 3804 3805 return false; 3806 } 3807 3808 bool MasmParser::emitFieldValue(const FieldInfo &Field, 3809 const IntFieldInfo &Contents) { 3810 // Default-initialize all values. 3811 for (const MCExpr *Value : Contents.Values) { 3812 if (emitIntValue(Value, Field.Type)) 3813 return true; 3814 } 3815 return false; 3816 } 3817 3818 bool MasmParser::emitFieldValue(const FieldInfo &Field, 3819 const RealFieldInfo &Contents) { 3820 for (const APInt &AsInt : Contents.AsIntValues) { 3821 getStreamer().emitIntValue(AsInt.getLimitedValue(), 3822 AsInt.getBitWidth() / 8); 3823 } 3824 return false; 3825 } 3826 3827 bool MasmParser::emitFieldValue(const FieldInfo &Field, 3828 const StructFieldInfo &Contents) { 3829 for (const auto &Initializer : Contents.Initializers) { 3830 size_t Index = 0, Offset = 0; 3831 for (const auto &SubField : Contents.Structure.Fields) { 3832 getStreamer().emitZeros(SubField.Offset - Offset); 3833 Offset = SubField.Offset + SubField.SizeOf; 3834 emitFieldInitializer(SubField, Initializer.FieldInitializers[Index++]); 3835 } 3836 } 3837 return false; 3838 } 3839 3840 bool MasmParser::emitFieldValue(const FieldInfo &Field) { 3841 switch (Field.Contents.FT) { 3842 case FT_INTEGRAL: 3843 return emitFieldValue(Field, Field.Contents.IntInfo); 3844 case FT_REAL: 3845 return emitFieldValue(Field, Field.Contents.RealInfo); 3846 case FT_STRUCT: 3847 return emitFieldValue(Field, Field.Contents.StructInfo); 3848 } 3849 llvm_unreachable("Unhandled FieldType enum"); 3850 } 3851 3852 bool MasmParser::emitFieldInitializer(const FieldInfo &Field, 3853 const IntFieldInfo &Contents, 3854 const IntFieldInfo &Initializer) { 3855 for (const auto &Value : Initializer.Values) { 3856 if (emitIntValue(Value, Field.Type)) 3857 return true; 3858 } 3859 // Default-initialize all remaining values. 3860 for (auto it = Contents.Values.begin() + Initializer.Values.size(); 3861 it != Contents.Values.end(); ++it) { 3862 const auto &Value = *it; 3863 if (emitIntValue(Value, Field.Type)) 3864 return true; 3865 } 3866 return false; 3867 } 3868 3869 bool MasmParser::emitFieldInitializer(const FieldInfo &Field, 3870 const RealFieldInfo &Contents, 3871 const RealFieldInfo &Initializer) { 3872 for (const auto &AsInt : Initializer.AsIntValues) { 3873 getStreamer().emitIntValue(AsInt.getLimitedValue(), 3874 AsInt.getBitWidth() / 8); 3875 } 3876 // Default-initialize all remaining values. 3877 for (auto It = Contents.AsIntValues.begin() + Initializer.AsIntValues.size(); 3878 It != Contents.AsIntValues.end(); ++It) { 3879 const auto &AsInt = *It; 3880 getStreamer().emitIntValue(AsInt.getLimitedValue(), 3881 AsInt.getBitWidth() / 8); 3882 } 3883 return false; 3884 } 3885 3886 bool MasmParser::emitFieldInitializer(const FieldInfo &Field, 3887 const StructFieldInfo &Contents, 3888 const StructFieldInfo &Initializer) { 3889 for (const auto &Init : Initializer.Initializers) { 3890 emitStructInitializer(Contents.Structure, Init); 3891 } 3892 // Default-initialize all remaining values. 3893 for (auto It = 3894 Contents.Initializers.begin() + Initializer.Initializers.size(); 3895 It != Contents.Initializers.end(); ++It) { 3896 const auto &Init = *It; 3897 emitStructInitializer(Contents.Structure, Init); 3898 } 3899 return false; 3900 } 3901 3902 bool MasmParser::emitFieldInitializer(const FieldInfo &Field, 3903 const FieldInitializer &Initializer) { 3904 switch (Field.Contents.FT) { 3905 case FT_INTEGRAL: 3906 return emitFieldInitializer(Field, Field.Contents.IntInfo, 3907 Initializer.IntInfo); 3908 case FT_REAL: 3909 return emitFieldInitializer(Field, Field.Contents.RealInfo, 3910 Initializer.RealInfo); 3911 case FT_STRUCT: 3912 return emitFieldInitializer(Field, Field.Contents.StructInfo, 3913 Initializer.StructInfo); 3914 } 3915 llvm_unreachable("Unhandled FieldType enum"); 3916 } 3917 3918 bool MasmParser::emitStructInitializer(const StructInfo &Structure, 3919 const StructInitializer &Initializer) { 3920 size_t Index = 0, Offset = 0; 3921 for (const auto &Init : Initializer.FieldInitializers) { 3922 const auto &Field = Structure.Fields[Index++]; 3923 getStreamer().emitZeros(Field.Offset - Offset); 3924 Offset = Field.Offset + Field.SizeOf; 3925 if (emitFieldInitializer(Field, Init)) 3926 return true; 3927 } 3928 // Default-initialize all remaining fields. 3929 for (auto It = 3930 Structure.Fields.begin() + Initializer.FieldInitializers.size(); 3931 It != Structure.Fields.end(); ++It) { 3932 const auto &Field = *It; 3933 getStreamer().emitZeros(Field.Offset - Offset); 3934 Offset = Field.Offset + Field.SizeOf; 3935 if (emitFieldValue(Field)) 3936 return true; 3937 } 3938 // Add final padding. 3939 if (Offset != Structure.Size) 3940 getStreamer().emitZeros(Structure.Size - Offset); 3941 return false; 3942 } 3943 3944 // Set data values from initializers. 3945 bool MasmParser::emitStructValues(const StructInfo &Structure, 3946 unsigned *Count) { 3947 std::vector<StructInitializer> Initializers; 3948 if (parseStructInstList(Structure, Initializers)) 3949 return true; 3950 3951 for (const auto &Initializer : Initializers) { 3952 if (emitStructInitializer(Structure, Initializer)) 3953 return true; 3954 } 3955 3956 if (Count) 3957 *Count = Initializers.size(); 3958 return false; 3959 } 3960 3961 // Declare a field in the current struct. 3962 bool MasmParser::addStructField(StringRef Name, const StructInfo &Structure) { 3963 StructInfo &OwningStruct = StructInProgress.back(); 3964 FieldInfo &Field = 3965 OwningStruct.addField(Name, FT_STRUCT, Structure.AlignmentSize); 3966 StructFieldInfo &StructInfo = Field.Contents.StructInfo; 3967 3968 StructInfo.Structure = Structure; 3969 Field.Type = Structure.Size; 3970 3971 if (parseStructInstList(Structure, StructInfo.Initializers)) 3972 return true; 3973 3974 Field.LengthOf = StructInfo.Initializers.size(); 3975 Field.SizeOf = Field.Type * Field.LengthOf; 3976 if (OwningStruct.IsUnion) 3977 OwningStruct.Size = std::max(OwningStruct.Size, Field.SizeOf); 3978 else 3979 OwningStruct.Size += Field.SizeOf; 3980 3981 return false; 3982 } 3983 3984 /// parseDirectiveStructValue 3985 /// ::= struct-id (<struct-initializer> | {struct-initializer}) 3986 /// [, (<struct-initializer> | {struct-initializer})]* 3987 bool MasmParser::parseDirectiveStructValue(const StructInfo &Structure, 3988 StringRef Directive, SMLoc DirLoc) { 3989 if (StructInProgress.empty()) { 3990 if (emitStructValues(Structure)) 3991 return true; 3992 } else if (addStructField("", Structure)) { 3993 return addErrorSuffix(" in '" + Twine(Directive) + "' directive"); 3994 } 3995 3996 return false; 3997 } 3998 3999 /// parseDirectiveNamedValue 4000 /// ::= name (byte | word | ... ) [ expression (, expression)* ] 4001 bool MasmParser::parseDirectiveNamedStructValue(const StructInfo &Structure, 4002 StringRef Directive, 4003 SMLoc DirLoc, StringRef Name) { 4004 if (StructInProgress.empty()) { 4005 // Initialize named data value. 4006 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 4007 getStreamer().emitLabel(Sym); 4008 unsigned Count; 4009 if (emitStructValues(Structure, &Count)) 4010 return true; 4011 AsmTypeInfo Type; 4012 Type.Name = Structure.Name; 4013 Type.Size = Structure.Size * Count; 4014 Type.ElementSize = Structure.Size; 4015 Type.Length = Count; 4016 KnownType[Name.lower()] = Type; 4017 } else if (addStructField(Name, Structure)) { 4018 return addErrorSuffix(" in '" + Twine(Directive) + "' directive"); 4019 } 4020 4021 return false; 4022 } 4023 4024 /// parseDirectiveStruct 4025 /// ::= <name> (STRUC | STRUCT | UNION) [fieldAlign] [, NONUNIQUE] 4026 /// (dataDir | generalDir | offsetDir | nestedStruct)+ 4027 /// <name> ENDS 4028 ////// dataDir = data declaration 4029 ////// offsetDir = EVEN, ORG, ALIGN 4030 bool MasmParser::parseDirectiveStruct(StringRef Directive, 4031 DirectiveKind DirKind, StringRef Name, 4032 SMLoc NameLoc) { 4033 // We ignore NONUNIQUE; we do not support OPTION M510 or OPTION OLDSTRUCTS 4034 // anyway, so all field accesses must be qualified. 4035 AsmToken NextTok = getTok(); 4036 int64_t AlignmentValue = 1; 4037 if (NextTok.isNot(AsmToken::Comma) && 4038 NextTok.isNot(AsmToken::EndOfStatement) && 4039 parseAbsoluteExpression(AlignmentValue)) { 4040 return addErrorSuffix(" in alignment value for '" + Twine(Directive) + 4041 "' directive"); 4042 } 4043 if (!isPowerOf2_64(AlignmentValue)) { 4044 return Error(NextTok.getLoc(), "alignment must be a power of two; was " + 4045 std::to_string(AlignmentValue)); 4046 } 4047 4048 StringRef Qualifier; 4049 SMLoc QualifierLoc; 4050 if (parseOptionalToken(AsmToken::Comma)) { 4051 QualifierLoc = getTok().getLoc(); 4052 if (parseIdentifier(Qualifier)) 4053 return addErrorSuffix(" in '" + Twine(Directive) + "' directive"); 4054 if (!Qualifier.equals_lower("nonunique")) 4055 return Error(QualifierLoc, "Unrecognized qualifier for '" + 4056 Twine(Directive) + 4057 "' directive; expected none or NONUNIQUE"); 4058 } 4059 4060 if (parseToken(AsmToken::EndOfStatement)) 4061 return addErrorSuffix(" in '" + Twine(Directive) + "' directive"); 4062 4063 StructInProgress.emplace_back(Name, DirKind == DK_UNION, AlignmentValue); 4064 return false; 4065 } 4066 4067 /// parseDirectiveNestedStruct 4068 /// ::= (STRUC | STRUCT | UNION) [name] 4069 /// (dataDir | generalDir | offsetDir | nestedStruct)+ 4070 /// ENDS 4071 bool MasmParser::parseDirectiveNestedStruct(StringRef Directive, 4072 DirectiveKind DirKind) { 4073 if (StructInProgress.empty()) 4074 return TokError("missing name in top-level '" + Twine(Directive) + 4075 "' directive"); 4076 4077 StringRef Name; 4078 if (getTok().is(AsmToken::Identifier)) { 4079 Name = getTok().getIdentifier(); 4080 parseToken(AsmToken::Identifier); 4081 } 4082 if (parseToken(AsmToken::EndOfStatement)) 4083 return addErrorSuffix(" in '" + Twine(Directive) + "' directive"); 4084 4085 StructInProgress.emplace_back(Name, DirKind == DK_UNION, 4086 StructInProgress.back().Alignment); 4087 return false; 4088 } 4089 4090 bool MasmParser::parseDirectiveEnds(StringRef Name, SMLoc NameLoc) { 4091 if (StructInProgress.empty()) 4092 return Error(NameLoc, "ENDS directive without matching STRUC/STRUCT/UNION"); 4093 if (StructInProgress.size() > 1) 4094 return Error(NameLoc, "unexpected name in nested ENDS directive"); 4095 if (StructInProgress.back().Name.compare_lower(Name)) 4096 return Error(NameLoc, "mismatched name in ENDS directive; expected '" + 4097 StructInProgress.back().Name + "'"); 4098 StructInfo Structure = StructInProgress.pop_back_val(); 4099 // Pad to make the structure's size divisible by the smaller of its alignment 4100 // and the size of its largest field. 4101 Structure.Size = llvm::alignTo( 4102 Structure.Size, std::min(Structure.Alignment, Structure.AlignmentSize)); 4103 Structs[Name.lower()] = Structure; 4104 4105 if (parseToken(AsmToken::EndOfStatement)) 4106 return addErrorSuffix(" in ENDS directive"); 4107 4108 return false; 4109 } 4110 4111 bool MasmParser::parseDirectiveNestedEnds() { 4112 if (StructInProgress.empty()) 4113 return TokError("ENDS directive without matching STRUC/STRUCT/UNION"); 4114 if (StructInProgress.size() == 1) 4115 return TokError("missing name in top-level ENDS directive"); 4116 4117 if (parseToken(AsmToken::EndOfStatement)) 4118 return addErrorSuffix(" in nested ENDS directive"); 4119 4120 StructInfo Structure = StructInProgress.pop_back_val(); 4121 // Pad to make the structure's size divisible by its alignment. 4122 Structure.Size = llvm::alignTo(Structure.Size, Structure.Alignment); 4123 4124 StructInfo &ParentStruct = StructInProgress.back(); 4125 if (Structure.Name.empty()) { 4126 const size_t OldFields = ParentStruct.Fields.size(); 4127 ParentStruct.Fields.insert( 4128 ParentStruct.Fields.end(), 4129 std::make_move_iterator(Structure.Fields.begin()), 4130 std::make_move_iterator(Structure.Fields.end())); 4131 for (const auto &FieldByName : Structure.FieldsByName) { 4132 ParentStruct.FieldsByName[FieldByName.getKey()] = 4133 FieldByName.getValue() + OldFields; 4134 } 4135 if (!ParentStruct.IsUnion) { 4136 for (auto FieldIter = ParentStruct.Fields.begin() + OldFields; 4137 FieldIter != ParentStruct.Fields.end(); ++FieldIter) { 4138 FieldIter->Offset += ParentStruct.Size; 4139 } 4140 } 4141 4142 if (ParentStruct.IsUnion) 4143 ParentStruct.Size = std::max(ParentStruct.Size, Structure.Size); 4144 else 4145 ParentStruct.Size += Structure.Size; 4146 } else { 4147 FieldInfo &Field = ParentStruct.addField(Structure.Name, FT_STRUCT, 4148 Structure.AlignmentSize); 4149 StructFieldInfo &StructInfo = Field.Contents.StructInfo; 4150 Field.Type = Structure.Size; 4151 Field.LengthOf = 1; 4152 Field.SizeOf = Structure.Size; 4153 4154 if (ParentStruct.IsUnion) 4155 ParentStruct.Size = std::max(ParentStruct.Size, Field.SizeOf); 4156 else 4157 ParentStruct.Size += Field.SizeOf; 4158 4159 StructInfo.Structure = Structure; 4160 StructInfo.Initializers.emplace_back(); 4161 auto &FieldInitializers = StructInfo.Initializers.back().FieldInitializers; 4162 for (const auto &SubField : Structure.Fields) { 4163 FieldInitializers.push_back(SubField.Contents); 4164 } 4165 } 4166 4167 return false; 4168 } 4169 4170 /// parseDirectiveOrg 4171 /// ::= .org expression [ , expression ] 4172 bool MasmParser::parseDirectiveOrg() { 4173 const MCExpr *Offset; 4174 SMLoc OffsetLoc = Lexer.getLoc(); 4175 if (checkForValidSection() || parseExpression(Offset)) 4176 return true; 4177 4178 // Parse optional fill expression. 4179 int64_t FillExpr = 0; 4180 if (parseOptionalToken(AsmToken::Comma)) 4181 if (parseAbsoluteExpression(FillExpr)) 4182 return addErrorSuffix(" in '.org' directive"); 4183 if (parseToken(AsmToken::EndOfStatement)) 4184 return addErrorSuffix(" in '.org' directive"); 4185 4186 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc); 4187 return false; 4188 } 4189 4190 /// parseDirectiveAlign 4191 /// ::= align expression 4192 bool MasmParser::parseDirectiveAlign() { 4193 SMLoc AlignmentLoc = getLexer().getLoc(); 4194 int64_t Alignment; 4195 4196 if (checkForValidSection()) 4197 return addErrorSuffix(" in align directive"); 4198 // Ignore empty 'align' directives. 4199 if (getTok().is(AsmToken::EndOfStatement)) { 4200 Warning(AlignmentLoc, "align directive with no operand is ignored"); 4201 return parseToken(AsmToken::EndOfStatement); 4202 } 4203 if (parseAbsoluteExpression(Alignment) || 4204 parseToken(AsmToken::EndOfStatement)) 4205 return addErrorSuffix(" in align directive"); 4206 4207 // Always emit an alignment here even if we thrown an error. 4208 bool ReturnVal = false; 4209 4210 // Reject alignments that aren't either a power of two or zero, for gas 4211 // compatibility. Alignment of zero is silently rounded up to one. 4212 if (Alignment == 0) 4213 Alignment = 1; 4214 if (!isPowerOf2_64(Alignment)) 4215 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2"); 4216 4217 // Check whether we should use optimal code alignment for this align 4218 // directive. 4219 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 4220 assert(Section && "must have section to emit alignment"); 4221 if (Section->UseCodeAlign()) { 4222 getStreamer().emitCodeAlignment(Alignment, /*MaxBytesToEmit=*/0); 4223 } else { 4224 // FIXME: Target specific behavior about how the "extra" bytes are filled. 4225 getStreamer().emitValueToAlignment(Alignment, /*Value=*/0, /*ValueSize=*/1, 4226 /*MaxBytesToEmit=*/0); 4227 } 4228 4229 return ReturnVal; 4230 } 4231 4232 /// parseDirectiveFile 4233 /// ::= .file filename 4234 /// ::= .file number [directory] filename [md5 checksum] [source source-text] 4235 bool MasmParser::parseDirectiveFile(SMLoc DirectiveLoc) { 4236 // FIXME: I'm not sure what this is. 4237 int64_t FileNumber = -1; 4238 if (getLexer().is(AsmToken::Integer)) { 4239 FileNumber = getTok().getIntVal(); 4240 Lex(); 4241 4242 if (FileNumber < 0) 4243 return TokError("negative file number"); 4244 } 4245 4246 std::string Path; 4247 4248 // Usually the directory and filename together, otherwise just the directory. 4249 // Allow the strings to have escaped octal character sequence. 4250 if (check(getTok().isNot(AsmToken::String), 4251 "unexpected token in '.file' directive") || 4252 parseEscapedString(Path)) 4253 return true; 4254 4255 StringRef Directory; 4256 StringRef Filename; 4257 std::string FilenameData; 4258 if (getLexer().is(AsmToken::String)) { 4259 if (check(FileNumber == -1, 4260 "explicit path specified, but no file number") || 4261 parseEscapedString(FilenameData)) 4262 return true; 4263 Filename = FilenameData; 4264 Directory = Path; 4265 } else { 4266 Filename = Path; 4267 } 4268 4269 uint64_t MD5Hi, MD5Lo; 4270 bool HasMD5 = false; 4271 4272 Optional<StringRef> Source; 4273 bool HasSource = false; 4274 std::string SourceString; 4275 4276 while (!parseOptionalToken(AsmToken::EndOfStatement)) { 4277 StringRef Keyword; 4278 if (check(getTok().isNot(AsmToken::Identifier), 4279 "unexpected token in '.file' directive") || 4280 parseIdentifier(Keyword)) 4281 return true; 4282 if (Keyword == "md5") { 4283 HasMD5 = true; 4284 if (check(FileNumber == -1, 4285 "MD5 checksum specified, but no file number") || 4286 parseHexOcta(*this, MD5Hi, MD5Lo)) 4287 return true; 4288 } else if (Keyword == "source") { 4289 HasSource = true; 4290 if (check(FileNumber == -1, 4291 "source specified, but no file number") || 4292 check(getTok().isNot(AsmToken::String), 4293 "unexpected token in '.file' directive") || 4294 parseEscapedString(SourceString)) 4295 return true; 4296 } else { 4297 return TokError("unexpected token in '.file' directive"); 4298 } 4299 } 4300 4301 if (FileNumber == -1) { 4302 // Ignore the directive if there is no number and the target doesn't support 4303 // numberless .file directives. This allows some portability of assembler 4304 // between different object file formats. 4305 if (getContext().getAsmInfo()->hasSingleParameterDotFile()) 4306 getStreamer().emitFileDirective(Filename); 4307 } else { 4308 // In case there is a -g option as well as debug info from directive .file, 4309 // we turn off the -g option, directly use the existing debug info instead. 4310 // Throw away any implicit file table for the assembler source. 4311 if (Ctx.getGenDwarfForAssembly()) { 4312 Ctx.getMCDwarfLineTable(0).resetFileTable(); 4313 Ctx.setGenDwarfForAssembly(false); 4314 } 4315 4316 Optional<MD5::MD5Result> CKMem; 4317 if (HasMD5) { 4318 MD5::MD5Result Sum; 4319 for (unsigned i = 0; i != 8; ++i) { 4320 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8)); 4321 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8)); 4322 } 4323 CKMem = Sum; 4324 } 4325 if (HasSource) { 4326 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size())); 4327 memcpy(SourceBuf, SourceString.data(), SourceString.size()); 4328 Source = StringRef(SourceBuf, SourceString.size()); 4329 } 4330 if (FileNumber == 0) { 4331 if (Ctx.getDwarfVersion() < 5) 4332 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5"); 4333 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source); 4334 } else { 4335 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective( 4336 FileNumber, Directory, Filename, CKMem, Source); 4337 if (!FileNumOrErr) 4338 return Error(DirectiveLoc, toString(FileNumOrErr.takeError())); 4339 } 4340 // Alert the user if there are some .file directives with MD5 and some not. 4341 // But only do that once. 4342 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) { 4343 ReportedInconsistentMD5 = true; 4344 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums"); 4345 } 4346 } 4347 4348 return false; 4349 } 4350 4351 /// parseDirectiveLine 4352 /// ::= .line [number] 4353 bool MasmParser::parseDirectiveLine() { 4354 int64_t LineNumber; 4355 if (getLexer().is(AsmToken::Integer)) { 4356 if (parseIntToken(LineNumber, "unexpected token in '.line' directive")) 4357 return true; 4358 (void)LineNumber; 4359 // FIXME: Do something with the .line. 4360 } 4361 if (parseToken(AsmToken::EndOfStatement, 4362 "unexpected token in '.line' directive")) 4363 return true; 4364 4365 return false; 4366 } 4367 4368 /// parseDirectiveLoc 4369 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end] 4370 /// [epilogue_begin] [is_stmt VALUE] [isa VALUE] 4371 /// The first number is a file number, must have been previously assigned with 4372 /// a .file directive, the second number is the line number and optionally the 4373 /// third number is a column position (zero if not specified). The remaining 4374 /// optional items are .loc sub-directives. 4375 bool MasmParser::parseDirectiveLoc() { 4376 int64_t FileNumber = 0, LineNumber = 0; 4377 SMLoc Loc = getTok().getLoc(); 4378 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") || 4379 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc, 4380 "file number less than one in '.loc' directive") || 4381 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc, 4382 "unassigned file number in '.loc' directive")) 4383 return true; 4384 4385 // optional 4386 if (getLexer().is(AsmToken::Integer)) { 4387 LineNumber = getTok().getIntVal(); 4388 if (LineNumber < 0) 4389 return TokError("line number less than zero in '.loc' directive"); 4390 Lex(); 4391 } 4392 4393 int64_t ColumnPos = 0; 4394 if (getLexer().is(AsmToken::Integer)) { 4395 ColumnPos = getTok().getIntVal(); 4396 if (ColumnPos < 0) 4397 return TokError("column position less than zero in '.loc' directive"); 4398 Lex(); 4399 } 4400 4401 auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags(); 4402 unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT; 4403 unsigned Isa = 0; 4404 int64_t Discriminator = 0; 4405 4406 auto parseLocOp = [&]() -> bool { 4407 StringRef Name; 4408 SMLoc Loc = getTok().getLoc(); 4409 if (parseIdentifier(Name)) 4410 return TokError("unexpected token in '.loc' directive"); 4411 4412 if (Name == "basic_block") 4413 Flags |= DWARF2_FLAG_BASIC_BLOCK; 4414 else if (Name == "prologue_end") 4415 Flags |= DWARF2_FLAG_PROLOGUE_END; 4416 else if (Name == "epilogue_begin") 4417 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN; 4418 else if (Name == "is_stmt") { 4419 Loc = getTok().getLoc(); 4420 const MCExpr *Value; 4421 if (parseExpression(Value)) 4422 return true; 4423 // The expression must be the constant 0 or 1. 4424 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 4425 int Value = MCE->getValue(); 4426 if (Value == 0) 4427 Flags &= ~DWARF2_FLAG_IS_STMT; 4428 else if (Value == 1) 4429 Flags |= DWARF2_FLAG_IS_STMT; 4430 else 4431 return Error(Loc, "is_stmt value not 0 or 1"); 4432 } else { 4433 return Error(Loc, "is_stmt value not the constant value of 0 or 1"); 4434 } 4435 } else if (Name == "isa") { 4436 Loc = getTok().getLoc(); 4437 const MCExpr *Value; 4438 if (parseExpression(Value)) 4439 return true; 4440 // The expression must be a constant greater or equal to 0. 4441 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) { 4442 int Value = MCE->getValue(); 4443 if (Value < 0) 4444 return Error(Loc, "isa number less than zero"); 4445 Isa = Value; 4446 } else { 4447 return Error(Loc, "isa number not a constant value"); 4448 } 4449 } else if (Name == "discriminator") { 4450 if (parseAbsoluteExpression(Discriminator)) 4451 return true; 4452 } else { 4453 return Error(Loc, "unknown sub-directive in '.loc' directive"); 4454 } 4455 return false; 4456 }; 4457 4458 if (parseMany(parseLocOp, false /*hasComma*/)) 4459 return true; 4460 4461 getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags, 4462 Isa, Discriminator, StringRef()); 4463 4464 return false; 4465 } 4466 4467 /// parseDirectiveStabs 4468 /// ::= .stabs string, number, number, number 4469 bool MasmParser::parseDirectiveStabs() { 4470 return TokError("unsupported directive '.stabs'"); 4471 } 4472 4473 /// parseDirectiveCVFile 4474 /// ::= .cv_file number filename [checksum] [checksumkind] 4475 bool MasmParser::parseDirectiveCVFile() { 4476 SMLoc FileNumberLoc = getTok().getLoc(); 4477 int64_t FileNumber; 4478 std::string Filename; 4479 std::string Checksum; 4480 int64_t ChecksumKind = 0; 4481 4482 if (parseIntToken(FileNumber, 4483 "expected file number in '.cv_file' directive") || 4484 check(FileNumber < 1, FileNumberLoc, "file number less than one") || 4485 check(getTok().isNot(AsmToken::String), 4486 "unexpected token in '.cv_file' directive") || 4487 parseEscapedString(Filename)) 4488 return true; 4489 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4490 if (check(getTok().isNot(AsmToken::String), 4491 "unexpected token in '.cv_file' directive") || 4492 parseEscapedString(Checksum) || 4493 parseIntToken(ChecksumKind, 4494 "expected checksum kind in '.cv_file' directive") || 4495 parseToken(AsmToken::EndOfStatement, 4496 "unexpected token in '.cv_file' directive")) 4497 return true; 4498 } 4499 4500 Checksum = fromHex(Checksum); 4501 void *CKMem = Ctx.allocate(Checksum.size(), 1); 4502 memcpy(CKMem, Checksum.data(), Checksum.size()); 4503 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem), 4504 Checksum.size()); 4505 4506 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes, 4507 static_cast<uint8_t>(ChecksumKind))) 4508 return Error(FileNumberLoc, "file number already allocated"); 4509 4510 return false; 4511 } 4512 4513 bool MasmParser::parseCVFunctionId(int64_t &FunctionId, 4514 StringRef DirectiveName) { 4515 SMLoc Loc; 4516 return parseTokenLoc(Loc) || 4517 parseIntToken(FunctionId, "expected function id in '" + DirectiveName + 4518 "' directive") || 4519 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc, 4520 "expected function id within range [0, UINT_MAX)"); 4521 } 4522 4523 bool MasmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) { 4524 SMLoc Loc; 4525 return parseTokenLoc(Loc) || 4526 parseIntToken(FileNumber, "expected integer in '" + DirectiveName + 4527 "' directive") || 4528 check(FileNumber < 1, Loc, "file number less than one in '" + 4529 DirectiveName + "' directive") || 4530 check(!getCVContext().isValidFileNumber(FileNumber), Loc, 4531 "unassigned file number in '" + DirectiveName + "' directive"); 4532 } 4533 4534 /// parseDirectiveCVFuncId 4535 /// ::= .cv_func_id FunctionId 4536 /// 4537 /// Introduces a function ID that can be used with .cv_loc. 4538 bool MasmParser::parseDirectiveCVFuncId() { 4539 SMLoc FunctionIdLoc = getTok().getLoc(); 4540 int64_t FunctionId; 4541 4542 if (parseCVFunctionId(FunctionId, ".cv_func_id") || 4543 parseToken(AsmToken::EndOfStatement, 4544 "unexpected token in '.cv_func_id' directive")) 4545 return true; 4546 4547 if (!getStreamer().EmitCVFuncIdDirective(FunctionId)) 4548 return Error(FunctionIdLoc, "function id already allocated"); 4549 4550 return false; 4551 } 4552 4553 /// parseDirectiveCVInlineSiteId 4554 /// ::= .cv_inline_site_id FunctionId 4555 /// "within" IAFunc 4556 /// "inlined_at" IAFile IALine [IACol] 4557 /// 4558 /// Introduces a function ID that can be used with .cv_loc. Includes "inlined 4559 /// at" source location information for use in the line table of the caller, 4560 /// whether the caller is a real function or another inlined call site. 4561 bool MasmParser::parseDirectiveCVInlineSiteId() { 4562 SMLoc FunctionIdLoc = getTok().getLoc(); 4563 int64_t FunctionId; 4564 int64_t IAFunc; 4565 int64_t IAFile; 4566 int64_t IALine; 4567 int64_t IACol = 0; 4568 4569 // FunctionId 4570 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id")) 4571 return true; 4572 4573 // "within" 4574 if (check((getLexer().isNot(AsmToken::Identifier) || 4575 getTok().getIdentifier() != "within"), 4576 "expected 'within' identifier in '.cv_inline_site_id' directive")) 4577 return true; 4578 Lex(); 4579 4580 // IAFunc 4581 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id")) 4582 return true; 4583 4584 // "inlined_at" 4585 if (check((getLexer().isNot(AsmToken::Identifier) || 4586 getTok().getIdentifier() != "inlined_at"), 4587 "expected 'inlined_at' identifier in '.cv_inline_site_id' " 4588 "directive") ) 4589 return true; 4590 Lex(); 4591 4592 // IAFile IALine 4593 if (parseCVFileId(IAFile, ".cv_inline_site_id") || 4594 parseIntToken(IALine, "expected line number after 'inlined_at'")) 4595 return true; 4596 4597 // [IACol] 4598 if (getLexer().is(AsmToken::Integer)) { 4599 IACol = getTok().getIntVal(); 4600 Lex(); 4601 } 4602 4603 if (parseToken(AsmToken::EndOfStatement, 4604 "unexpected token in '.cv_inline_site_id' directive")) 4605 return true; 4606 4607 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile, 4608 IALine, IACol, FunctionIdLoc)) 4609 return Error(FunctionIdLoc, "function id already allocated"); 4610 4611 return false; 4612 } 4613 4614 /// parseDirectiveCVLoc 4615 /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end] 4616 /// [is_stmt VALUE] 4617 /// The first number is a file number, must have been previously assigned with 4618 /// a .file directive, the second number is the line number and optionally the 4619 /// third number is a column position (zero if not specified). The remaining 4620 /// optional items are .loc sub-directives. 4621 bool MasmParser::parseDirectiveCVLoc() { 4622 SMLoc DirectiveLoc = getTok().getLoc(); 4623 int64_t FunctionId, FileNumber; 4624 if (parseCVFunctionId(FunctionId, ".cv_loc") || 4625 parseCVFileId(FileNumber, ".cv_loc")) 4626 return true; 4627 4628 int64_t LineNumber = 0; 4629 if (getLexer().is(AsmToken::Integer)) { 4630 LineNumber = getTok().getIntVal(); 4631 if (LineNumber < 0) 4632 return TokError("line number less than zero in '.cv_loc' directive"); 4633 Lex(); 4634 } 4635 4636 int64_t ColumnPos = 0; 4637 if (getLexer().is(AsmToken::Integer)) { 4638 ColumnPos = getTok().getIntVal(); 4639 if (ColumnPos < 0) 4640 return TokError("column position less than zero in '.cv_loc' directive"); 4641 Lex(); 4642 } 4643 4644 bool PrologueEnd = false; 4645 uint64_t IsStmt = 0; 4646 4647 auto parseOp = [&]() -> bool { 4648 StringRef Name; 4649 SMLoc Loc = getTok().getLoc(); 4650 if (parseIdentifier(Name)) 4651 return TokError("unexpected token in '.cv_loc' directive"); 4652 if (Name == "prologue_end") 4653 PrologueEnd = true; 4654 else if (Name == "is_stmt") { 4655 Loc = getTok().getLoc(); 4656 const MCExpr *Value; 4657 if (parseExpression(Value)) 4658 return true; 4659 // The expression must be the constant 0 or 1. 4660 IsStmt = ~0ULL; 4661 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) 4662 IsStmt = MCE->getValue(); 4663 4664 if (IsStmt > 1) 4665 return Error(Loc, "is_stmt value not 0 or 1"); 4666 } else { 4667 return Error(Loc, "unknown sub-directive in '.cv_loc' directive"); 4668 } 4669 return false; 4670 }; 4671 4672 if (parseMany(parseOp, false /*hasComma*/)) 4673 return true; 4674 4675 getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber, 4676 ColumnPos, PrologueEnd, IsStmt, StringRef(), 4677 DirectiveLoc); 4678 return false; 4679 } 4680 4681 /// parseDirectiveCVLinetable 4682 /// ::= .cv_linetable FunctionId, FnStart, FnEnd 4683 bool MasmParser::parseDirectiveCVLinetable() { 4684 int64_t FunctionId; 4685 StringRef FnStartName, FnEndName; 4686 SMLoc Loc = getTok().getLoc(); 4687 if (parseCVFunctionId(FunctionId, ".cv_linetable") || 4688 parseToken(AsmToken::Comma, 4689 "unexpected token in '.cv_linetable' directive") || 4690 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 4691 "expected identifier in directive") || 4692 parseToken(AsmToken::Comma, 4693 "unexpected token in '.cv_linetable' directive") || 4694 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 4695 "expected identifier in directive")) 4696 return true; 4697 4698 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 4699 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 4700 4701 getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym); 4702 return false; 4703 } 4704 4705 /// parseDirectiveCVInlineLinetable 4706 /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd 4707 bool MasmParser::parseDirectiveCVInlineLinetable() { 4708 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum; 4709 StringRef FnStartName, FnEndName; 4710 SMLoc Loc = getTok().getLoc(); 4711 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") || 4712 parseTokenLoc(Loc) || 4713 parseIntToken( 4714 SourceFileId, 4715 "expected SourceField in '.cv_inline_linetable' directive") || 4716 check(SourceFileId <= 0, Loc, 4717 "File id less than zero in '.cv_inline_linetable' directive") || 4718 parseTokenLoc(Loc) || 4719 parseIntToken( 4720 SourceLineNum, 4721 "expected SourceLineNum in '.cv_inline_linetable' directive") || 4722 check(SourceLineNum < 0, Loc, 4723 "Line number less than zero in '.cv_inline_linetable' directive") || 4724 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc, 4725 "expected identifier in directive") || 4726 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc, 4727 "expected identifier in directive")) 4728 return true; 4729 4730 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 4731 return true; 4732 4733 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName); 4734 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName); 4735 getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId, 4736 SourceLineNum, FnStartSym, 4737 FnEndSym); 4738 return false; 4739 } 4740 4741 void MasmParser::initializeCVDefRangeTypeMap() { 4742 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER; 4743 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL; 4744 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER; 4745 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL; 4746 } 4747 4748 /// parseDirectiveCVDefRange 4749 /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes* 4750 bool MasmParser::parseDirectiveCVDefRange() { 4751 SMLoc Loc; 4752 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges; 4753 while (getLexer().is(AsmToken::Identifier)) { 4754 Loc = getLexer().getLoc(); 4755 StringRef GapStartName; 4756 if (parseIdentifier(GapStartName)) 4757 return Error(Loc, "expected identifier in directive"); 4758 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName); 4759 4760 Loc = getLexer().getLoc(); 4761 StringRef GapEndName; 4762 if (parseIdentifier(GapEndName)) 4763 return Error(Loc, "expected identifier in directive"); 4764 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName); 4765 4766 Ranges.push_back({GapStartSym, GapEndSym}); 4767 } 4768 4769 StringRef CVDefRangeTypeStr; 4770 if (parseToken( 4771 AsmToken::Comma, 4772 "expected comma before def_range type in .cv_def_range directive") || 4773 parseIdentifier(CVDefRangeTypeStr)) 4774 return Error(Loc, "expected def_range type in directive"); 4775 4776 StringMap<CVDefRangeType>::const_iterator CVTypeIt = 4777 CVDefRangeTypeMap.find(CVDefRangeTypeStr); 4778 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end()) 4779 ? CVDR_DEFRANGE 4780 : CVTypeIt->getValue(); 4781 switch (CVDRType) { 4782 case CVDR_DEFRANGE_REGISTER: { 4783 int64_t DRRegister; 4784 if (parseToken(AsmToken::Comma, "expected comma before register number in " 4785 ".cv_def_range directive") || 4786 parseAbsoluteExpression(DRRegister)) 4787 return Error(Loc, "expected register number"); 4788 4789 codeview::DefRangeRegisterHeader DRHdr; 4790 DRHdr.Register = DRRegister; 4791 DRHdr.MayHaveNoName = 0; 4792 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 4793 break; 4794 } 4795 case CVDR_DEFRANGE_FRAMEPOINTER_REL: { 4796 int64_t DROffset; 4797 if (parseToken(AsmToken::Comma, 4798 "expected comma before offset in .cv_def_range directive") || 4799 parseAbsoluteExpression(DROffset)) 4800 return Error(Loc, "expected offset value"); 4801 4802 codeview::DefRangeFramePointerRelHeader DRHdr; 4803 DRHdr.Offset = DROffset; 4804 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 4805 break; 4806 } 4807 case CVDR_DEFRANGE_SUBFIELD_REGISTER: { 4808 int64_t DRRegister; 4809 int64_t DROffsetInParent; 4810 if (parseToken(AsmToken::Comma, "expected comma before register number in " 4811 ".cv_def_range directive") || 4812 parseAbsoluteExpression(DRRegister)) 4813 return Error(Loc, "expected register number"); 4814 if (parseToken(AsmToken::Comma, 4815 "expected comma before offset in .cv_def_range directive") || 4816 parseAbsoluteExpression(DROffsetInParent)) 4817 return Error(Loc, "expected offset value"); 4818 4819 codeview::DefRangeSubfieldRegisterHeader DRHdr; 4820 DRHdr.Register = DRRegister; 4821 DRHdr.MayHaveNoName = 0; 4822 DRHdr.OffsetInParent = DROffsetInParent; 4823 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 4824 break; 4825 } 4826 case CVDR_DEFRANGE_REGISTER_REL: { 4827 int64_t DRRegister; 4828 int64_t DRFlags; 4829 int64_t DRBasePointerOffset; 4830 if (parseToken(AsmToken::Comma, "expected comma before register number in " 4831 ".cv_def_range directive") || 4832 parseAbsoluteExpression(DRRegister)) 4833 return Error(Loc, "expected register value"); 4834 if (parseToken( 4835 AsmToken::Comma, 4836 "expected comma before flag value in .cv_def_range directive") || 4837 parseAbsoluteExpression(DRFlags)) 4838 return Error(Loc, "expected flag value"); 4839 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset " 4840 "in .cv_def_range directive") || 4841 parseAbsoluteExpression(DRBasePointerOffset)) 4842 return Error(Loc, "expected base pointer offset value"); 4843 4844 codeview::DefRangeRegisterRelHeader DRHdr; 4845 DRHdr.Register = DRRegister; 4846 DRHdr.Flags = DRFlags; 4847 DRHdr.BasePointerOffset = DRBasePointerOffset; 4848 getStreamer().emitCVDefRangeDirective(Ranges, DRHdr); 4849 break; 4850 } 4851 default: 4852 return Error(Loc, "unexpected def_range type in .cv_def_range directive"); 4853 } 4854 return true; 4855 } 4856 4857 /// parseDirectiveCVString 4858 /// ::= .cv_stringtable "string" 4859 bool MasmParser::parseDirectiveCVString() { 4860 std::string Data; 4861 if (checkForValidSection() || parseEscapedString(Data)) 4862 return addErrorSuffix(" in '.cv_string' directive"); 4863 4864 // Put the string in the table and emit the offset. 4865 std::pair<StringRef, unsigned> Insertion = 4866 getCVContext().addToStringTable(Data); 4867 getStreamer().emitIntValue(Insertion.second, 4); 4868 return false; 4869 } 4870 4871 /// parseDirectiveCVStringTable 4872 /// ::= .cv_stringtable 4873 bool MasmParser::parseDirectiveCVStringTable() { 4874 getStreamer().emitCVStringTableDirective(); 4875 return false; 4876 } 4877 4878 /// parseDirectiveCVFileChecksums 4879 /// ::= .cv_filechecksums 4880 bool MasmParser::parseDirectiveCVFileChecksums() { 4881 getStreamer().emitCVFileChecksumsDirective(); 4882 return false; 4883 } 4884 4885 /// parseDirectiveCVFileChecksumOffset 4886 /// ::= .cv_filechecksumoffset fileno 4887 bool MasmParser::parseDirectiveCVFileChecksumOffset() { 4888 int64_t FileNo; 4889 if (parseIntToken(FileNo, "expected identifier in directive")) 4890 return true; 4891 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement")) 4892 return true; 4893 getStreamer().emitCVFileChecksumOffsetDirective(FileNo); 4894 return false; 4895 } 4896 4897 /// parseDirectiveCVFPOData 4898 /// ::= .cv_fpo_data procsym 4899 bool MasmParser::parseDirectiveCVFPOData() { 4900 SMLoc DirLoc = getLexer().getLoc(); 4901 StringRef ProcName; 4902 if (parseIdentifier(ProcName)) 4903 return TokError("expected symbol name"); 4904 if (parseEOL("unexpected tokens")) 4905 return addErrorSuffix(" in '.cv_fpo_data' directive"); 4906 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName); 4907 getStreamer().EmitCVFPOData(ProcSym, DirLoc); 4908 return false; 4909 } 4910 4911 /// parseDirectiveCFISections 4912 /// ::= .cfi_sections section [, section] 4913 bool MasmParser::parseDirectiveCFISections() { 4914 StringRef Name; 4915 bool EH = false; 4916 bool Debug = false; 4917 4918 if (parseIdentifier(Name)) 4919 return TokError("Expected an identifier"); 4920 4921 if (Name == ".eh_frame") 4922 EH = true; 4923 else if (Name == ".debug_frame") 4924 Debug = true; 4925 4926 if (getLexer().is(AsmToken::Comma)) { 4927 Lex(); 4928 4929 if (parseIdentifier(Name)) 4930 return TokError("Expected an identifier"); 4931 4932 if (Name == ".eh_frame") 4933 EH = true; 4934 else if (Name == ".debug_frame") 4935 Debug = true; 4936 } 4937 4938 getStreamer().emitCFISections(EH, Debug); 4939 return false; 4940 } 4941 4942 /// parseDirectiveCFIStartProc 4943 /// ::= .cfi_startproc [simple] 4944 bool MasmParser::parseDirectiveCFIStartProc() { 4945 StringRef Simple; 4946 if (!parseOptionalToken(AsmToken::EndOfStatement)) { 4947 if (check(parseIdentifier(Simple) || Simple != "simple", 4948 "unexpected token") || 4949 parseToken(AsmToken::EndOfStatement)) 4950 return addErrorSuffix(" in '.cfi_startproc' directive"); 4951 } 4952 4953 // TODO(kristina): Deal with a corner case of incorrect diagnostic context 4954 // being produced if this directive is emitted as part of preprocessor macro 4955 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer. 4956 // Tools like llvm-mc on the other hand are not affected by it, and report 4957 // correct context information. 4958 getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc()); 4959 return false; 4960 } 4961 4962 /// parseDirectiveCFIEndProc 4963 /// ::= .cfi_endproc 4964 bool MasmParser::parseDirectiveCFIEndProc() { 4965 getStreamer().emitCFIEndProc(); 4966 return false; 4967 } 4968 4969 /// parse register name or number. 4970 bool MasmParser::parseRegisterOrRegisterNumber(int64_t &Register, 4971 SMLoc DirectiveLoc) { 4972 unsigned RegNo; 4973 4974 if (getLexer().isNot(AsmToken::Integer)) { 4975 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc)) 4976 return true; 4977 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true); 4978 } else 4979 return parseAbsoluteExpression(Register); 4980 4981 return false; 4982 } 4983 4984 /// parseDirectiveCFIDefCfa 4985 /// ::= .cfi_def_cfa register, offset 4986 bool MasmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) { 4987 int64_t Register = 0, Offset = 0; 4988 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 4989 parseToken(AsmToken::Comma, "unexpected token in directive") || 4990 parseAbsoluteExpression(Offset)) 4991 return true; 4992 4993 getStreamer().emitCFIDefCfa(Register, Offset); 4994 return false; 4995 } 4996 4997 /// parseDirectiveCFIDefCfaOffset 4998 /// ::= .cfi_def_cfa_offset offset 4999 bool MasmParser::parseDirectiveCFIDefCfaOffset() { 5000 int64_t Offset = 0; 5001 if (parseAbsoluteExpression(Offset)) 5002 return true; 5003 5004 getStreamer().emitCFIDefCfaOffset(Offset); 5005 return false; 5006 } 5007 5008 /// parseDirectiveCFIRegister 5009 /// ::= .cfi_register register, register 5010 bool MasmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) { 5011 int64_t Register1 = 0, Register2 = 0; 5012 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || 5013 parseToken(AsmToken::Comma, "unexpected token in directive") || 5014 parseRegisterOrRegisterNumber(Register2, DirectiveLoc)) 5015 return true; 5016 5017 getStreamer().emitCFIRegister(Register1, Register2); 5018 return false; 5019 } 5020 5021 /// parseDirectiveCFIWindowSave 5022 /// ::= .cfi_window_save 5023 bool MasmParser::parseDirectiveCFIWindowSave() { 5024 getStreamer().emitCFIWindowSave(); 5025 return false; 5026 } 5027 5028 /// parseDirectiveCFIAdjustCfaOffset 5029 /// ::= .cfi_adjust_cfa_offset adjustment 5030 bool MasmParser::parseDirectiveCFIAdjustCfaOffset() { 5031 int64_t Adjustment = 0; 5032 if (parseAbsoluteExpression(Adjustment)) 5033 return true; 5034 5035 getStreamer().emitCFIAdjustCfaOffset(Adjustment); 5036 return false; 5037 } 5038 5039 /// parseDirectiveCFIDefCfaRegister 5040 /// ::= .cfi_def_cfa_register register 5041 bool MasmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) { 5042 int64_t Register = 0; 5043 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 5044 return true; 5045 5046 getStreamer().emitCFIDefCfaRegister(Register); 5047 return false; 5048 } 5049 5050 /// parseDirectiveCFIOffset 5051 /// ::= .cfi_offset register, offset 5052 bool MasmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) { 5053 int64_t Register = 0; 5054 int64_t Offset = 0; 5055 5056 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 5057 parseToken(AsmToken::Comma, "unexpected token in directive") || 5058 parseAbsoluteExpression(Offset)) 5059 return true; 5060 5061 getStreamer().emitCFIOffset(Register, Offset); 5062 return false; 5063 } 5064 5065 /// parseDirectiveCFIRelOffset 5066 /// ::= .cfi_rel_offset register, offset 5067 bool MasmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) { 5068 int64_t Register = 0, Offset = 0; 5069 5070 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || 5071 parseToken(AsmToken::Comma, "unexpected token in directive") || 5072 parseAbsoluteExpression(Offset)) 5073 return true; 5074 5075 getStreamer().emitCFIRelOffset(Register, Offset); 5076 return false; 5077 } 5078 5079 static bool isValidEncoding(int64_t Encoding) { 5080 if (Encoding & ~0xff) 5081 return false; 5082 5083 if (Encoding == dwarf::DW_EH_PE_omit) 5084 return true; 5085 5086 const unsigned Format = Encoding & 0xf; 5087 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 && 5088 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 && 5089 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 && 5090 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed) 5091 return false; 5092 5093 const unsigned Application = Encoding & 0x70; 5094 if (Application != dwarf::DW_EH_PE_absptr && 5095 Application != dwarf::DW_EH_PE_pcrel) 5096 return false; 5097 5098 return true; 5099 } 5100 5101 /// parseDirectiveCFIPersonalityOrLsda 5102 /// IsPersonality true for cfi_personality, false for cfi_lsda 5103 /// ::= .cfi_personality encoding, [symbol_name] 5104 /// ::= .cfi_lsda encoding, [symbol_name] 5105 bool MasmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) { 5106 int64_t Encoding = 0; 5107 if (parseAbsoluteExpression(Encoding)) 5108 return true; 5109 if (Encoding == dwarf::DW_EH_PE_omit) 5110 return false; 5111 5112 StringRef Name; 5113 if (check(!isValidEncoding(Encoding), "unsupported encoding.") || 5114 parseToken(AsmToken::Comma, "unexpected token in directive") || 5115 check(parseIdentifier(Name), "expected identifier in directive")) 5116 return true; 5117 5118 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 5119 5120 if (IsPersonality) 5121 getStreamer().emitCFIPersonality(Sym, Encoding); 5122 else 5123 getStreamer().emitCFILsda(Sym, Encoding); 5124 return false; 5125 } 5126 5127 /// parseDirectiveCFIRememberState 5128 /// ::= .cfi_remember_state 5129 bool MasmParser::parseDirectiveCFIRememberState() { 5130 getStreamer().emitCFIRememberState(); 5131 return false; 5132 } 5133 5134 /// parseDirectiveCFIRestoreState 5135 /// ::= .cfi_remember_state 5136 bool MasmParser::parseDirectiveCFIRestoreState() { 5137 getStreamer().emitCFIRestoreState(); 5138 return false; 5139 } 5140 5141 /// parseDirectiveCFISameValue 5142 /// ::= .cfi_same_value register 5143 bool MasmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) { 5144 int64_t Register = 0; 5145 5146 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 5147 return true; 5148 5149 getStreamer().emitCFISameValue(Register); 5150 return false; 5151 } 5152 5153 /// parseDirectiveCFIRestore 5154 /// ::= .cfi_restore register 5155 bool MasmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) { 5156 int64_t Register = 0; 5157 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 5158 return true; 5159 5160 getStreamer().emitCFIRestore(Register); 5161 return false; 5162 } 5163 5164 /// parseDirectiveCFIEscape 5165 /// ::= .cfi_escape expression[,...] 5166 bool MasmParser::parseDirectiveCFIEscape() { 5167 std::string Values; 5168 int64_t CurrValue; 5169 if (parseAbsoluteExpression(CurrValue)) 5170 return true; 5171 5172 Values.push_back((uint8_t)CurrValue); 5173 5174 while (getLexer().is(AsmToken::Comma)) { 5175 Lex(); 5176 5177 if (parseAbsoluteExpression(CurrValue)) 5178 return true; 5179 5180 Values.push_back((uint8_t)CurrValue); 5181 } 5182 5183 getStreamer().emitCFIEscape(Values); 5184 return false; 5185 } 5186 5187 /// parseDirectiveCFIReturnColumn 5188 /// ::= .cfi_return_column register 5189 bool MasmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) { 5190 int64_t Register = 0; 5191 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 5192 return true; 5193 getStreamer().emitCFIReturnColumn(Register); 5194 return false; 5195 } 5196 5197 /// parseDirectiveCFISignalFrame 5198 /// ::= .cfi_signal_frame 5199 bool MasmParser::parseDirectiveCFISignalFrame() { 5200 if (parseToken(AsmToken::EndOfStatement, 5201 "unexpected token in '.cfi_signal_frame'")) 5202 return true; 5203 5204 getStreamer().emitCFISignalFrame(); 5205 return false; 5206 } 5207 5208 /// parseDirectiveCFIUndefined 5209 /// ::= .cfi_undefined register 5210 bool MasmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) { 5211 int64_t Register = 0; 5212 5213 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc)) 5214 return true; 5215 5216 getStreamer().emitCFIUndefined(Register); 5217 return false; 5218 } 5219 5220 /// parseDirectiveMacro 5221 /// ::= name macro [parameters] 5222 /// ["LOCAL" identifiers] 5223 /// parameters ::= parameter [, parameter]* 5224 /// parameter ::= name ":" qualifier 5225 /// qualifier ::= "req" | "vararg" | "=" macro_argument 5226 bool MasmParser::parseDirectiveMacro(StringRef Name, SMLoc NameLoc) { 5227 MCAsmMacroParameters Parameters; 5228 while (getLexer().isNot(AsmToken::EndOfStatement)) { 5229 if (!Parameters.empty() && Parameters.back().Vararg) 5230 return Error(Lexer.getLoc(), 5231 "Vararg parameter '" + Parameters.back().Name + 5232 "' should be last in the list of parameters"); 5233 5234 MCAsmMacroParameter Parameter; 5235 if (parseIdentifier(Parameter.Name)) 5236 return TokError("expected identifier in 'macro' directive"); 5237 5238 // Emit an error if two (or more) named parameters share the same name. 5239 for (const MCAsmMacroParameter& CurrParam : Parameters) 5240 if (CurrParam.Name.equals_lower(Parameter.Name)) 5241 return TokError("macro '" + Name + "' has multiple parameters" 5242 " named '" + Parameter.Name + "'"); 5243 5244 if (Lexer.is(AsmToken::Colon)) { 5245 Lex(); // consume ':' 5246 5247 if (parseOptionalToken(AsmToken::Equal)) { 5248 // Default value 5249 SMLoc ParamLoc; 5250 5251 ParamLoc = Lexer.getLoc(); 5252 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false)) 5253 return true; 5254 } else { 5255 SMLoc QualLoc; 5256 StringRef Qualifier; 5257 5258 QualLoc = Lexer.getLoc(); 5259 if (parseIdentifier(Qualifier)) 5260 return Error(QualLoc, "missing parameter qualifier for " 5261 "'" + 5262 Parameter.Name + "' in macro '" + Name + 5263 "'"); 5264 5265 if (Qualifier.equals_lower("req")) 5266 Parameter.Required = true; 5267 else if (Qualifier.equals_lower("vararg")) 5268 Parameter.Vararg = true; 5269 else 5270 return Error(QualLoc, 5271 Qualifier + " is not a valid parameter qualifier for '" + 5272 Parameter.Name + "' in macro '" + Name + "'"); 5273 } 5274 } 5275 5276 Parameters.push_back(std::move(Parameter)); 5277 5278 if (getLexer().is(AsmToken::Comma)) 5279 Lex(); 5280 } 5281 5282 // Eat just the end of statement. 5283 Lexer.Lex(); 5284 5285 std::vector<std::string> Locals; 5286 if (getTok().is(AsmToken::Identifier) && 5287 getTok().getIdentifier().equals_lower("local")) { 5288 Lex(); // Eat the LOCAL directive. 5289 5290 StringRef ID; 5291 while (true) { 5292 if (parseIdentifier(ID)) 5293 return true; 5294 Locals.push_back(ID.lower()); 5295 5296 // If we see a comma, continue (and allow line continuation). 5297 if (!parseOptionalToken(AsmToken::Comma)) 5298 break; 5299 parseOptionalToken(AsmToken::EndOfStatement); 5300 } 5301 } 5302 5303 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors. 5304 AsmToken EndToken, StartToken = getTok(); 5305 unsigned MacroDepth = 0; 5306 // Lex the macro definition. 5307 while (true) { 5308 // Ignore Lexing errors in macros. 5309 while (Lexer.is(AsmToken::Error)) { 5310 Lexer.Lex(); 5311 } 5312 5313 // Check whether we have reached the end of the file. 5314 if (getLexer().is(AsmToken::Eof)) 5315 return Error(NameLoc, "no matching 'endm' in definition"); 5316 5317 // Otherwise, check whether we have reach the 'endm'. 5318 if (getLexer().is(AsmToken::Identifier)) { 5319 if (getTok().getIdentifier().equals_lower("endm")) { 5320 if (MacroDepth == 0) { // Outermost macro. 5321 EndToken = getTok(); 5322 Lexer.Lex(); 5323 if (getLexer().isNot(AsmToken::EndOfStatement)) 5324 return TokError("unexpected token in '" + EndToken.getIdentifier() + 5325 "' directive"); 5326 break; 5327 } else { 5328 // Otherwise we just found the end of an inner macro. 5329 --MacroDepth; 5330 } 5331 } else { 5332 const AsmToken NextTok = getLexer().peekTok(); 5333 if (NextTok.is(AsmToken::Identifier) && 5334 NextTok.getIdentifier().equals_lower("macro")) { 5335 // We allow nested macros. Those aren't instantiated until the 5336 // outermost macro is expanded so just ignore them for now. 5337 ++MacroDepth; 5338 } 5339 } 5340 } 5341 5342 // Otherwise, scan til the end of the statement. 5343 eatToEndOfStatement(); 5344 } 5345 5346 if (getContext().lookupMacro(Name)) { 5347 return Error(NameLoc, "macro '" + Name + "' is already defined"); 5348 } 5349 5350 const char *BodyStart = StartToken.getLoc().getPointer(); 5351 const char *BodyEnd = EndToken.getLoc().getPointer(); 5352 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 5353 checkForBadMacro(NameLoc, Name, Body, Parameters); 5354 MCAsmMacro Macro(Name, Body, std::move(Parameters), std::move(Locals)); 5355 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n"; 5356 Macro.dump()); 5357 getContext().defineMacro(Name, std::move(Macro)); 5358 return false; 5359 } 5360 5361 /// checkForBadMacro 5362 /// 5363 /// With the support added for named parameters there may be code out there that 5364 /// is transitioning from positional parameters. In versions of gas that did 5365 /// not support named parameters they would be ignored on the macro definition. 5366 /// But to support both styles of parameters this is not possible so if a macro 5367 /// definition has named parameters but does not use them and has what appears 5368 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a 5369 /// warning that the positional parameter found in body which have no effect. 5370 /// Hoping the developer will either remove the named parameters from the macro 5371 /// definition so the positional parameters get used if that was what was 5372 /// intended or change the macro to use the named parameters. It is possible 5373 /// this warning will trigger when the none of the named parameters are used 5374 /// and the strings like $1 are infact to simply to be passed trough unchanged. 5375 void MasmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, 5376 StringRef Body, 5377 ArrayRef<MCAsmMacroParameter> Parameters) { 5378 // If this macro is not defined with named parameters the warning we are 5379 // checking for here doesn't apply. 5380 unsigned NParameters = Parameters.size(); 5381 if (NParameters == 0) 5382 return; 5383 5384 bool NamedParametersFound = false; 5385 bool PositionalParametersFound = false; 5386 5387 // Look at the body of the macro for use of both the named parameters and what 5388 // are likely to be positional parameters. This is what expandMacro() is 5389 // doing when it finds the parameters in the body. 5390 while (!Body.empty()) { 5391 // Scan for the next possible parameter. 5392 std::size_t End = Body.size(), Pos = 0; 5393 for (; Pos != End; ++Pos) { 5394 // Check for a substitution or escape. 5395 // This macro is defined with parameters, look for \foo, \bar, etc. 5396 if (Body[Pos] == '\\' && Pos + 1 != End) 5397 break; 5398 5399 // This macro should have parameters, but look for $0, $1, ..., $n too. 5400 if (Body[Pos] != '$' || Pos + 1 == End) 5401 continue; 5402 char Next = Body[Pos + 1]; 5403 if (Next == '$' || Next == 'n' || 5404 isdigit(static_cast<unsigned char>(Next))) 5405 break; 5406 } 5407 5408 // Check if we reached the end. 5409 if (Pos == End) 5410 break; 5411 5412 if (Body[Pos] == '$') { 5413 switch (Body[Pos + 1]) { 5414 // $$ => $ 5415 case '$': 5416 break; 5417 5418 // $n => number of arguments 5419 case 'n': 5420 PositionalParametersFound = true; 5421 break; 5422 5423 // $[0-9] => argument 5424 default: { 5425 PositionalParametersFound = true; 5426 break; 5427 } 5428 } 5429 Pos += 2; 5430 } else { 5431 unsigned I = Pos + 1; 5432 while (isIdentifierChar(Body[I]) && I + 1 != End) 5433 ++I; 5434 5435 const char *Begin = Body.data() + Pos + 1; 5436 StringRef Argument(Begin, I - (Pos + 1)); 5437 unsigned Index = 0; 5438 for (; Index < NParameters; ++Index) 5439 if (Parameters[Index].Name == Argument) 5440 break; 5441 5442 if (Index == NParameters) { 5443 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')') 5444 Pos += 3; 5445 else { 5446 Pos = I; 5447 } 5448 } else { 5449 NamedParametersFound = true; 5450 Pos += 1 + Argument.size(); 5451 } 5452 } 5453 // Update the scan point. 5454 Body = Body.substr(Pos); 5455 } 5456 5457 if (!NamedParametersFound && PositionalParametersFound) 5458 Warning(DirectiveLoc, "macro defined with named parameters which are not " 5459 "used in macro body, possible positional parameter " 5460 "found in body which will have no effect"); 5461 } 5462 5463 /// parseDirectiveExitMacro 5464 /// ::= exitm 5465 bool MasmParser::parseDirectiveExitMacro(StringRef Directive) { 5466 if (parseToken(AsmToken::EndOfStatement, 5467 "unexpected token in '" + Directive + "' directive")) 5468 return true; 5469 5470 if (!isInsideMacroInstantiation()) 5471 return TokError("unexpected '" + Directive + "' in file, " 5472 "no current macro definition"); 5473 5474 // Exit all conditionals that are active in the current macro. 5475 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) { 5476 TheCondState = TheCondStack.back(); 5477 TheCondStack.pop_back(); 5478 } 5479 5480 handleMacroExit(); 5481 return false; 5482 } 5483 5484 /// parseDirectiveEndMacro 5485 /// ::= .endm 5486 /// ::= .endmacro 5487 bool MasmParser::parseDirectiveEndMacro(StringRef Directive) { 5488 if (getLexer().isNot(AsmToken::EndOfStatement)) 5489 return TokError("unexpected token in '" + Directive + "' directive"); 5490 5491 // If we are inside a macro instantiation, terminate the current 5492 // instantiation. 5493 if (isInsideMacroInstantiation()) { 5494 handleMacroExit(); 5495 return false; 5496 } 5497 5498 // Otherwise, this .endmacro is a stray entry in the file; well formed 5499 // .endmacro directives are handled during the macro definition parsing. 5500 return TokError("unexpected '" + Directive + "' in file, " 5501 "no current macro definition"); 5502 } 5503 5504 /// parseDirectivePurgeMacro 5505 /// ::= .purgem 5506 bool MasmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) { 5507 StringRef Name; 5508 SMLoc Loc; 5509 if (parseTokenLoc(Loc) || 5510 check(parseIdentifier(Name), Loc, 5511 "expected identifier in '.purgem' directive") || 5512 parseToken(AsmToken::EndOfStatement, 5513 "unexpected token in '.purgem' directive")) 5514 return true; 5515 5516 if (!getContext().lookupMacro(Name)) 5517 return Error(DirectiveLoc, "macro '" + Name + "' is not defined"); 5518 5519 getContext().undefineMacro(Name); 5520 DEBUG_WITH_TYPE("asm-macros", dbgs() 5521 << "Un-defining macro: " << Name << "\n"); 5522 return false; 5523 } 5524 5525 /// parseDirectiveSymbolAttribute 5526 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ] 5527 bool MasmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) { 5528 auto parseOp = [&]() -> bool { 5529 StringRef Name; 5530 SMLoc Loc = getTok().getLoc(); 5531 if (parseIdentifier(Name)) 5532 return Error(Loc, "expected identifier"); 5533 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 5534 5535 // Assembler local symbols don't make any sense here. Complain loudly. 5536 if (Sym->isTemporary()) 5537 return Error(Loc, "non-local symbol required"); 5538 5539 if (!getStreamer().emitSymbolAttribute(Sym, Attr)) 5540 return Error(Loc, "unable to emit symbol attribute"); 5541 return false; 5542 }; 5543 5544 if (parseMany(parseOp)) 5545 return addErrorSuffix(" in directive"); 5546 return false; 5547 } 5548 5549 /// parseDirectiveComm 5550 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ] 5551 bool MasmParser::parseDirectiveComm(bool IsLocal) { 5552 if (checkForValidSection()) 5553 return true; 5554 5555 SMLoc IDLoc = getLexer().getLoc(); 5556 StringRef Name; 5557 if (parseIdentifier(Name)) 5558 return TokError("expected identifier in directive"); 5559 5560 // Handle the identifier as the key symbol. 5561 MCSymbol *Sym = getContext().getOrCreateSymbol(Name); 5562 5563 if (getLexer().isNot(AsmToken::Comma)) 5564 return TokError("unexpected token in directive"); 5565 Lex(); 5566 5567 int64_t Size; 5568 SMLoc SizeLoc = getLexer().getLoc(); 5569 if (parseAbsoluteExpression(Size)) 5570 return true; 5571 5572 int64_t Pow2Alignment = 0; 5573 SMLoc Pow2AlignmentLoc; 5574 if (getLexer().is(AsmToken::Comma)) { 5575 Lex(); 5576 Pow2AlignmentLoc = getLexer().getLoc(); 5577 if (parseAbsoluteExpression(Pow2Alignment)) 5578 return true; 5579 5580 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType(); 5581 if (IsLocal && LCOMM == LCOMM::NoAlignment) 5582 return Error(Pow2AlignmentLoc, "alignment not supported on this target"); 5583 5584 // If this target takes alignments in bytes (not log) validate and convert. 5585 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) || 5586 (IsLocal && LCOMM == LCOMM::ByteAlignment)) { 5587 if (!isPowerOf2_64(Pow2Alignment)) 5588 return Error(Pow2AlignmentLoc, "alignment must be a power of 2"); 5589 Pow2Alignment = Log2_64(Pow2Alignment); 5590 } 5591 } 5592 5593 if (parseToken(AsmToken::EndOfStatement, 5594 "unexpected token in '.comm' or '.lcomm' directive")) 5595 return true; 5596 5597 // NOTE: a size of zero for a .comm should create a undefined symbol 5598 // but a size of .lcomm creates a bss symbol of size zero. 5599 if (Size < 0) 5600 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't " 5601 "be less than zero"); 5602 5603 // NOTE: The alignment in the directive is a power of 2 value, the assembler 5604 // may internally end up wanting an alignment in bytes. 5605 // FIXME: Diagnose overflow. 5606 if (Pow2Alignment < 0) 5607 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive " 5608 "alignment, can't be less than zero"); 5609 5610 Sym->redefineIfPossible(); 5611 if (!Sym->isUndefined()) 5612 return Error(IDLoc, "invalid symbol redefinition"); 5613 5614 // Create the Symbol as a common or local common with Size and Pow2Alignment. 5615 if (IsLocal) { 5616 getStreamer().emitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment); 5617 return false; 5618 } 5619 5620 getStreamer().emitCommonSymbol(Sym, Size, 1 << Pow2Alignment); 5621 return false; 5622 } 5623 5624 /// parseDirectiveComment 5625 /// ::= comment delimiter [[text]] 5626 /// [[text]] 5627 /// [[text]] delimiter [[text]] 5628 bool MasmParser::parseDirectiveComment(SMLoc DirectiveLoc) { 5629 StringRef FirstLine = parseStringToEndOfStatement(); 5630 size_t DelimiterEnd = FirstLine.find_first_of("\b\t\v\f\r\x1A "); 5631 StringRef Delimiter = FirstLine.take_front(DelimiterEnd); 5632 if (Delimiter.empty()) 5633 return Error(DirectiveLoc, "no delimiter in 'comment' directive"); 5634 do { 5635 if (getTok().is(AsmToken::Eof)) 5636 return Error(DirectiveLoc, "unmatched delimiter in 'comment' directive"); 5637 Lex(); // eat end of statement 5638 } while (!parseStringToEndOfStatement().contains(Delimiter)); 5639 return parseToken(AsmToken::EndOfStatement, 5640 "unexpected token in 'comment' directive"); 5641 } 5642 5643 /// parseDirectiveInclude 5644 /// ::= include <filename> 5645 /// | include filename 5646 bool MasmParser::parseDirectiveInclude() { 5647 // Allow the strings to have escaped octal character sequence. 5648 std::string Filename; 5649 SMLoc IncludeLoc = getTok().getLoc(); 5650 5651 if (!parseAngleBracketString(Filename)) 5652 Filename = parseStringToEndOfStatement().str(); 5653 if (check(!Filename.empty(), "missing filename in 'include' directive") || 5654 check(getTok().isNot(AsmToken::EndOfStatement), 5655 "unexpected token in 'include' directive") || 5656 // Attempt to switch the lexer to the included file before consuming the 5657 // end of statement to avoid losing it when we switch. 5658 check(enterIncludeFile(Filename), IncludeLoc, 5659 "Could not find include file '" + Filename + "'")) 5660 return true; 5661 5662 return false; 5663 } 5664 5665 /// parseDirectiveIf 5666 /// ::= .if{,eq,ge,gt,le,lt,ne} expression 5667 bool MasmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) { 5668 TheCondStack.push_back(TheCondState); 5669 TheCondState.TheCond = AsmCond::IfCond; 5670 if (TheCondState.Ignore) { 5671 eatToEndOfStatement(); 5672 } else { 5673 int64_t ExprValue; 5674 if (parseAbsoluteExpression(ExprValue) || 5675 parseToken(AsmToken::EndOfStatement, 5676 "unexpected token in '.if' directive")) 5677 return true; 5678 5679 switch (DirKind) { 5680 default: 5681 llvm_unreachable("unsupported directive"); 5682 case DK_IF: 5683 break; 5684 case DK_IFE: 5685 ExprValue = ExprValue == 0; 5686 break; 5687 } 5688 5689 TheCondState.CondMet = ExprValue; 5690 TheCondState.Ignore = !TheCondState.CondMet; 5691 } 5692 5693 return false; 5694 } 5695 5696 /// parseDirectiveIfb 5697 /// ::= .ifb string 5698 bool MasmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 5699 TheCondStack.push_back(TheCondState); 5700 TheCondState.TheCond = AsmCond::IfCond; 5701 5702 if (TheCondState.Ignore) { 5703 eatToEndOfStatement(); 5704 } else { 5705 std::string Str; 5706 if (parseTextItem(Str)) 5707 return TokError("expected string parameter for 'ifb' directive"); 5708 5709 if (parseToken(AsmToken::EndOfStatement, 5710 "unexpected token in 'ifb' directive")) 5711 return true; 5712 5713 TheCondState.CondMet = ExpectBlank == Str.empty(); 5714 TheCondState.Ignore = !TheCondState.CondMet; 5715 } 5716 5717 return false; 5718 } 5719 5720 /// parseDirectiveIfidn 5721 /// ::= ifidn string1, string2 5722 bool MasmParser::parseDirectiveIfidn(SMLoc DirectiveLoc, bool ExpectEqual, bool CaseInsensitive) { 5723 std::string String1, String2; 5724 5725 if (parseTextItem(String1)) { 5726 if (ExpectEqual) 5727 return TokError("expected string parameter for 'ifidn' directive"); 5728 return TokError("expected string parameter for 'ifdif' directive"); 5729 } 5730 5731 if (Lexer.isNot(AsmToken::Comma)) { 5732 if (ExpectEqual) 5733 return TokError( 5734 "expected comma after first string for 'ifidn' directive"); 5735 return TokError("expected comma after first string for 'ifdif' directive"); 5736 } 5737 Lex(); 5738 5739 if (parseTextItem(String2)) { 5740 if (ExpectEqual) 5741 return TokError("expected string parameter for 'ifidn' directive"); 5742 return TokError("expected string parameter for 'ifdif' directive"); 5743 } 5744 5745 TheCondStack.push_back(TheCondState); 5746 TheCondState.TheCond = AsmCond::IfCond; 5747 if (CaseInsensitive) 5748 TheCondState.CondMet = 5749 ExpectEqual == (StringRef(String1).equals_lower(String2)); 5750 else 5751 TheCondState.CondMet = ExpectEqual == (String1 == String2); 5752 TheCondState.Ignore = !TheCondState.CondMet; 5753 5754 return false; 5755 } 5756 5757 /// parseDirectiveIfdef 5758 /// ::= ifdef symbol 5759 /// | ifdef variable 5760 bool MasmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) { 5761 TheCondStack.push_back(TheCondState); 5762 TheCondState.TheCond = AsmCond::IfCond; 5763 5764 if (TheCondState.Ignore) { 5765 eatToEndOfStatement(); 5766 } else { 5767 bool is_defined = false; 5768 unsigned RegNo; 5769 SMLoc StartLoc, EndLoc; 5770 is_defined = (getTargetParser().tryParseRegister( 5771 RegNo, StartLoc, EndLoc) == MatchOperand_Success); 5772 if (!is_defined) { 5773 StringRef Name; 5774 if (check(parseIdentifier(Name), "expected identifier after 'ifdef'") || 5775 parseToken(AsmToken::EndOfStatement, "unexpected token in 'ifdef'")) 5776 return true; 5777 5778 if (Variables.find(Name) != Variables.end()) { 5779 is_defined = true; 5780 } else { 5781 MCSymbol *Sym = getContext().lookupSymbol(Name); 5782 is_defined = (Sym && !Sym->isUndefined(false)); 5783 } 5784 } 5785 5786 TheCondState.CondMet = (is_defined == expect_defined); 5787 TheCondState.Ignore = !TheCondState.CondMet; 5788 } 5789 5790 return false; 5791 } 5792 5793 /// parseDirectiveElseIf 5794 /// ::= elseif expression 5795 bool MasmParser::parseDirectiveElseIf(SMLoc DirectiveLoc, 5796 DirectiveKind DirKind) { 5797 if (TheCondState.TheCond != AsmCond::IfCond && 5798 TheCondState.TheCond != AsmCond::ElseIfCond) 5799 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an" 5800 " .if or an .elseif"); 5801 TheCondState.TheCond = AsmCond::ElseIfCond; 5802 5803 bool LastIgnoreState = false; 5804 if (!TheCondStack.empty()) 5805 LastIgnoreState = TheCondStack.back().Ignore; 5806 if (LastIgnoreState || TheCondState.CondMet) { 5807 TheCondState.Ignore = true; 5808 eatToEndOfStatement(); 5809 } else { 5810 int64_t ExprValue; 5811 if (parseAbsoluteExpression(ExprValue)) 5812 return true; 5813 5814 if (parseToken(AsmToken::EndOfStatement, 5815 "unexpected token in '.elseif' directive")) 5816 return true; 5817 5818 switch (DirKind) { 5819 default: 5820 llvm_unreachable("unsupported directive"); 5821 case DK_ELSEIF: 5822 break; 5823 case DK_ELSEIFE: 5824 ExprValue = ExprValue == 0; 5825 break; 5826 } 5827 5828 TheCondState.CondMet = ExprValue; 5829 TheCondState.Ignore = !TheCondState.CondMet; 5830 } 5831 5832 return false; 5833 } 5834 5835 /// parseDirectiveElseIfb 5836 /// ::= elseifb expression 5837 bool MasmParser::parseDirectiveElseIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 5838 if (TheCondState.TheCond != AsmCond::IfCond && 5839 TheCondState.TheCond != AsmCond::ElseIfCond) 5840 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 5841 " if or an elseif"); 5842 TheCondState.TheCond = AsmCond::ElseIfCond; 5843 5844 bool LastIgnoreState = false; 5845 if (!TheCondStack.empty()) 5846 LastIgnoreState = TheCondStack.back().Ignore; 5847 if (LastIgnoreState || TheCondState.CondMet) { 5848 TheCondState.Ignore = true; 5849 eatToEndOfStatement(); 5850 } else { 5851 std::string Str; 5852 if (parseTextItem(Str)) 5853 return TokError("expected string parameter for 'elseifb' directive"); 5854 5855 if (parseToken(AsmToken::EndOfStatement, 5856 "unexpected token in 'elseifb' directive")) 5857 return true; 5858 5859 TheCondState.CondMet = ExpectBlank == Str.empty(); 5860 TheCondState.Ignore = !TheCondState.CondMet; 5861 } 5862 5863 return false; 5864 } 5865 5866 /// parseDirectiveElseIfdef 5867 /// ::= elseifdef symbol 5868 /// | elseifdef variable 5869 bool MasmParser::parseDirectiveElseIfdef(SMLoc DirectiveLoc, 5870 bool expect_defined) { 5871 if (TheCondState.TheCond != AsmCond::IfCond && 5872 TheCondState.TheCond != AsmCond::ElseIfCond) 5873 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 5874 " if or an elseif"); 5875 TheCondState.TheCond = AsmCond::ElseIfCond; 5876 5877 bool LastIgnoreState = false; 5878 if (!TheCondStack.empty()) 5879 LastIgnoreState = TheCondStack.back().Ignore; 5880 if (LastIgnoreState || TheCondState.CondMet) { 5881 TheCondState.Ignore = true; 5882 eatToEndOfStatement(); 5883 } else { 5884 bool is_defined = false; 5885 unsigned RegNo; 5886 SMLoc StartLoc, EndLoc; 5887 is_defined = (getTargetParser().tryParseRegister(RegNo, StartLoc, EndLoc) == 5888 MatchOperand_Success); 5889 if (!is_defined) { 5890 StringRef Name; 5891 if (check(parseIdentifier(Name), 5892 "expected identifier after 'elseifdef'") || 5893 parseToken(AsmToken::EndOfStatement, 5894 "unexpected token in 'elseifdef'")) 5895 return true; 5896 5897 if (Variables.find(Name) != Variables.end()) { 5898 is_defined = true; 5899 } else { 5900 MCSymbol *Sym = getContext().lookupSymbol(Name); 5901 is_defined = (Sym && !Sym->isUndefined(false)); 5902 } 5903 } 5904 5905 TheCondState.CondMet = (is_defined == expect_defined); 5906 TheCondState.Ignore = !TheCondState.CondMet; 5907 } 5908 5909 return false; 5910 } 5911 5912 /// parseDirectiveElseIfidn 5913 /// ::= elseifidn string1, string2 5914 bool MasmParser::parseDirectiveElseIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 5915 bool CaseInsensitive) { 5916 if (TheCondState.TheCond != AsmCond::IfCond && 5917 TheCondState.TheCond != AsmCond::ElseIfCond) 5918 return Error(DirectiveLoc, "Encountered an elseif that doesn't follow an" 5919 " if or an elseif"); 5920 TheCondState.TheCond = AsmCond::ElseIfCond; 5921 5922 bool LastIgnoreState = false; 5923 if (!TheCondStack.empty()) 5924 LastIgnoreState = TheCondStack.back().Ignore; 5925 if (LastIgnoreState || TheCondState.CondMet) { 5926 TheCondState.Ignore = true; 5927 eatToEndOfStatement(); 5928 } else { 5929 std::string String1, String2; 5930 5931 if (parseTextItem(String1)) { 5932 if (ExpectEqual) 5933 return TokError("expected string parameter for 'elseifidn' directive"); 5934 return TokError("expected string parameter for 'elseifdif' directive"); 5935 } 5936 5937 if (Lexer.isNot(AsmToken::Comma)) { 5938 if (ExpectEqual) 5939 return TokError( 5940 "expected comma after first string for 'elseifidn' directive"); 5941 return TokError( 5942 "expected comma after first string for 'elseifdif' directive"); 5943 } 5944 Lex(); 5945 5946 if (parseTextItem(String2)) { 5947 if (ExpectEqual) 5948 return TokError("expected string parameter for 'elseifidn' directive"); 5949 return TokError("expected string parameter for 'elseifdif' directive"); 5950 } 5951 5952 if (CaseInsensitive) 5953 TheCondState.CondMet = 5954 ExpectEqual == (StringRef(String1).equals_lower(String2)); 5955 else 5956 TheCondState.CondMet = ExpectEqual == (String1 == String2); 5957 TheCondState.Ignore = !TheCondState.CondMet; 5958 } 5959 5960 return false; 5961 } 5962 5963 /// parseDirectiveElse 5964 /// ::= else 5965 bool MasmParser::parseDirectiveElse(SMLoc DirectiveLoc) { 5966 if (parseToken(AsmToken::EndOfStatement, 5967 "unexpected token in 'else' directive")) 5968 return true; 5969 5970 if (TheCondState.TheCond != AsmCond::IfCond && 5971 TheCondState.TheCond != AsmCond::ElseIfCond) 5972 return Error(DirectiveLoc, "Encountered an else that doesn't follow an if" 5973 " or an elseif"); 5974 TheCondState.TheCond = AsmCond::ElseCond; 5975 bool LastIgnoreState = false; 5976 if (!TheCondStack.empty()) 5977 LastIgnoreState = TheCondStack.back().Ignore; 5978 if (LastIgnoreState || TheCondState.CondMet) 5979 TheCondState.Ignore = true; 5980 else 5981 TheCondState.Ignore = false; 5982 5983 return false; 5984 } 5985 5986 /// parseDirectiveEnd 5987 /// ::= end 5988 bool MasmParser::parseDirectiveEnd(SMLoc DirectiveLoc) { 5989 if (parseToken(AsmToken::EndOfStatement, 5990 "unexpected token in 'end' directive")) 5991 return true; 5992 5993 while (Lexer.isNot(AsmToken::Eof)) 5994 Lexer.Lex(); 5995 5996 return false; 5997 } 5998 5999 /// parseDirectiveError 6000 /// ::= .err [message] 6001 bool MasmParser::parseDirectiveError(SMLoc DirectiveLoc) { 6002 if (!TheCondStack.empty()) { 6003 if (TheCondStack.back().Ignore) { 6004 eatToEndOfStatement(); 6005 return false; 6006 } 6007 } 6008 6009 StringRef Message = ".err directive invoked in source file"; 6010 if (Lexer.isNot(AsmToken::EndOfStatement)) 6011 Message = parseStringToEndOfStatement(); 6012 Lex(); 6013 6014 return Error(DirectiveLoc, Message); 6015 } 6016 6017 /// parseDirectiveErrorIfb 6018 /// ::= .errb textitem[, message] 6019 bool MasmParser::parseDirectiveErrorIfb(SMLoc DirectiveLoc, bool ExpectBlank) { 6020 if (!TheCondStack.empty()) { 6021 if (TheCondStack.back().Ignore) { 6022 eatToEndOfStatement(); 6023 return false; 6024 } 6025 } 6026 6027 std::string Text; 6028 if (parseTextItem(Text)) 6029 return Error(getTok().getLoc(), "missing text item in '.errb' directive"); 6030 6031 StringRef Message = ".errb directive invoked in source file"; 6032 if (Lexer.isNot(AsmToken::EndOfStatement)) { 6033 if (parseToken(AsmToken::Comma)) 6034 return addErrorSuffix(" in '.errb' directive"); 6035 Message = parseStringToEndOfStatement(); 6036 } 6037 Lex(); 6038 6039 if (Text.empty() == ExpectBlank) 6040 return Error(DirectiveLoc, Message); 6041 return false; 6042 } 6043 6044 /// parseDirectiveErrorIfdef 6045 /// ::= .errdef name[, message] 6046 bool MasmParser::parseDirectiveErrorIfdef(SMLoc DirectiveLoc, 6047 bool ExpectDefined) { 6048 if (!TheCondStack.empty()) { 6049 if (TheCondStack.back().Ignore) { 6050 eatToEndOfStatement(); 6051 return false; 6052 } 6053 } 6054 6055 bool IsDefined = false; 6056 unsigned RegNo; 6057 SMLoc StartLoc, EndLoc; 6058 IsDefined = (getTargetParser().tryParseRegister(RegNo, StartLoc, EndLoc) == 6059 MatchOperand_Success); 6060 if (!IsDefined) { 6061 StringRef Name; 6062 if (check(parseIdentifier(Name), "expected identifier after '.errdef'")) 6063 return true; 6064 6065 if (Variables.find(Name) != Variables.end()) { 6066 IsDefined = true; 6067 } else { 6068 MCSymbol *Sym = getContext().lookupSymbol(Name); 6069 IsDefined = (Sym && !Sym->isUndefined(false)); 6070 } 6071 } 6072 6073 StringRef Message = ".errdef directive invoked in source file"; 6074 if (Lexer.isNot(AsmToken::EndOfStatement)) { 6075 if (parseToken(AsmToken::Comma)) 6076 return addErrorSuffix(" in '.errdef' directive"); 6077 Message = parseStringToEndOfStatement(); 6078 } 6079 Lex(); 6080 6081 if (IsDefined == ExpectDefined) 6082 return Error(DirectiveLoc, Message); 6083 return false; 6084 } 6085 6086 /// parseDirectiveErrorIfidn 6087 /// ::= .erridn textitem1, textitem2[, message] 6088 bool MasmParser::parseDirectiveErrorIfidn(SMLoc DirectiveLoc, bool ExpectEqual, 6089 bool CaseInsensitive) { 6090 if (!TheCondStack.empty()) { 6091 if (TheCondStack.back().Ignore) { 6092 eatToEndOfStatement(); 6093 return false; 6094 } 6095 } 6096 6097 std::string String1, String2; 6098 6099 if (parseTextItem(String1)) { 6100 if (ExpectEqual) 6101 return TokError("expected string parameter for '.erridn' directive"); 6102 return TokError("expected string parameter for '.errdif' directive"); 6103 } 6104 6105 if (Lexer.isNot(AsmToken::Comma)) { 6106 if (ExpectEqual) 6107 return TokError( 6108 "expected comma after first string for '.erridn' directive"); 6109 return TokError( 6110 "expected comma after first string for '.errdif' directive"); 6111 } 6112 Lex(); 6113 6114 if (parseTextItem(String2)) { 6115 if (ExpectEqual) 6116 return TokError("expected string parameter for '.erridn' directive"); 6117 return TokError("expected string parameter for '.errdif' directive"); 6118 } 6119 6120 StringRef Message; 6121 if (ExpectEqual) 6122 Message = ".erridn directive invoked in source file"; 6123 else 6124 Message = ".errdif directive invoked in source file"; 6125 if (Lexer.isNot(AsmToken::EndOfStatement)) { 6126 if (parseToken(AsmToken::Comma)) 6127 return addErrorSuffix(" in '.erridn' directive"); 6128 Message = parseStringToEndOfStatement(); 6129 } 6130 Lex(); 6131 6132 if (CaseInsensitive) 6133 TheCondState.CondMet = 6134 ExpectEqual == (StringRef(String1).equals_lower(String2)); 6135 else 6136 TheCondState.CondMet = ExpectEqual == (String1 == String2); 6137 TheCondState.Ignore = !TheCondState.CondMet; 6138 6139 if ((CaseInsensitive && 6140 ExpectEqual == StringRef(String1).equals_lower(String2)) || 6141 (ExpectEqual == (String1 == String2))) 6142 return Error(DirectiveLoc, Message); 6143 return false; 6144 } 6145 6146 /// parseDirectiveErrorIfe 6147 /// ::= .erre expression[, message] 6148 bool MasmParser::parseDirectiveErrorIfe(SMLoc DirectiveLoc, bool ExpectZero) { 6149 if (!TheCondStack.empty()) { 6150 if (TheCondStack.back().Ignore) { 6151 eatToEndOfStatement(); 6152 return false; 6153 } 6154 } 6155 6156 int64_t ExprValue; 6157 if (parseAbsoluteExpression(ExprValue)) 6158 return addErrorSuffix(" in '.erre' directive"); 6159 6160 StringRef Message = ".erre directive invoked in source file"; 6161 if (Lexer.isNot(AsmToken::EndOfStatement)) { 6162 if (parseToken(AsmToken::Comma)) 6163 return addErrorSuffix(" in '.erre' directive"); 6164 Message = parseStringToEndOfStatement(); 6165 } 6166 Lex(); 6167 6168 if ((ExprValue == 0) == ExpectZero) 6169 return Error(DirectiveLoc, Message); 6170 return false; 6171 } 6172 6173 /// parseDirectiveEndIf 6174 /// ::= .endif 6175 bool MasmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) { 6176 if (parseToken(AsmToken::EndOfStatement, 6177 "unexpected token in '.endif' directive")) 6178 return true; 6179 6180 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) 6181 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow " 6182 "an .if or .else"); 6183 if (!TheCondStack.empty()) { 6184 TheCondState = TheCondStack.back(); 6185 TheCondStack.pop_back(); 6186 } 6187 6188 return false; 6189 } 6190 6191 void MasmParser::initializeDirectiveKindMap() { 6192 DirectiveKindMap["="] = DK_ASSIGN; 6193 DirectiveKindMap["equ"] = DK_EQU; 6194 DirectiveKindMap["textequ"] = DK_TEXTEQU; 6195 // DirectiveKindMap[".ascii"] = DK_ASCII; 6196 // DirectiveKindMap[".asciz"] = DK_ASCIZ; 6197 // DirectiveKindMap[".string"] = DK_STRING; 6198 DirectiveKindMap["byte"] = DK_BYTE; 6199 DirectiveKindMap["sbyte"] = DK_SBYTE; 6200 DirectiveKindMap["word"] = DK_WORD; 6201 DirectiveKindMap["sword"] = DK_SWORD; 6202 DirectiveKindMap["dword"] = DK_DWORD; 6203 DirectiveKindMap["sdword"] = DK_SDWORD; 6204 DirectiveKindMap["fword"] = DK_FWORD; 6205 DirectiveKindMap["qword"] = DK_QWORD; 6206 DirectiveKindMap["sqword"] = DK_SQWORD; 6207 DirectiveKindMap["real4"] = DK_REAL4; 6208 DirectiveKindMap["real8"] = DK_REAL8; 6209 DirectiveKindMap["real10"] = DK_REAL10; 6210 DirectiveKindMap["align"] = DK_ALIGN; 6211 // DirectiveKindMap[".org"] = DK_ORG; 6212 DirectiveKindMap["extern"] = DK_EXTERN; 6213 DirectiveKindMap["public"] = DK_PUBLIC; 6214 // DirectiveKindMap[".comm"] = DK_COMM; 6215 DirectiveKindMap["comment"] = DK_COMMENT; 6216 DirectiveKindMap["include"] = DK_INCLUDE; 6217 // DirectiveKindMap[".rept"] = DK_REPT; 6218 // DirectiveKindMap[".rep"] = DK_REPT; 6219 // DirectiveKindMap[".irp"] = DK_IRP; 6220 // DirectiveKindMap[".irpc"] = DK_IRPC; 6221 // DirectiveKindMap[".endr"] = DK_ENDR; 6222 DirectiveKindMap["if"] = DK_IF; 6223 DirectiveKindMap["ife"] = DK_IFE; 6224 DirectiveKindMap["ifb"] = DK_IFB; 6225 DirectiveKindMap["ifnb"] = DK_IFNB; 6226 DirectiveKindMap["ifdef"] = DK_IFDEF; 6227 DirectiveKindMap["ifndef"] = DK_IFNDEF; 6228 DirectiveKindMap["ifdif"] = DK_IFDIF; 6229 DirectiveKindMap["ifdifi"] = DK_IFDIFI; 6230 DirectiveKindMap["ifidn"] = DK_IFIDN; 6231 DirectiveKindMap["ifidni"] = DK_IFIDNI; 6232 DirectiveKindMap["elseif"] = DK_ELSEIF; 6233 DirectiveKindMap["elseifdef"] = DK_ELSEIFDEF; 6234 DirectiveKindMap["elseifndef"] = DK_ELSEIFNDEF; 6235 DirectiveKindMap["elseifdif"] = DK_ELSEIFDIF; 6236 DirectiveKindMap["elseifidn"] = DK_ELSEIFIDN; 6237 DirectiveKindMap["else"] = DK_ELSE; 6238 DirectiveKindMap["end"] = DK_END; 6239 DirectiveKindMap["endif"] = DK_ENDIF; 6240 // DirectiveKindMap[".file"] = DK_FILE; 6241 // DirectiveKindMap[".line"] = DK_LINE; 6242 // DirectiveKindMap[".loc"] = DK_LOC; 6243 // DirectiveKindMap[".stabs"] = DK_STABS; 6244 // DirectiveKindMap[".cv_file"] = DK_CV_FILE; 6245 // DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID; 6246 // DirectiveKindMap[".cv_loc"] = DK_CV_LOC; 6247 // DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE; 6248 // DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE; 6249 // DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID; 6250 // DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE; 6251 // DirectiveKindMap[".cv_string"] = DK_CV_STRING; 6252 // DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE; 6253 // DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS; 6254 // DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET; 6255 // DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA; 6256 // DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS; 6257 // DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC; 6258 // DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC; 6259 // DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA; 6260 // DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET; 6261 // DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET; 6262 // DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER; 6263 // DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET; 6264 // DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET; 6265 // DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY; 6266 // DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA; 6267 // DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE; 6268 // DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE; 6269 // DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE; 6270 // DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE; 6271 // DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE; 6272 // DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN; 6273 // DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME; 6274 // DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED; 6275 // DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER; 6276 // DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE; 6277 // DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME; 6278 DirectiveKindMap["macro"] = DK_MACRO; 6279 DirectiveKindMap["exitm"] = DK_EXITM; 6280 DirectiveKindMap["endm"] = DK_ENDM; 6281 // DirectiveKindMap[".purgem"] = DK_PURGEM; 6282 DirectiveKindMap[".err"] = DK_ERR; 6283 DirectiveKindMap[".errb"] = DK_ERRB; 6284 DirectiveKindMap[".errnb"] = DK_ERRNB; 6285 DirectiveKindMap[".errdef"] = DK_ERRDEF; 6286 DirectiveKindMap[".errndef"] = DK_ERRNDEF; 6287 DirectiveKindMap[".errdif"] = DK_ERRDIF; 6288 DirectiveKindMap[".errdifi"] = DK_ERRDIFI; 6289 DirectiveKindMap[".erridn"] = DK_ERRIDN; 6290 DirectiveKindMap[".erridni"] = DK_ERRIDNI; 6291 DirectiveKindMap[".erre"] = DK_ERRE; 6292 DirectiveKindMap[".errnz"] = DK_ERRNZ; 6293 DirectiveKindMap[".pushframe"] = DK_PUSHFRAME; 6294 DirectiveKindMap[".pushreg"] = DK_PUSHREG; 6295 DirectiveKindMap[".savereg"] = DK_SAVEREG; 6296 DirectiveKindMap[".savexmm128"] = DK_SAVEXMM128; 6297 DirectiveKindMap[".setframe"] = DK_SETFRAME; 6298 DirectiveKindMap[".radix"] = DK_RADIX; 6299 DirectiveKindMap["db"] = DK_DB; 6300 DirectiveKindMap["dd"] = DK_DD; 6301 DirectiveKindMap["df"] = DK_DF; 6302 DirectiveKindMap["dq"] = DK_DQ; 6303 DirectiveKindMap["dw"] = DK_DW; 6304 DirectiveKindMap["echo"] = DK_ECHO; 6305 DirectiveKindMap["struc"] = DK_STRUCT; 6306 DirectiveKindMap["struct"] = DK_STRUCT; 6307 DirectiveKindMap["union"] = DK_UNION; 6308 DirectiveKindMap["ends"] = DK_ENDS; 6309 } 6310 6311 MCAsmMacro *MasmParser::parseMacroLikeBody(SMLoc DirectiveLoc) { 6312 AsmToken EndToken, StartToken = getTok(); 6313 6314 unsigned NestLevel = 0; 6315 while (true) { 6316 // Check whether we have reached the end of the file. 6317 if (getLexer().is(AsmToken::Eof)) { 6318 printError(DirectiveLoc, "no matching '.endr' in definition"); 6319 return nullptr; 6320 } 6321 6322 if (Lexer.is(AsmToken::Identifier) && 6323 (getTok().getIdentifier() == ".rep" || 6324 getTok().getIdentifier() == ".rept" || 6325 getTok().getIdentifier() == ".irp" || 6326 getTok().getIdentifier() == ".irpc")) { 6327 ++NestLevel; 6328 } 6329 6330 // Otherwise, check whether we have reached the .endr. 6331 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") { 6332 if (NestLevel == 0) { 6333 EndToken = getTok(); 6334 Lex(); 6335 if (Lexer.isNot(AsmToken::EndOfStatement)) { 6336 printError(getTok().getLoc(), 6337 "unexpected token in '.endr' directive"); 6338 return nullptr; 6339 } 6340 break; 6341 } 6342 --NestLevel; 6343 } 6344 6345 // Otherwise, scan till the end of the statement. 6346 eatToEndOfStatement(); 6347 } 6348 6349 const char *BodyStart = StartToken.getLoc().getPointer(); 6350 const char *BodyEnd = EndToken.getLoc().getPointer(); 6351 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart); 6352 6353 // We Are Anonymous. 6354 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters()); 6355 return &MacroLikeBodies.back(); 6356 } 6357 6358 void MasmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc, 6359 raw_svector_ostream &OS) { 6360 OS << ".endr\n"; 6361 6362 std::unique_ptr<MemoryBuffer> Instantiation = 6363 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>"); 6364 6365 // Create the macro instantiation object and add to the current macro 6366 // instantiation stack. 6367 MacroInstantiation *MI = new MacroInstantiation{ 6368 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()}; 6369 ActiveMacros.push_back(MI); 6370 6371 // Jump to the macro instantiation and prime the lexer. 6372 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc()); 6373 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer()); 6374 Lex(); 6375 } 6376 6377 /// parseDirectiveRept 6378 /// ::= .rep | .rept count 6379 bool MasmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) { 6380 const MCExpr *CountExpr; 6381 SMLoc CountLoc = getTok().getLoc(); 6382 if (parseExpression(CountExpr)) 6383 return true; 6384 6385 int64_t Count; 6386 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) { 6387 return Error(CountLoc, "unexpected token in '" + Dir + "' directive"); 6388 } 6389 6390 if (check(Count < 0, CountLoc, "Count is negative") || 6391 parseToken(AsmToken::EndOfStatement, 6392 "unexpected token in '" + Dir + "' directive")) 6393 return true; 6394 6395 // Lex the rept definition. 6396 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 6397 if (!M) 6398 return true; 6399 6400 // Macro instantiation is lexical, unfortunately. We construct a new buffer 6401 // to hold the macro body with substitutions. 6402 SmallString<256> Buf; 6403 raw_svector_ostream OS(Buf); 6404 while (Count--) { 6405 if (expandMacro(OS, M->Body, None, None, M->Locals, getTok().getLoc())) 6406 return true; 6407 } 6408 instantiateMacroLikeBody(M, DirectiveLoc, OS); 6409 6410 return false; 6411 } 6412 6413 /// parseDirectiveIrp 6414 /// ::= .irp symbol,values 6415 bool MasmParser::parseDirectiveIrp(SMLoc DirectiveLoc) { 6416 MCAsmMacroParameter Parameter; 6417 MCAsmMacroArguments A; 6418 if (check(parseIdentifier(Parameter.Name), 6419 "expected identifier in '.irp' directive") || 6420 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") || 6421 parseMacroArguments(nullptr, A) || 6422 parseToken(AsmToken::EndOfStatement, "expected End of Statement")) 6423 return true; 6424 6425 // Lex the irp definition. 6426 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 6427 if (!M) 6428 return true; 6429 6430 // Macro instantiation is lexical, unfortunately. We construct a new buffer 6431 // to hold the macro body with substitutions. 6432 SmallString<256> Buf; 6433 raw_svector_ostream OS(Buf); 6434 6435 for (const MCAsmMacroArgument &Arg : A) { 6436 if (expandMacro(OS, M->Body, Parameter, Arg, M->Locals, getTok().getLoc())) 6437 return true; 6438 } 6439 6440 instantiateMacroLikeBody(M, DirectiveLoc, OS); 6441 6442 return false; 6443 } 6444 6445 /// parseDirectiveIrpc 6446 /// ::= .irpc symbol,values 6447 bool MasmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) { 6448 MCAsmMacroParameter Parameter; 6449 MCAsmMacroArguments A; 6450 6451 if (check(parseIdentifier(Parameter.Name), 6452 "expected identifier in '.irpc' directive") || 6453 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") || 6454 parseMacroArguments(nullptr, A)) 6455 return true; 6456 6457 if (A.size() != 1 || A.front().size() != 1) 6458 return TokError("unexpected token in '.irpc' directive"); 6459 6460 // Eat the end of statement. 6461 if (parseToken(AsmToken::EndOfStatement, "expected end of statement")) 6462 return true; 6463 6464 // Lex the irpc definition. 6465 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc); 6466 if (!M) 6467 return true; 6468 6469 // Macro instantiation is lexical, unfortunately. We construct a new buffer 6470 // to hold the macro body with substitutions. 6471 SmallString<256> Buf; 6472 raw_svector_ostream OS(Buf); 6473 6474 StringRef Values = A.front().front().getString(); 6475 for (std::size_t I = 0, End = Values.size(); I != End; ++I) { 6476 MCAsmMacroArgument Arg; 6477 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1)); 6478 6479 if (expandMacro(OS, M->Body, Parameter, Arg, M->Locals, getTok().getLoc())) 6480 return true; 6481 } 6482 6483 instantiateMacroLikeBody(M, DirectiveLoc, OS); 6484 6485 return false; 6486 } 6487 6488 bool MasmParser::parseDirectiveEndr(SMLoc DirectiveLoc) { 6489 if (ActiveMacros.empty()) 6490 return TokError("unmatched '.endr' directive"); 6491 6492 // The only .repl that should get here are the ones created by 6493 // instantiateMacroLikeBody. 6494 assert(getLexer().is(AsmToken::EndOfStatement)); 6495 6496 handleMacroExit(); 6497 return false; 6498 } 6499 6500 bool MasmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info, 6501 size_t Len) { 6502 const MCExpr *Value; 6503 SMLoc ExprLoc = getLexer().getLoc(); 6504 if (parseExpression(Value)) 6505 return true; 6506 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 6507 if (!MCE) 6508 return Error(ExprLoc, "unexpected expression in _emit"); 6509 uint64_t IntValue = MCE->getValue(); 6510 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) 6511 return Error(ExprLoc, "literal value out of range for directive"); 6512 6513 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len); 6514 return false; 6515 } 6516 6517 bool MasmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) { 6518 const MCExpr *Value; 6519 SMLoc ExprLoc = getLexer().getLoc(); 6520 if (parseExpression(Value)) 6521 return true; 6522 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value); 6523 if (!MCE) 6524 return Error(ExprLoc, "unexpected expression in align"); 6525 uint64_t IntValue = MCE->getValue(); 6526 if (!isPowerOf2_64(IntValue)) 6527 return Error(ExprLoc, "literal value not a power of two greater then zero"); 6528 6529 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue)); 6530 return false; 6531 } 6532 6533 bool MasmParser::parseDirectiveRadix(SMLoc DirectiveLoc) { 6534 const SMLoc Loc = getLexer().getLoc(); 6535 StringRef RadixString = parseStringToEndOfStatement().trim(); 6536 unsigned Radix; 6537 if (RadixString.getAsInteger(10, Radix)) { 6538 return Error(Loc, 6539 "radix must be a decimal number in the range 2 to 16; was " + 6540 RadixString); 6541 } 6542 if (Radix < 2 || Radix > 16) 6543 return Error(Loc, "radix must be in the range 2 to 16; was " + 6544 std::to_string(Radix)); 6545 getLexer().setMasmDefaultRadix(Radix); 6546 return false; 6547 } 6548 6549 bool MasmParser::parseDirectiveEcho() { 6550 StringRef Message = parseStringToEndOfStatement(); 6551 Lex(); // eat end of statement 6552 llvm::outs() << Message << '\n'; 6553 return false; 6554 } 6555 6556 // We are comparing pointers, but the pointers are relative to a single string. 6557 // Thus, this should always be deterministic. 6558 static int rewritesSort(const AsmRewrite *AsmRewriteA, 6559 const AsmRewrite *AsmRewriteB) { 6560 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer()) 6561 return -1; 6562 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer()) 6563 return 1; 6564 6565 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output 6566 // rewrite to the same location. Make sure the SizeDirective rewrite is 6567 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This 6568 // ensures the sort algorithm is stable. 6569 if (AsmRewritePrecedence[AsmRewriteA->Kind] > 6570 AsmRewritePrecedence[AsmRewriteB->Kind]) 6571 return -1; 6572 6573 if (AsmRewritePrecedence[AsmRewriteA->Kind] < 6574 AsmRewritePrecedence[AsmRewriteB->Kind]) 6575 return 1; 6576 llvm_unreachable("Unstable rewrite sort."); 6577 } 6578 6579 bool MasmParser::lookUpField(StringRef Name, AsmFieldInfo &Info) const { 6580 const std::pair<StringRef, StringRef> BaseMember = Name.split('.'); 6581 const StringRef Base = BaseMember.first, Member = BaseMember.second; 6582 return lookUpField(Base, Member, Info); 6583 } 6584 6585 bool MasmParser::lookUpField(StringRef Base, StringRef Member, 6586 AsmFieldInfo &Info) const { 6587 if (Base.empty()) 6588 return true; 6589 6590 AsmFieldInfo BaseInfo; 6591 if (Base.contains('.') && !lookUpField(Base, BaseInfo)) 6592 Base = BaseInfo.Type.Name; 6593 6594 auto StructIt = Structs.find(Base.lower()); 6595 auto TypeIt = KnownType.find(Base.lower()); 6596 if (TypeIt != KnownType.end()) { 6597 StructIt = Structs.find(TypeIt->second.Name.lower()); 6598 } 6599 if (StructIt != Structs.end()) 6600 return lookUpField(StructIt->second, Member, Info); 6601 6602 return true; 6603 } 6604 6605 bool MasmParser::lookUpField(const StructInfo &Structure, StringRef Member, 6606 AsmFieldInfo &Info) const { 6607 if (Member.empty()) { 6608 Info.Type.Name = Structure.Name; 6609 Info.Type.Size = Structure.Size; 6610 Info.Type.ElementSize = Structure.Size; 6611 Info.Type.Length = 1; 6612 return false; 6613 } 6614 6615 std::pair<StringRef, StringRef> Split = Member.split('.'); 6616 const StringRef FieldName = Split.first, FieldMember = Split.second; 6617 6618 auto StructIt = Structs.find(FieldName.lower()); 6619 if (StructIt != Structs.end()) 6620 return lookUpField(StructIt->second, FieldMember, Info); 6621 6622 auto FieldIt = Structure.FieldsByName.find(FieldName.lower()); 6623 if (FieldIt == Structure.FieldsByName.end()) 6624 return true; 6625 6626 const FieldInfo &Field = Structure.Fields[FieldIt->second]; 6627 if (FieldMember.empty()) { 6628 Info.Offset += Field.Offset; 6629 Info.Type.Size = Field.SizeOf; 6630 Info.Type.ElementSize = Field.Type; 6631 Info.Type.Length = Field.LengthOf; 6632 if (Field.Contents.FT == FT_STRUCT) 6633 Info.Type.Name = Field.Contents.StructInfo.Structure.Name; 6634 else 6635 Info.Type.Name = ""; 6636 return false; 6637 } 6638 6639 if (Field.Contents.FT != FT_STRUCT) 6640 return true; 6641 const StructFieldInfo &StructInfo = Field.Contents.StructInfo; 6642 6643 if (lookUpField(StructInfo.Structure, FieldMember, Info)) 6644 return true; 6645 6646 Info.Offset += Field.Offset; 6647 return false; 6648 } 6649 6650 bool MasmParser::lookUpType(StringRef Name, AsmTypeInfo &Info) const { 6651 unsigned Size = StringSwitch<unsigned>(Name) 6652 .CasesLower("byte", "db", "sbyte", 1) 6653 .CasesLower("word", "dw", "sword", 2) 6654 .CasesLower("dword", "dd", "sdword", 4) 6655 .CasesLower("fword", "df", 6) 6656 .CasesLower("qword", "dq", "sqword", 8) 6657 .CaseLower("real4", 4) 6658 .CaseLower("real8", 8) 6659 .CaseLower("real10", 10) 6660 .Default(0); 6661 if (Size) { 6662 Info.Name = Name; 6663 Info.ElementSize = Size; 6664 Info.Length = 1; 6665 Info.Size = Size; 6666 return false; 6667 } 6668 6669 auto StructIt = Structs.find(Name.lower()); 6670 if (StructIt != Structs.end()) { 6671 const StructInfo &Structure = StructIt->second; 6672 Info.Name = Name; 6673 Info.ElementSize = Structure.Size; 6674 Info.Length = 1; 6675 Info.Size = Structure.Size; 6676 return false; 6677 } 6678 6679 return true; 6680 } 6681 6682 bool MasmParser::parseMSInlineAsm( 6683 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs, 6684 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls, 6685 SmallVectorImpl<std::string> &Constraints, 6686 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII, 6687 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) { 6688 SmallVector<void *, 4> InputDecls; 6689 SmallVector<void *, 4> OutputDecls; 6690 SmallVector<bool, 4> InputDeclsAddressOf; 6691 SmallVector<bool, 4> OutputDeclsAddressOf; 6692 SmallVector<std::string, 4> InputConstraints; 6693 SmallVector<std::string, 4> OutputConstraints; 6694 SmallVector<unsigned, 4> ClobberRegs; 6695 6696 SmallVector<AsmRewrite, 4> AsmStrRewrites; 6697 6698 // Prime the lexer. 6699 Lex(); 6700 6701 // While we have input, parse each statement. 6702 unsigned InputIdx = 0; 6703 unsigned OutputIdx = 0; 6704 while (getLexer().isNot(AsmToken::Eof)) { 6705 // Parse curly braces marking block start/end. 6706 if (parseCurlyBlockScope(AsmStrRewrites)) 6707 continue; 6708 6709 ParseStatementInfo Info(&AsmStrRewrites); 6710 bool StatementErr = parseStatement(Info, &SI); 6711 6712 if (StatementErr || Info.ParseError) { 6713 // Emit pending errors if any exist. 6714 printPendingErrors(); 6715 return true; 6716 } 6717 6718 // No pending error should exist here. 6719 assert(!hasPendingError() && "unexpected error from parseStatement"); 6720 6721 if (Info.Opcode == ~0U) 6722 continue; 6723 6724 const MCInstrDesc &Desc = MII->get(Info.Opcode); 6725 6726 // Build the list of clobbers, outputs and inputs. 6727 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) { 6728 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i]; 6729 6730 // Register operand. 6731 if (Operand.isReg() && !Operand.needAddressOf() && 6732 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) { 6733 unsigned NumDefs = Desc.getNumDefs(); 6734 // Clobber. 6735 if (NumDefs && Operand.getMCOperandNum() < NumDefs) 6736 ClobberRegs.push_back(Operand.getReg()); 6737 continue; 6738 } 6739 6740 // Expr/Input or Output. 6741 StringRef SymName = Operand.getSymName(); 6742 if (SymName.empty()) 6743 continue; 6744 6745 void *OpDecl = Operand.getOpDecl(); 6746 if (!OpDecl) 6747 continue; 6748 6749 StringRef Constraint = Operand.getConstraint(); 6750 if (Operand.isImm()) { 6751 // Offset as immediate. 6752 if (Operand.isOffsetOfLocal()) 6753 Constraint = "r"; 6754 else 6755 Constraint = "i"; 6756 } 6757 6758 bool isOutput = (i == 1) && Desc.mayStore(); 6759 SMLoc Start = SMLoc::getFromPointer(SymName.data()); 6760 if (isOutput) { 6761 ++InputIdx; 6762 OutputDecls.push_back(OpDecl); 6763 OutputDeclsAddressOf.push_back(Operand.needAddressOf()); 6764 OutputConstraints.push_back(("=" + Constraint).str()); 6765 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size()); 6766 } else { 6767 InputDecls.push_back(OpDecl); 6768 InputDeclsAddressOf.push_back(Operand.needAddressOf()); 6769 InputConstraints.push_back(Constraint.str()); 6770 if (Desc.OpInfo[i - 1].isBranchTarget()) 6771 AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size()); 6772 else 6773 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size()); 6774 } 6775 } 6776 6777 // Consider implicit defs to be clobbers. Think of cpuid and push. 6778 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(), 6779 Desc.getNumImplicitDefs()); 6780 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end()); 6781 } 6782 6783 // Set the number of Outputs and Inputs. 6784 NumOutputs = OutputDecls.size(); 6785 NumInputs = InputDecls.size(); 6786 6787 // Set the unique clobbers. 6788 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end()); 6789 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()), 6790 ClobberRegs.end()); 6791 Clobbers.assign(ClobberRegs.size(), std::string()); 6792 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) { 6793 raw_string_ostream OS(Clobbers[I]); 6794 IP->printRegName(OS, ClobberRegs[I]); 6795 } 6796 6797 // Merge the various outputs and inputs. Output are expected first. 6798 if (NumOutputs || NumInputs) { 6799 unsigned NumExprs = NumOutputs + NumInputs; 6800 OpDecls.resize(NumExprs); 6801 Constraints.resize(NumExprs); 6802 for (unsigned i = 0; i < NumOutputs; ++i) { 6803 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]); 6804 Constraints[i] = OutputConstraints[i]; 6805 } 6806 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) { 6807 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]); 6808 Constraints[j] = InputConstraints[i]; 6809 } 6810 } 6811 6812 // Build the IR assembly string. 6813 std::string AsmStringIR; 6814 raw_string_ostream OS(AsmStringIR); 6815 StringRef ASMString = 6816 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer(); 6817 const char *AsmStart = ASMString.begin(); 6818 const char *AsmEnd = ASMString.end(); 6819 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort); 6820 for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) { 6821 const AsmRewrite &AR = *it; 6822 // Check if this has already been covered by another rewrite... 6823 if (AR.Done) 6824 continue; 6825 AsmRewriteKind Kind = AR.Kind; 6826 6827 const char *Loc = AR.Loc.getPointer(); 6828 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!"); 6829 6830 // Emit everything up to the immediate/expression. 6831 if (unsigned Len = Loc - AsmStart) 6832 OS << StringRef(AsmStart, Len); 6833 6834 // Skip the original expression. 6835 if (Kind == AOK_Skip) { 6836 AsmStart = Loc + AR.Len; 6837 continue; 6838 } 6839 6840 unsigned AdditionalSkip = 0; 6841 // Rewrite expressions in $N notation. 6842 switch (Kind) { 6843 default: 6844 break; 6845 case AOK_IntelExpr: 6846 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression"); 6847 if (AR.IntelExp.NeedBracs) 6848 OS << "["; 6849 if (AR.IntelExp.hasBaseReg()) 6850 OS << AR.IntelExp.BaseReg; 6851 if (AR.IntelExp.hasIndexReg()) 6852 OS << (AR.IntelExp.hasBaseReg() ? " + " : "") 6853 << AR.IntelExp.IndexReg; 6854 if (AR.IntelExp.Scale > 1) 6855 OS << " * $$" << AR.IntelExp.Scale; 6856 if (AR.IntelExp.hasOffset()) { 6857 if (AR.IntelExp.hasRegs()) 6858 OS << " + "; 6859 // Fuse this rewrite with a rewrite of the offset name, if present. 6860 StringRef OffsetName = AR.IntelExp.OffsetName; 6861 SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data()); 6862 size_t OffsetLen = OffsetName.size(); 6863 auto rewrite_it = std::find_if( 6864 it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) { 6865 return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen && 6866 (FusingAR.Kind == AOK_Input || 6867 FusingAR.Kind == AOK_CallInput); 6868 }); 6869 if (rewrite_it == AsmStrRewrites.end()) { 6870 OS << "offset " << OffsetName; 6871 } else if (rewrite_it->Kind == AOK_CallInput) { 6872 OS << "${" << InputIdx++ << ":P}"; 6873 rewrite_it->Done = true; 6874 } else { 6875 OS << '$' << InputIdx++; 6876 rewrite_it->Done = true; 6877 } 6878 } 6879 if (AR.IntelExp.Imm || AR.IntelExp.emitImm()) 6880 OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm; 6881 if (AR.IntelExp.NeedBracs) 6882 OS << "]"; 6883 break; 6884 case AOK_Label: 6885 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label; 6886 break; 6887 case AOK_Input: 6888 OS << '$' << InputIdx++; 6889 break; 6890 case AOK_CallInput: 6891 OS << "${" << InputIdx++ << ":P}"; 6892 break; 6893 case AOK_Output: 6894 OS << '$' << OutputIdx++; 6895 break; 6896 case AOK_SizeDirective: 6897 switch (AR.Val) { 6898 default: break; 6899 case 8: OS << "byte ptr "; break; 6900 case 16: OS << "word ptr "; break; 6901 case 32: OS << "dword ptr "; break; 6902 case 64: OS << "qword ptr "; break; 6903 case 80: OS << "xword ptr "; break; 6904 case 128: OS << "xmmword ptr "; break; 6905 case 256: OS << "ymmword ptr "; break; 6906 } 6907 break; 6908 case AOK_Emit: 6909 OS << ".byte"; 6910 break; 6911 case AOK_Align: { 6912 // MS alignment directives are measured in bytes. If the native assembler 6913 // measures alignment in bytes, we can pass it straight through. 6914 OS << ".align"; 6915 if (getContext().getAsmInfo()->getAlignmentIsInBytes()) 6916 break; 6917 6918 // Alignment is in log2 form, so print that instead and skip the original 6919 // immediate. 6920 unsigned Val = AR.Val; 6921 OS << ' ' << Val; 6922 assert(Val < 10 && "Expected alignment less then 2^10."); 6923 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4; 6924 break; 6925 } 6926 case AOK_EVEN: 6927 OS << ".even"; 6928 break; 6929 case AOK_EndOfStatement: 6930 OS << "\n\t"; 6931 break; 6932 } 6933 6934 // Skip the original expression. 6935 AsmStart = Loc + AR.Len + AdditionalSkip; 6936 } 6937 6938 // Emit the remainder of the asm string. 6939 if (AsmStart != AsmEnd) 6940 OS << StringRef(AsmStart, AsmEnd - AsmStart); 6941 6942 AsmString = OS.str(); 6943 return false; 6944 } 6945 6946 /// Create an MCAsmParser instance. 6947 MCAsmParser *llvm::createMCMasmParser(SourceMgr &SM, MCContext &C, 6948 MCStreamer &Out, const MCAsmInfo &MAI, 6949 unsigned CB) { 6950 return new MasmParser(SM, C, Out, MAI, CB); 6951 } 6952