LLVM API Documentation

AsmParser.cpp
Go to the documentation of this file.
00001 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This class implements the parser for assembly files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/ADT/APFloat.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/StringMap.h"
00018 #include "llvm/ADT/Twine.h"
00019 #include "llvm/MC/MCAsmInfo.h"
00020 #include "llvm/MC/MCContext.h"
00021 #include "llvm/MC/MCDwarf.h"
00022 #include "llvm/MC/MCExpr.h"
00023 #include "llvm/MC/MCInstPrinter.h"
00024 #include "llvm/MC/MCInstrInfo.h"
00025 #include "llvm/MC/MCObjectFileInfo.h"
00026 #include "llvm/MC/MCParser/AsmCond.h"
00027 #include "llvm/MC/MCParser/AsmLexer.h"
00028 #include "llvm/MC/MCParser/MCAsmParser.h"
00029 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
00030 #include "llvm/MC/MCRegisterInfo.h"
00031 #include "llvm/MC/MCSectionMachO.h"
00032 #include "llvm/MC/MCStreamer.h"
00033 #include "llvm/MC/MCSymbol.h"
00034 #include "llvm/MC/MCTargetAsmParser.h"
00035 #include "llvm/Support/CommandLine.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/MathExtras.h"
00038 #include "llvm/Support/MemoryBuffer.h"
00039 #include "llvm/Support/SourceMgr.h"
00040 #include "llvm/Support/raw_ostream.h"
00041 #include <cctype>
00042 #include <deque>
00043 #include <set>
00044 #include <string>
00045 #include <vector>
00046 using namespace llvm;
00047 
00048 MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
00049 
00050 namespace {
00051 /// \brief Helper types for tracking macro definitions.
00052 typedef std::vector<AsmToken> MCAsmMacroArgument;
00053 typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
00054 
00055 struct MCAsmMacroParameter {
00056   StringRef Name;
00057   MCAsmMacroArgument Value;
00058   bool Required;
00059   bool Vararg;
00060 
00061   MCAsmMacroParameter() : Required(false), Vararg(false) {}
00062 };
00063 
00064 typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
00065 
00066 struct MCAsmMacro {
00067   StringRef Name;
00068   StringRef Body;
00069   MCAsmMacroParameters Parameters;
00070 
00071 public:
00072   MCAsmMacro(StringRef N, StringRef B, ArrayRef<MCAsmMacroParameter> P) :
00073     Name(N), Body(B), Parameters(P) {}
00074 };
00075 
00076 /// \brief Helper class for storing information about an active macro
00077 /// instantiation.
00078 struct MacroInstantiation {
00079   /// The location of the instantiation.
00080   SMLoc InstantiationLoc;
00081 
00082   /// The buffer where parsing should resume upon instantiation completion.
00083   int ExitBuffer;
00084 
00085   /// The location where parsing should resume upon instantiation completion.
00086   SMLoc ExitLoc;
00087 
00088   /// The depth of TheCondStack at the start of the instantiation.
00089   size_t CondStackDepth;
00090 
00091 public:
00092   MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
00093 };
00094 
00095 struct ParseStatementInfo {
00096   /// \brief The parsed operands from the last parsed statement.
00097   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
00098 
00099   /// \brief The opcode from the last parsed instruction.
00100   unsigned Opcode;
00101 
00102   /// \brief Was there an error parsing the inline assembly?
00103   bool ParseError;
00104 
00105   SmallVectorImpl<AsmRewrite> *AsmRewrites;
00106 
00107   ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
00108   ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
00109     : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
00110 };
00111 
00112 /// \brief The concrete assembly parser instance.
00113 class AsmParser : public MCAsmParser {
00114   AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
00115   void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
00116 private:
00117   AsmLexer Lexer;
00118   MCContext &Ctx;
00119   MCStreamer &Out;
00120   const MCAsmInfo &MAI;
00121   SourceMgr &SrcMgr;
00122   SourceMgr::DiagHandlerTy SavedDiagHandler;
00123   void *SavedDiagContext;
00124   MCAsmParserExtension *PlatformParser;
00125 
00126   /// This is the current buffer index we're lexing from as managed by the
00127   /// SourceMgr object.
00128   unsigned CurBuffer;
00129 
00130   AsmCond TheCondState;
00131   std::vector<AsmCond> TheCondStack;
00132 
00133   /// \brief maps directive names to handler methods in parser
00134   /// extensions. Extensions register themselves in this map by calling
00135   /// addDirectiveHandler.
00136   StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
00137 
00138   /// \brief Map of currently defined macros.
00139   StringMap<MCAsmMacro*> MacroMap;
00140 
00141   /// \brief Stack of active macro instantiations.
00142   std::vector<MacroInstantiation*> ActiveMacros;
00143 
00144   /// \brief List of bodies of anonymous macros.
00145   std::deque<MCAsmMacro> MacroLikeBodies;
00146 
00147   /// Boolean tracking whether macro substitution is enabled.
00148   unsigned MacrosEnabledFlag : 1;
00149 
00150   /// Flag tracking whether any errors have been encountered.
00151   unsigned HadError : 1;
00152 
00153   /// The values from the last parsed cpp hash file line comment if any.
00154   StringRef CppHashFilename;
00155   int64_t CppHashLineNumber;
00156   SMLoc CppHashLoc;
00157   unsigned CppHashBuf;
00158   /// When generating dwarf for assembly source files we need to calculate the
00159   /// logical line number based on the last parsed cpp hash file line comment
00160   /// and current line. Since this is slow and messes up the SourceMgr's
00161   /// cache we save the last info we queried with SrcMgr.FindLineNumber().
00162   SMLoc LastQueryIDLoc;
00163   unsigned LastQueryBuffer;
00164   unsigned LastQueryLine;
00165 
00166   /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
00167   unsigned AssemblerDialect;
00168 
00169   /// \brief is Darwin compatibility enabled?
00170   bool IsDarwin;
00171 
00172   /// \brief Are we parsing ms-style inline assembly?
00173   bool ParsingInlineAsm;
00174 
00175 public:
00176   AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
00177             const MCAsmInfo &MAI);
00178   virtual ~AsmParser();
00179 
00180   bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
00181 
00182   void addDirectiveHandler(StringRef Directive,
00183                            ExtensionDirectiveHandler Handler) override {
00184     ExtensionDirectiveMap[Directive] = Handler;
00185   }
00186 
00187 public:
00188   /// @name MCAsmParser Interface
00189   /// {
00190 
00191   SourceMgr &getSourceManager() override { return SrcMgr; }
00192   MCAsmLexer &getLexer() override { return Lexer; }
00193   MCContext &getContext() override { return Ctx; }
00194   MCStreamer &getStreamer() override { return Out; }
00195   unsigned getAssemblerDialect() override {
00196     if (AssemblerDialect == ~0U)
00197       return MAI.getAssemblerDialect();
00198     else
00199       return AssemblerDialect;
00200   }
00201   void setAssemblerDialect(unsigned i) override {
00202     AssemblerDialect = i;
00203   }
00204 
00205   void Note(SMLoc L, const Twine &Msg,
00206             ArrayRef<SMRange> Ranges = None) override;
00207   bool Warning(SMLoc L, const Twine &Msg,
00208                ArrayRef<SMRange> Ranges = None) override;
00209   bool Error(SMLoc L, const Twine &Msg,
00210              ArrayRef<SMRange> Ranges = None) override;
00211 
00212   const AsmToken &Lex() override;
00213 
00214   void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
00215   bool isParsingInlineAsm() override { return ParsingInlineAsm; }
00216 
00217   bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
00218                         unsigned &NumOutputs, unsigned &NumInputs,
00219                         SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
00220                         SmallVectorImpl<std::string> &Constraints,
00221                         SmallVectorImpl<std::string> &Clobbers,
00222                         const MCInstrInfo *MII, const MCInstPrinter *IP,
00223                         MCAsmParserSemaCallback &SI) override;
00224 
00225   bool parseExpression(const MCExpr *&Res);
00226   bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
00227   bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
00228   bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
00229   bool parseAbsoluteExpression(int64_t &Res) override;
00230 
00231   /// \brief Parse an identifier or string (as a quoted identifier)
00232   /// and set \p Res to the identifier contents.
00233   bool parseIdentifier(StringRef &Res) override;
00234   void eatToEndOfStatement() override;
00235 
00236   void checkForValidSection() override;
00237   /// }
00238 
00239 private:
00240 
00241   bool parseStatement(ParseStatementInfo &Info);
00242   void eatToEndOfLine();
00243   bool parseCppHashLineFilenameComment(const SMLoc &L);
00244 
00245   void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
00246                         ArrayRef<MCAsmMacroParameter> Parameters);
00247   bool expandMacro(raw_svector_ostream &OS, StringRef Body,
00248                    ArrayRef<MCAsmMacroParameter> Parameters,
00249                    ArrayRef<MCAsmMacroArgument> A,
00250                    const SMLoc &L);
00251 
00252   /// \brief Are macros enabled in the parser?
00253   bool areMacrosEnabled() {return MacrosEnabledFlag;}
00254 
00255   /// \brief Control a flag in the parser that enables or disables macros.
00256   void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
00257 
00258   /// \brief Lookup a previously defined macro.
00259   /// \param Name Macro name.
00260   /// \returns Pointer to macro. NULL if no such macro was defined.
00261   const MCAsmMacro* lookupMacro(StringRef Name);
00262 
00263   /// \brief Define a new macro with the given name and information.
00264   void defineMacro(StringRef Name, const MCAsmMacro& Macro);
00265 
00266   /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
00267   void undefineMacro(StringRef Name);
00268 
00269   /// \brief Are we inside a macro instantiation?
00270   bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
00271 
00272   /// \brief Handle entry to macro instantiation.
00273   ///
00274   /// \param M The macro.
00275   /// \param NameLoc Instantiation location.
00276   bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
00277 
00278   /// \brief Handle exit from macro instantiation.
00279   void handleMacroExit();
00280 
00281   /// \brief Extract AsmTokens for a macro argument.
00282   bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
00283 
00284   /// \brief Parse all macro arguments for a given macro.
00285   bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
00286 
00287   void printMacroInstantiations();
00288   void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
00289                     ArrayRef<SMRange> Ranges = None) const {
00290     SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
00291   }
00292   static void DiagHandler(const SMDiagnostic &Diag, void *Context);
00293 
00294   /// \brief Enter the specified file. This returns true on failure.
00295   bool enterIncludeFile(const std::string &Filename);
00296 
00297   /// \brief Process the specified file for the .incbin directive.
00298   /// This returns true on failure.
00299   bool processIncbinFile(const std::string &Filename);
00300 
00301   /// \brief Reset the current lexer position to that given by \p Loc. The
00302   /// current token is not set; clients should ensure Lex() is called
00303   /// subsequently.
00304   ///
00305   /// \param InBuffer If not 0, should be the known buffer id that contains the
00306   /// location.
00307   void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
00308 
00309   /// \brief Parse up to the end of statement and a return the contents from the
00310   /// current token until the end of the statement; the current token on exit
00311   /// will be either the EndOfStatement or EOF.
00312   StringRef parseStringToEndOfStatement() override;
00313 
00314   /// \brief Parse until the end of a statement or a comma is encountered,
00315   /// return the contents from the current token up to the end or comma.
00316   StringRef parseStringToComma();
00317 
00318   bool parseAssignment(StringRef Name, bool allow_redef,
00319                        bool NoDeadStrip = false);
00320 
00321   bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
00322   bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
00323   bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
00324 
00325   bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
00326 
00327   // Generic (target and platform independent) directive parsing.
00328   enum DirectiveKind {
00329     DK_NO_DIRECTIVE, // Placeholder
00330     DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
00331     DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
00332     DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
00333     DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
00334     DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
00335     DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
00336     DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
00337     DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
00338     DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
00339     DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
00340     DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
00341     DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
00342     DK_ELSEIF, DK_ELSE, DK_ENDIF,
00343     DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
00344     DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
00345     DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
00346     DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
00347     DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
00348     DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
00349     DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
00350     DK_MACROS_ON, DK_MACROS_OFF,
00351     DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
00352     DK_SLEB128, DK_ULEB128,
00353     DK_ERR, DK_ERROR, DK_WARNING,
00354     DK_END
00355   };
00356 
00357   /// \brief Maps directive name --> DirectiveKind enum, for
00358   /// directives parsed by this class.
00359   StringMap<DirectiveKind> DirectiveKindMap;
00360 
00361   // ".ascii", ".asciz", ".string"
00362   bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
00363   bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
00364   bool parseDirectiveOctaValue(); // ".octa"
00365   bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
00366   bool parseDirectiveFill(); // ".fill"
00367   bool parseDirectiveZero(); // ".zero"
00368   // ".set", ".equ", ".equiv"
00369   bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
00370   bool parseDirectiveOrg(); // ".org"
00371   // ".align{,32}", ".p2align{,w,l}"
00372   bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
00373 
00374   // ".file", ".line", ".loc", ".stabs"
00375   bool parseDirectiveFile(SMLoc DirectiveLoc);
00376   bool parseDirectiveLine();
00377   bool parseDirectiveLoc();
00378   bool parseDirectiveStabs();
00379 
00380   // .cfi directives
00381   bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
00382   bool parseDirectiveCFIWindowSave();
00383   bool parseDirectiveCFISections();
00384   bool parseDirectiveCFIStartProc();
00385   bool parseDirectiveCFIEndProc();
00386   bool parseDirectiveCFIDefCfaOffset();
00387   bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
00388   bool parseDirectiveCFIAdjustCfaOffset();
00389   bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
00390   bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
00391   bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
00392   bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
00393   bool parseDirectiveCFIRememberState();
00394   bool parseDirectiveCFIRestoreState();
00395   bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
00396   bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
00397   bool parseDirectiveCFIEscape();
00398   bool parseDirectiveCFISignalFrame();
00399   bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
00400 
00401   // macro directives
00402   bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
00403   bool parseDirectiveExitMacro(StringRef Directive);
00404   bool parseDirectiveEndMacro(StringRef Directive);
00405   bool parseDirectiveMacro(SMLoc DirectiveLoc);
00406   bool parseDirectiveMacrosOnOff(StringRef Directive);
00407 
00408   // ".bundle_align_mode"
00409   bool parseDirectiveBundleAlignMode();
00410   // ".bundle_lock"
00411   bool parseDirectiveBundleLock();
00412   // ".bundle_unlock"
00413   bool parseDirectiveBundleUnlock();
00414 
00415   // ".space", ".skip"
00416   bool parseDirectiveSpace(StringRef IDVal);
00417 
00418   // .sleb128 (Signed=true) and .uleb128 (Signed=false)
00419   bool parseDirectiveLEB128(bool Signed);
00420 
00421   /// \brief Parse a directive like ".globl" which
00422   /// accepts a single symbol (which should be a label or an external).
00423   bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
00424 
00425   bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
00426 
00427   bool parseDirectiveAbort(); // ".abort"
00428   bool parseDirectiveInclude(); // ".include"
00429   bool parseDirectiveIncbin(); // ".incbin"
00430 
00431   // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
00432   bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
00433   // ".ifb" or ".ifnb", depending on ExpectBlank.
00434   bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
00435   // ".ifc" or ".ifnc", depending on ExpectEqual.
00436   bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
00437   // ".ifeqs"
00438   bool parseDirectiveIfeqs(SMLoc DirectiveLoc);
00439   // ".ifdef" or ".ifndef", depending on expect_defined
00440   bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
00441   bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
00442   bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
00443   bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
00444   bool parseEscapedString(std::string &Data) override;
00445 
00446   const MCExpr *applyModifierToExpr(const MCExpr *E,
00447                                     MCSymbolRefExpr::VariantKind Variant);
00448 
00449   // Macro-like directives
00450   MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
00451   void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
00452                                 raw_svector_ostream &OS);
00453   bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
00454   bool parseDirectiveIrp(SMLoc DirectiveLoc);  // ".irp"
00455   bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
00456   bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
00457 
00458   // "_emit" or "__emit"
00459   bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
00460                             size_t Len);
00461 
00462   // "align"
00463   bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
00464 
00465   // "end"
00466   bool parseDirectiveEnd(SMLoc DirectiveLoc);
00467 
00468   // ".err" or ".error"
00469   bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
00470 
00471   // ".warning"
00472   bool parseDirectiveWarning(SMLoc DirectiveLoc);
00473 
00474   void initializeDirectiveKindMap();
00475 };
00476 }
00477 
00478 namespace llvm {
00479 
00480 extern MCAsmParserExtension *createDarwinAsmParser();
00481 extern MCAsmParserExtension *createELFAsmParser();
00482 extern MCAsmParserExtension *createCOFFAsmParser();
00483 
00484 }
00485 
00486 enum { DEFAULT_ADDRSPACE = 0 };
00487 
00488 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
00489                      const MCAsmInfo &_MAI)
00490     : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
00491       PlatformParser(nullptr), CurBuffer(_SM.getMainFileID()),
00492       MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
00493       AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
00494   // Save the old handler.
00495   SavedDiagHandler = SrcMgr.getDiagHandler();
00496   SavedDiagContext = SrcMgr.getDiagContext();
00497   // Set our own handler which calls the saved handler.
00498   SrcMgr.setDiagHandler(DiagHandler, this);
00499   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
00500 
00501   // Initialize the platform / file format parser.
00502   switch (_Ctx.getObjectFileInfo()->getObjectFileType()) {
00503   case MCObjectFileInfo::IsCOFF:
00504       PlatformParser = createCOFFAsmParser();
00505       PlatformParser->Initialize(*this);
00506       break;
00507   case MCObjectFileInfo::IsMachO:
00508       PlatformParser = createDarwinAsmParser();
00509       PlatformParser->Initialize(*this);
00510       IsDarwin = true;
00511       break;
00512   case MCObjectFileInfo::IsELF:
00513       PlatformParser = createELFAsmParser();
00514       PlatformParser->Initialize(*this);
00515       break;
00516   }
00517 
00518   initializeDirectiveKindMap();
00519 }
00520 
00521 AsmParser::~AsmParser() {
00522   assert((HadError || ActiveMacros.empty()) &&
00523          "Unexpected active macro instantiation!");
00524 
00525   // Destroy any macros.
00526   for (StringMap<MCAsmMacro *>::iterator it = MacroMap.begin(),
00527                                          ie = MacroMap.end();
00528        it != ie; ++it)
00529     delete it->getValue();
00530 
00531   delete PlatformParser;
00532 }
00533 
00534 void AsmParser::printMacroInstantiations() {
00535   // Print the active macro instantiation stack.
00536   for (std::vector<MacroInstantiation *>::const_reverse_iterator
00537            it = ActiveMacros.rbegin(),
00538            ie = ActiveMacros.rend();
00539        it != ie; ++it)
00540     printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
00541                  "while in macro instantiation");
00542 }
00543 
00544 void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
00545   printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
00546   printMacroInstantiations();
00547 }
00548 
00549 bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
00550   if (getTargetParser().getTargetOptions().MCFatalWarnings)
00551     return Error(L, Msg, Ranges);
00552   printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
00553   printMacroInstantiations();
00554   return false;
00555 }
00556 
00557 bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
00558   HadError = true;
00559   printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
00560   printMacroInstantiations();
00561   return true;
00562 }
00563 
00564 bool AsmParser::enterIncludeFile(const std::string &Filename) {
00565   std::string IncludedFile;
00566   unsigned NewBuf =
00567       SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
00568   if (!NewBuf)
00569     return true;
00570 
00571   CurBuffer = NewBuf;
00572   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
00573   return false;
00574 }
00575 
00576 /// Process the specified .incbin file by searching for it in the include paths
00577 /// then just emitting the byte contents of the file to the streamer. This
00578 /// returns true on failure.
00579 bool AsmParser::processIncbinFile(const std::string &Filename) {
00580   std::string IncludedFile;
00581   unsigned NewBuf =
00582       SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
00583   if (!NewBuf)
00584     return true;
00585 
00586   // Pick up the bytes from the file and emit them.
00587   getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
00588   return false;
00589 }
00590 
00591 void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
00592   CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
00593   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
00594                   Loc.getPointer());
00595 }
00596 
00597 const AsmToken &AsmParser::Lex() {
00598   const AsmToken *tok = &Lexer.Lex();
00599 
00600   if (tok->is(AsmToken::Eof)) {
00601     // If this is the end of an included file, pop the parent file off the
00602     // include stack.
00603     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
00604     if (ParentIncludeLoc != SMLoc()) {
00605       jumpToLoc(ParentIncludeLoc);
00606       tok = &Lexer.Lex();
00607     }
00608   }
00609 
00610   if (tok->is(AsmToken::Error))
00611     Error(Lexer.getErrLoc(), Lexer.getErr());
00612 
00613   return *tok;
00614 }
00615 
00616 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
00617   // Create the initial section, if requested.
00618   if (!NoInitialTextSection)
00619     Out.InitSections();
00620 
00621   // Prime the lexer.
00622   Lex();
00623 
00624   HadError = false;
00625   AsmCond StartingCondState = TheCondState;
00626 
00627   // If we are generating dwarf for assembly source files save the initial text
00628   // section and generate a .file directive.
00629   if (getContext().getGenDwarfForAssembly()) {
00630     MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
00631     getStreamer().EmitLabel(SectionStartSym);
00632     auto InsertResult = getContext().addGenDwarfSection(
00633         getStreamer().getCurrentSection().first);
00634     assert(InsertResult.second && ".text section should not have debug info yet");
00635     InsertResult.first->second.first = SectionStartSym;
00636     getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
00637         0, StringRef(), getContext().getMainFileName()));
00638   }
00639 
00640   // While we have input, parse each statement.
00641   while (Lexer.isNot(AsmToken::Eof)) {
00642     ParseStatementInfo Info;
00643     if (!parseStatement(Info))
00644       continue;
00645 
00646     // We had an error, validate that one was emitted and recover by skipping to
00647     // the next line.
00648     assert(HadError && "Parse statement returned an error, but none emitted!");
00649     eatToEndOfStatement();
00650   }
00651 
00652   if (TheCondState.TheCond != StartingCondState.TheCond ||
00653       TheCondState.Ignore != StartingCondState.Ignore)
00654     return TokError("unmatched .ifs or .elses");
00655 
00656   // Check to see there are no empty DwarfFile slots.
00657   const auto &LineTables = getContext().getMCDwarfLineTables();
00658   if (!LineTables.empty()) {
00659     unsigned Index = 0;
00660     for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
00661       if (File.Name.empty() && Index != 0)
00662         TokError("unassigned file number: " + Twine(Index) +
00663                  " for .file directives");
00664       ++Index;
00665     }
00666   }
00667 
00668   // Check to see that all assembler local symbols were actually defined.
00669   // Targets that don't do subsections via symbols may not want this, though,
00670   // so conservatively exclude them. Only do this if we're finalizing, though,
00671   // as otherwise we won't necessarilly have seen everything yet.
00672   if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
00673     const MCContext::SymbolTable &Symbols = getContext().getSymbols();
00674     for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
00675                                                 e = Symbols.end();
00676          i != e; ++i) {
00677       MCSymbol *Sym = i->getValue();
00678       // Variable symbols may not be marked as defined, so check those
00679       // explicitly. If we know it's a variable, we have a definition for
00680       // the purposes of this check.
00681       if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
00682         // FIXME: We would really like to refer back to where the symbol was
00683         // first referenced for a source location. We need to add something
00684         // to track that. Currently, we just point to the end of the file.
00685         printMessage(
00686             getLexer().getLoc(), SourceMgr::DK_Error,
00687             "assembler local symbol '" + Sym->getName() + "' not defined");
00688     }
00689   }
00690 
00691   // Finalize the output stream if there are no errors and if the client wants
00692   // us to.
00693   if (!HadError && !NoFinalize)
00694     Out.Finish();
00695 
00696   return HadError;
00697 }
00698 
00699 void AsmParser::checkForValidSection() {
00700   if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
00701     TokError("expected section directive before assembly directive");
00702     Out.InitSections();
00703   }
00704 }
00705 
00706 /// \brief Throw away the rest of the line for testing purposes.
00707 void AsmParser::eatToEndOfStatement() {
00708   while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
00709     Lex();
00710 
00711   // Eat EOL.
00712   if (Lexer.is(AsmToken::EndOfStatement))
00713     Lex();
00714 }
00715 
00716 StringRef AsmParser::parseStringToEndOfStatement() {
00717   const char *Start = getTok().getLoc().getPointer();
00718 
00719   while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
00720     Lex();
00721 
00722   const char *End = getTok().getLoc().getPointer();
00723   return StringRef(Start, End - Start);
00724 }
00725 
00726 StringRef AsmParser::parseStringToComma() {
00727   const char *Start = getTok().getLoc().getPointer();
00728 
00729   while (Lexer.isNot(AsmToken::EndOfStatement) &&
00730          Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
00731     Lex();
00732 
00733   const char *End = getTok().getLoc().getPointer();
00734   return StringRef(Start, End - Start);
00735 }
00736 
00737 /// \brief Parse a paren expression and return it.
00738 /// NOTE: This assumes the leading '(' has already been consumed.
00739 ///
00740 /// parenexpr ::= expr)
00741 ///
00742 bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
00743   if (parseExpression(Res))
00744     return true;
00745   if (Lexer.isNot(AsmToken::RParen))
00746     return TokError("expected ')' in parentheses expression");
00747   EndLoc = Lexer.getTok().getEndLoc();
00748   Lex();
00749   return false;
00750 }
00751 
00752 /// \brief Parse a bracket expression and return it.
00753 /// NOTE: This assumes the leading '[' has already been consumed.
00754 ///
00755 /// bracketexpr ::= expr]
00756 ///
00757 bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
00758   if (parseExpression(Res))
00759     return true;
00760   if (Lexer.isNot(AsmToken::RBrac))
00761     return TokError("expected ']' in brackets expression");
00762   EndLoc = Lexer.getTok().getEndLoc();
00763   Lex();
00764   return false;
00765 }
00766 
00767 /// \brief Parse a primary expression and return it.
00768 ///  primaryexpr ::= (parenexpr
00769 ///  primaryexpr ::= symbol
00770 ///  primaryexpr ::= number
00771 ///  primaryexpr ::= '.'
00772 ///  primaryexpr ::= ~,+,- primaryexpr
00773 bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
00774   SMLoc FirstTokenLoc = getLexer().getLoc();
00775   AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
00776   switch (FirstTokenKind) {
00777   default:
00778     return TokError("unknown token in expression");
00779   // If we have an error assume that we've already handled it.
00780   case AsmToken::Error:
00781     return true;
00782   case AsmToken::Exclaim:
00783     Lex(); // Eat the operator.
00784     if (parsePrimaryExpr(Res, EndLoc))
00785       return true;
00786     Res = MCUnaryExpr::CreateLNot(Res, getContext());
00787     return false;
00788   case AsmToken::Dollar:
00789   case AsmToken::At:
00790   case AsmToken::String:
00791   case AsmToken::Identifier: {
00792     StringRef Identifier;
00793     if (parseIdentifier(Identifier)) {
00794       if (FirstTokenKind == AsmToken::Dollar) {
00795         if (Lexer.getMAI().getDollarIsPC()) {
00796           // This is a '$' reference, which references the current PC.  Emit a
00797           // temporary label to the streamer and refer to it.
00798           MCSymbol *Sym = Ctx.CreateTempSymbol();
00799           Out.EmitLabel(Sym);
00800           Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
00801                                         getContext());
00802           EndLoc = FirstTokenLoc;
00803           return false;
00804         }
00805         return Error(FirstTokenLoc, "invalid token in expression");
00806       }
00807     }
00808     // Parse symbol variant
00809     std::pair<StringRef, StringRef> Split;
00810     if (!MAI.useParensForSymbolVariant()) {
00811       if (FirstTokenKind == AsmToken::String) {
00812         if (Lexer.is(AsmToken::At)) {
00813           Lexer.Lex(); // eat @
00814           SMLoc AtLoc = getLexer().getLoc();
00815           StringRef VName;
00816           if (parseIdentifier(VName))
00817             return Error(AtLoc, "expected symbol variant after '@'");
00818 
00819           Split = std::make_pair(Identifier, VName);
00820         }
00821       } else {
00822         Split = Identifier.split('@');
00823       }
00824     } else if (Lexer.is(AsmToken::LParen)) {
00825       Lexer.Lex(); // eat (
00826       StringRef VName;
00827       parseIdentifier(VName);
00828       if (Lexer.isNot(AsmToken::RParen)) {
00829           return Error(Lexer.getTok().getLoc(),
00830                        "unexpected token in variant, expected ')'");
00831       }
00832       Lexer.Lex(); // eat )
00833       Split = std::make_pair(Identifier, VName);
00834     }
00835 
00836     EndLoc = SMLoc::getFromPointer(Identifier.end());
00837 
00838     // This is a symbol reference.
00839     StringRef SymbolName = Identifier;
00840     MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
00841 
00842     // Lookup the symbol variant if used.
00843     if (Split.second.size()) {
00844       Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
00845       if (Variant != MCSymbolRefExpr::VK_Invalid) {
00846         SymbolName = Split.first;
00847       } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
00848         Variant = MCSymbolRefExpr::VK_None;
00849       } else {
00850         return Error(SMLoc::getFromPointer(Split.second.begin()),
00851                      "invalid variant '" + Split.second + "'");
00852       }
00853     }
00854 
00855     MCSymbol *Sym = getContext().GetOrCreateSymbol(SymbolName);
00856 
00857     // If this is an absolute variable reference, substitute it now to preserve
00858     // semantics in the face of reassignment.
00859     if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
00860       if (Variant)
00861         return Error(EndLoc, "unexpected modifier on variable reference");
00862 
00863       Res = Sym->getVariableValue();
00864       return false;
00865     }
00866 
00867     // Otherwise create a symbol ref.
00868     Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
00869     return false;
00870   }
00871   case AsmToken::BigNum:
00872     return TokError("literal value out of range for directive");
00873   case AsmToken::Integer: {
00874     SMLoc Loc = getTok().getLoc();
00875     int64_t IntVal = getTok().getIntVal();
00876     Res = MCConstantExpr::Create(IntVal, getContext());
00877     EndLoc = Lexer.getTok().getEndLoc();
00878     Lex(); // Eat token.
00879     // Look for 'b' or 'f' following an Integer as a directional label
00880     if (Lexer.getKind() == AsmToken::Identifier) {
00881       StringRef IDVal = getTok().getString();
00882       // Lookup the symbol variant if used.
00883       std::pair<StringRef, StringRef> Split = IDVal.split('@');
00884       MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
00885       if (Split.first.size() != IDVal.size()) {
00886         Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
00887         if (Variant == MCSymbolRefExpr::VK_Invalid)
00888           return TokError("invalid variant '" + Split.second + "'");
00889         IDVal = Split.first;
00890       }
00891       if (IDVal == "f" || IDVal == "b") {
00892         MCSymbol *Sym =
00893             Ctx.GetDirectionalLocalSymbol(IntVal, IDVal == "b");
00894         Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
00895         if (IDVal == "b" && Sym->isUndefined())
00896           return Error(Loc, "invalid reference to undefined symbol");
00897         EndLoc = Lexer.getTok().getEndLoc();
00898         Lex(); // Eat identifier.
00899       }
00900     }
00901     return false;
00902   }
00903   case AsmToken::Real: {
00904     APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
00905     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
00906     Res = MCConstantExpr::Create(IntVal, getContext());
00907     EndLoc = Lexer.getTok().getEndLoc();
00908     Lex(); // Eat token.
00909     return false;
00910   }
00911   case AsmToken::Dot: {
00912     // This is a '.' reference, which references the current PC.  Emit a
00913     // temporary label to the streamer and refer to it.
00914     MCSymbol *Sym = Ctx.CreateTempSymbol();
00915     Out.EmitLabel(Sym);
00916     Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
00917     EndLoc = Lexer.getTok().getEndLoc();
00918     Lex(); // Eat identifier.
00919     return false;
00920   }
00921   case AsmToken::LParen:
00922     Lex(); // Eat the '('.
00923     return parseParenExpr(Res, EndLoc);
00924   case AsmToken::LBrac:
00925     if (!PlatformParser->HasBracketExpressions())
00926       return TokError("brackets expression not supported on this target");
00927     Lex(); // Eat the '['.
00928     return parseBracketExpr(Res, EndLoc);
00929   case AsmToken::Minus:
00930     Lex(); // Eat the operator.
00931     if (parsePrimaryExpr(Res, EndLoc))
00932       return true;
00933     Res = MCUnaryExpr::CreateMinus(Res, getContext());
00934     return false;
00935   case AsmToken::Plus:
00936     Lex(); // Eat the operator.
00937     if (parsePrimaryExpr(Res, EndLoc))
00938       return true;
00939     Res = MCUnaryExpr::CreatePlus(Res, getContext());
00940     return false;
00941   case AsmToken::Tilde:
00942     Lex(); // Eat the operator.
00943     if (parsePrimaryExpr(Res, EndLoc))
00944       return true;
00945     Res = MCUnaryExpr::CreateNot(Res, getContext());
00946     return false;
00947   }
00948 }
00949 
00950 bool AsmParser::parseExpression(const MCExpr *&Res) {
00951   SMLoc EndLoc;
00952   return parseExpression(Res, EndLoc);
00953 }
00954 
00955 const MCExpr *
00956 AsmParser::applyModifierToExpr(const MCExpr *E,
00957                                MCSymbolRefExpr::VariantKind Variant) {
00958   // Ask the target implementation about this expression first.
00959   const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
00960   if (NewE)
00961     return NewE;
00962   // Recurse over the given expression, rebuilding it to apply the given variant
00963   // if there is exactly one symbol.
00964   switch (E->getKind()) {
00965   case MCExpr::Target:
00966   case MCExpr::Constant:
00967     return nullptr;
00968 
00969   case MCExpr::SymbolRef: {
00970     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
00971 
00972     if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
00973       TokError("invalid variant on expression '" + getTok().getIdentifier() +
00974                "' (already modified)");
00975       return E;
00976     }
00977 
00978     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
00979   }
00980 
00981   case MCExpr::Unary: {
00982     const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
00983     const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
00984     if (!Sub)
00985       return nullptr;
00986     return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
00987   }
00988 
00989   case MCExpr::Binary: {
00990     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
00991     const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
00992     const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
00993 
00994     if (!LHS && !RHS)
00995       return nullptr;
00996 
00997     if (!LHS)
00998       LHS = BE->getLHS();
00999     if (!RHS)
01000       RHS = BE->getRHS();
01001 
01002     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
01003   }
01004   }
01005 
01006   llvm_unreachable("Invalid expression kind!");
01007 }
01008 
01009 /// \brief Parse an expression and return it.
01010 ///
01011 ///  expr ::= expr &&,|| expr               -> lowest.
01012 ///  expr ::= expr |,^,&,! expr
01013 ///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
01014 ///  expr ::= expr <<,>> expr
01015 ///  expr ::= expr +,- expr
01016 ///  expr ::= expr *,/,% expr               -> highest.
01017 ///  expr ::= primaryexpr
01018 ///
01019 bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
01020   // Parse the expression.
01021   Res = nullptr;
01022   if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
01023     return true;
01024 
01025   // As a special case, we support 'a op b @ modifier' by rewriting the
01026   // expression to include the modifier. This is inefficient, but in general we
01027   // expect users to use 'a@modifier op b'.
01028   if (Lexer.getKind() == AsmToken::At) {
01029     Lex();
01030 
01031     if (Lexer.isNot(AsmToken::Identifier))
01032       return TokError("unexpected symbol modifier following '@'");
01033 
01034     MCSymbolRefExpr::VariantKind Variant =
01035         MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
01036     if (Variant == MCSymbolRefExpr::VK_Invalid)
01037       return TokError("invalid variant '" + getTok().getIdentifier() + "'");
01038 
01039     const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
01040     if (!ModifiedRes) {
01041       return TokError("invalid modifier '" + getTok().getIdentifier() +
01042                       "' (no symbols present)");
01043     }
01044 
01045     Res = ModifiedRes;
01046     Lex();
01047   }
01048 
01049   // Try to constant fold it up front, if possible.
01050   int64_t Value;
01051   if (Res->EvaluateAsAbsolute(Value))
01052     Res = MCConstantExpr::Create(Value, getContext());
01053 
01054   return false;
01055 }
01056 
01057 bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
01058   Res = nullptr;
01059   return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
01060 }
01061 
01062 bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
01063   const MCExpr *Expr;
01064 
01065   SMLoc StartLoc = Lexer.getLoc();
01066   if (parseExpression(Expr))
01067     return true;
01068 
01069   if (!Expr->EvaluateAsAbsolute(Res))
01070     return Error(StartLoc, "expected absolute expression");
01071 
01072   return false;
01073 }
01074 
01075 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
01076                                    MCBinaryExpr::Opcode &Kind) {
01077   switch (K) {
01078   default:
01079     return 0; // not a binop.
01080 
01081   // Lowest Precedence: &&, ||
01082   case AsmToken::AmpAmp:
01083     Kind = MCBinaryExpr::LAnd;
01084     return 1;
01085   case AsmToken::PipePipe:
01086     Kind = MCBinaryExpr::LOr;
01087     return 1;
01088 
01089   // Low Precedence: |, &, ^
01090   //
01091   // FIXME: gas seems to support '!' as an infix operator?
01092   case AsmToken::Pipe:
01093     Kind = MCBinaryExpr::Or;
01094     return 2;
01095   case AsmToken::Caret:
01096     Kind = MCBinaryExpr::Xor;
01097     return 2;
01098   case AsmToken::Amp:
01099     Kind = MCBinaryExpr::And;
01100     return 2;
01101 
01102   // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
01103   case AsmToken::EqualEqual:
01104     Kind = MCBinaryExpr::EQ;
01105     return 3;
01106   case AsmToken::ExclaimEqual:
01107   case AsmToken::LessGreater:
01108     Kind = MCBinaryExpr::NE;
01109     return 3;
01110   case AsmToken::Less:
01111     Kind = MCBinaryExpr::LT;
01112     return 3;
01113   case AsmToken::LessEqual:
01114     Kind = MCBinaryExpr::LTE;
01115     return 3;
01116   case AsmToken::Greater:
01117     Kind = MCBinaryExpr::GT;
01118     return 3;
01119   case AsmToken::GreaterEqual:
01120     Kind = MCBinaryExpr::GTE;
01121     return 3;
01122 
01123   // Intermediate Precedence: <<, >>
01124   case AsmToken::LessLess:
01125     Kind = MCBinaryExpr::Shl;
01126     return 4;
01127   case AsmToken::GreaterGreater:
01128     Kind = MCBinaryExpr::Shr;
01129     return 4;
01130 
01131   // High Intermediate Precedence: +, -
01132   case AsmToken::Plus:
01133     Kind = MCBinaryExpr::Add;
01134     return 5;
01135   case AsmToken::Minus:
01136     Kind = MCBinaryExpr::Sub;
01137     return 5;
01138 
01139   // Highest Precedence: *, /, %
01140   case AsmToken::Star:
01141     Kind = MCBinaryExpr::Mul;
01142     return 6;
01143   case AsmToken::Slash:
01144     Kind = MCBinaryExpr::Div;
01145     return 6;
01146   case AsmToken::Percent:
01147     Kind = MCBinaryExpr::Mod;
01148     return 6;
01149   }
01150 }
01151 
01152 /// \brief Parse all binary operators with precedence >= 'Precedence'.
01153 /// Res contains the LHS of the expression on input.
01154 bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
01155                               SMLoc &EndLoc) {
01156   while (1) {
01157     MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
01158     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
01159 
01160     // If the next token is lower precedence than we are allowed to eat, return
01161     // successfully with what we ate already.
01162     if (TokPrec < Precedence)
01163       return false;
01164 
01165     Lex();
01166 
01167     // Eat the next primary expression.
01168     const MCExpr *RHS;
01169     if (parsePrimaryExpr(RHS, EndLoc))
01170       return true;
01171 
01172     // If BinOp binds less tightly with RHS than the operator after RHS, let
01173     // the pending operator take RHS as its LHS.
01174     MCBinaryExpr::Opcode Dummy;
01175     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
01176     if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
01177       return true;
01178 
01179     // Merge LHS and RHS according to operator.
01180     Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
01181   }
01182 }
01183 
01184 /// ParseStatement:
01185 ///   ::= EndOfStatement
01186 ///   ::= Label* Directive ...Operands... EndOfStatement
01187 ///   ::= Label* Identifier OperandList* EndOfStatement
01188 bool AsmParser::parseStatement(ParseStatementInfo &Info) {
01189   if (Lexer.is(AsmToken::EndOfStatement)) {
01190     Out.AddBlankLine();
01191     Lex();
01192     return false;
01193   }
01194 
01195   // Statements always start with an identifier or are a full line comment.
01196   AsmToken ID = getTok();
01197   SMLoc IDLoc = ID.getLoc();
01198   StringRef IDVal;
01199   int64_t LocalLabelVal = -1;
01200   // A full line comment is a '#' as the first token.
01201   if (Lexer.is(AsmToken::Hash))
01202     return parseCppHashLineFilenameComment(IDLoc);
01203 
01204   // Allow an integer followed by a ':' as a directional local label.
01205   if (Lexer.is(AsmToken::Integer)) {
01206     LocalLabelVal = getTok().getIntVal();
01207     if (LocalLabelVal < 0) {
01208       if (!TheCondState.Ignore)
01209         return TokError("unexpected token at start of statement");
01210       IDVal = "";
01211     } else {
01212       IDVal = getTok().getString();
01213       Lex(); // Consume the integer token to be used as an identifier token.
01214       if (Lexer.getKind() != AsmToken::Colon) {
01215         if (!TheCondState.Ignore)
01216           return TokError("unexpected token at start of statement");
01217       }
01218     }
01219   } else if (Lexer.is(AsmToken::Dot)) {
01220     // Treat '.' as a valid identifier in this context.
01221     Lex();
01222     IDVal = ".";
01223   } else if (parseIdentifier(IDVal)) {
01224     if (!TheCondState.Ignore)
01225       return TokError("unexpected token at start of statement");
01226     IDVal = "";
01227   }
01228 
01229   // Handle conditional assembly here before checking for skipping.  We
01230   // have to do this so that .endif isn't skipped in a ".if 0" block for
01231   // example.
01232   StringMap<DirectiveKind>::const_iterator DirKindIt =
01233       DirectiveKindMap.find(IDVal);
01234   DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
01235                               ? DK_NO_DIRECTIVE
01236                               : DirKindIt->getValue();
01237   switch (DirKind) {
01238   default:
01239     break;
01240   case DK_IF:
01241   case DK_IFEQ:
01242   case DK_IFGE:
01243   case DK_IFGT:
01244   case DK_IFLE:
01245   case DK_IFLT:
01246   case DK_IFNE:
01247     return parseDirectiveIf(IDLoc, DirKind);
01248   case DK_IFB:
01249     return parseDirectiveIfb(IDLoc, true);
01250   case DK_IFNB:
01251     return parseDirectiveIfb(IDLoc, false);
01252   case DK_IFC:
01253     return parseDirectiveIfc(IDLoc, true);
01254   case DK_IFEQS:
01255     return parseDirectiveIfeqs(IDLoc);
01256   case DK_IFNC:
01257     return parseDirectiveIfc(IDLoc, false);
01258   case DK_IFDEF:
01259     return parseDirectiveIfdef(IDLoc, true);
01260   case DK_IFNDEF:
01261   case DK_IFNOTDEF:
01262     return parseDirectiveIfdef(IDLoc, false);
01263   case DK_ELSEIF:
01264     return parseDirectiveElseIf(IDLoc);
01265   case DK_ELSE:
01266     return parseDirectiveElse(IDLoc);
01267   case DK_ENDIF:
01268     return parseDirectiveEndIf(IDLoc);
01269   }
01270 
01271   // Ignore the statement if in the middle of inactive conditional
01272   // (e.g. ".if 0").
01273   if (TheCondState.Ignore) {
01274     eatToEndOfStatement();
01275     return false;
01276   }
01277 
01278   // FIXME: Recurse on local labels?
01279 
01280   // See what kind of statement we have.
01281   switch (Lexer.getKind()) {
01282   case AsmToken::Colon: {
01283     checkForValidSection();
01284 
01285     // identifier ':'   -> Label.
01286     Lex();
01287 
01288     // Diagnose attempt to use '.' as a label.
01289     if (IDVal == ".")
01290       return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
01291 
01292     // Diagnose attempt to use a variable as a label.
01293     //
01294     // FIXME: Diagnostics. Note the location of the definition as a label.
01295     // FIXME: This doesn't diagnose assignment to a symbol which has been
01296     // implicitly marked as external.
01297     MCSymbol *Sym;
01298     if (LocalLabelVal == -1)
01299       Sym = getContext().GetOrCreateSymbol(IDVal);
01300     else
01301       Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
01302     if (!Sym->isUndefined() || Sym->isVariable())
01303       return Error(IDLoc, "invalid symbol redefinition");
01304 
01305     // Emit the label.
01306     if (!ParsingInlineAsm)
01307       Out.EmitLabel(Sym);
01308 
01309     // If we are generating dwarf for assembly source files then gather the
01310     // info to make a dwarf label entry for this label if needed.
01311     if (getContext().getGenDwarfForAssembly())
01312       MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
01313                                  IDLoc);
01314 
01315     getTargetParser().onLabelParsed(Sym);
01316 
01317     // Consume any end of statement token, if present, to avoid spurious
01318     // AddBlankLine calls().
01319     if (Lexer.is(AsmToken::EndOfStatement)) {
01320       Lex();
01321       if (Lexer.is(AsmToken::Eof))
01322         return false;
01323     }
01324 
01325     return false;
01326   }
01327 
01328   case AsmToken::Equal:
01329     // identifier '=' ... -> assignment statement
01330     Lex();
01331 
01332     return parseAssignment(IDVal, true);
01333 
01334   default: // Normal instruction or directive.
01335     break;
01336   }
01337 
01338   // If macros are enabled, check to see if this is a macro instantiation.
01339   if (areMacrosEnabled())
01340     if (const MCAsmMacro *M = lookupMacro(IDVal)) {
01341       return handleMacroEntry(M, IDLoc);
01342     }
01343 
01344   // Otherwise, we have a normal instruction or directive.
01345 
01346   // Directives start with "."
01347   if (IDVal[0] == '.' && IDVal != ".") {
01348     // There are several entities interested in parsing directives:
01349     //
01350     // 1. The target-specific assembly parser. Some directives are target
01351     //    specific or may potentially behave differently on certain targets.
01352     // 2. Asm parser extensions. For example, platform-specific parsers
01353     //    (like the ELF parser) register themselves as extensions.
01354     // 3. The generic directive parser implemented by this class. These are
01355     //    all the directives that behave in a target and platform independent
01356     //    manner, or at least have a default behavior that's shared between
01357     //    all targets and platforms.
01358 
01359     // First query the target-specific parser. It will return 'true' if it
01360     // isn't interested in this directive.
01361     if (!getTargetParser().ParseDirective(ID))
01362       return false;
01363 
01364     // Next, check the extension directive map to see if any extension has
01365     // registered itself to parse this directive.
01366     std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
01367         ExtensionDirectiveMap.lookup(IDVal);
01368     if (Handler.first)
01369       return (*Handler.second)(Handler.first, IDVal, IDLoc);
01370 
01371     // Finally, if no one else is interested in this directive, it must be
01372     // generic and familiar to this class.
01373     switch (DirKind) {
01374     default:
01375       break;
01376     case DK_SET:
01377     case DK_EQU:
01378       return parseDirectiveSet(IDVal, true);
01379     case DK_EQUIV:
01380       return parseDirectiveSet(IDVal, false);
01381     case DK_ASCII:
01382       return parseDirectiveAscii(IDVal, false);
01383     case DK_ASCIZ:
01384     case DK_STRING:
01385       return parseDirectiveAscii(IDVal, true);
01386     case DK_BYTE:
01387       return parseDirectiveValue(1);
01388     case DK_SHORT:
01389     case DK_VALUE:
01390     case DK_2BYTE:
01391       return parseDirectiveValue(2);
01392     case DK_LONG:
01393     case DK_INT:
01394     case DK_4BYTE:
01395       return parseDirectiveValue(4);
01396     case DK_QUAD:
01397     case DK_8BYTE:
01398       return parseDirectiveValue(8);
01399     case DK_OCTA:
01400       return parseDirectiveOctaValue();
01401     case DK_SINGLE:
01402     case DK_FLOAT:
01403       return parseDirectiveRealValue(APFloat::IEEEsingle);
01404     case DK_DOUBLE:
01405       return parseDirectiveRealValue(APFloat::IEEEdouble);
01406     case DK_ALIGN: {
01407       bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
01408       return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
01409     }
01410     case DK_ALIGN32: {
01411       bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
01412       return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
01413     }
01414     case DK_BALIGN:
01415       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
01416     case DK_BALIGNW:
01417       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
01418     case DK_BALIGNL:
01419       return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
01420     case DK_P2ALIGN:
01421       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
01422     case DK_P2ALIGNW:
01423       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
01424     case DK_P2ALIGNL:
01425       return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
01426     case DK_ORG:
01427       return parseDirectiveOrg();
01428     case DK_FILL:
01429       return parseDirectiveFill();
01430     case DK_ZERO:
01431       return parseDirectiveZero();
01432     case DK_EXTERN:
01433       eatToEndOfStatement(); // .extern is the default, ignore it.
01434       return false;
01435     case DK_GLOBL:
01436     case DK_GLOBAL:
01437       return parseDirectiveSymbolAttribute(MCSA_Global);
01438     case DK_LAZY_REFERENCE:
01439       return parseDirectiveSymbolAttribute(MCSA_LazyReference);
01440     case DK_NO_DEAD_STRIP:
01441       return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
01442     case DK_SYMBOL_RESOLVER:
01443       return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
01444     case DK_PRIVATE_EXTERN:
01445       return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
01446     case DK_REFERENCE:
01447       return parseDirectiveSymbolAttribute(MCSA_Reference);
01448     case DK_WEAK_DEFINITION:
01449       return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
01450     case DK_WEAK_REFERENCE:
01451       return parseDirectiveSymbolAttribute(MCSA_WeakReference);
01452     case DK_WEAK_DEF_CAN_BE_HIDDEN:
01453       return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
01454     case DK_COMM:
01455     case DK_COMMON:
01456       return parseDirectiveComm(/*IsLocal=*/false);
01457     case DK_LCOMM:
01458       return parseDirectiveComm(/*IsLocal=*/true);
01459     case DK_ABORT:
01460       return parseDirectiveAbort();
01461     case DK_INCLUDE:
01462       return parseDirectiveInclude();
01463     case DK_INCBIN:
01464       return parseDirectiveIncbin();
01465     case DK_CODE16:
01466     case DK_CODE16GCC:
01467       return TokError(Twine(IDVal) + " not supported yet");
01468     case DK_REPT:
01469       return parseDirectiveRept(IDLoc, IDVal);
01470     case DK_IRP:
01471       return parseDirectiveIrp(IDLoc);
01472     case DK_IRPC:
01473       return parseDirectiveIrpc(IDLoc);
01474     case DK_ENDR:
01475       return parseDirectiveEndr(IDLoc);
01476     case DK_BUNDLE_ALIGN_MODE:
01477       return parseDirectiveBundleAlignMode();
01478     case DK_BUNDLE_LOCK:
01479       return parseDirectiveBundleLock();
01480     case DK_BUNDLE_UNLOCK:
01481       return parseDirectiveBundleUnlock();
01482     case DK_SLEB128:
01483       return parseDirectiveLEB128(true);
01484     case DK_ULEB128:
01485       return parseDirectiveLEB128(false);
01486     case DK_SPACE:
01487     case DK_SKIP:
01488       return parseDirectiveSpace(IDVal);
01489     case DK_FILE:
01490       return parseDirectiveFile(IDLoc);
01491     case DK_LINE:
01492       return parseDirectiveLine();
01493     case DK_LOC:
01494       return parseDirectiveLoc();
01495     case DK_STABS:
01496       return parseDirectiveStabs();
01497     case DK_CFI_SECTIONS:
01498       return parseDirectiveCFISections();
01499     case DK_CFI_STARTPROC:
01500       return parseDirectiveCFIStartProc();
01501     case DK_CFI_ENDPROC:
01502       return parseDirectiveCFIEndProc();
01503     case DK_CFI_DEF_CFA:
01504       return parseDirectiveCFIDefCfa(IDLoc);
01505     case DK_CFI_DEF_CFA_OFFSET:
01506       return parseDirectiveCFIDefCfaOffset();
01507     case DK_CFI_ADJUST_CFA_OFFSET:
01508       return parseDirectiveCFIAdjustCfaOffset();
01509     case DK_CFI_DEF_CFA_REGISTER:
01510       return parseDirectiveCFIDefCfaRegister(IDLoc);
01511     case DK_CFI_OFFSET:
01512       return parseDirectiveCFIOffset(IDLoc);
01513     case DK_CFI_REL_OFFSET:
01514       return parseDirectiveCFIRelOffset(IDLoc);
01515     case DK_CFI_PERSONALITY:
01516       return parseDirectiveCFIPersonalityOrLsda(true);
01517     case DK_CFI_LSDA:
01518       return parseDirectiveCFIPersonalityOrLsda(false);
01519     case DK_CFI_REMEMBER_STATE:
01520       return parseDirectiveCFIRememberState();
01521     case DK_CFI_RESTORE_STATE:
01522       return parseDirectiveCFIRestoreState();
01523     case DK_CFI_SAME_VALUE:
01524       return parseDirectiveCFISameValue(IDLoc);
01525     case DK_CFI_RESTORE:
01526       return parseDirectiveCFIRestore(IDLoc);
01527     case DK_CFI_ESCAPE:
01528       return parseDirectiveCFIEscape();
01529     case DK_CFI_SIGNAL_FRAME:
01530       return parseDirectiveCFISignalFrame();
01531     case DK_CFI_UNDEFINED:
01532       return parseDirectiveCFIUndefined(IDLoc);
01533     case DK_CFI_REGISTER:
01534       return parseDirectiveCFIRegister(IDLoc);
01535     case DK_CFI_WINDOW_SAVE:
01536       return parseDirectiveCFIWindowSave();
01537     case DK_MACROS_ON:
01538     case DK_MACROS_OFF:
01539       return parseDirectiveMacrosOnOff(IDVal);
01540     case DK_MACRO:
01541       return parseDirectiveMacro(IDLoc);
01542     case DK_EXITM:
01543       return parseDirectiveExitMacro(IDVal);
01544     case DK_ENDM:
01545     case DK_ENDMACRO:
01546       return parseDirectiveEndMacro(IDVal);
01547     case DK_PURGEM:
01548       return parseDirectivePurgeMacro(IDLoc);
01549     case DK_END:
01550       return parseDirectiveEnd(IDLoc);
01551     case DK_ERR:
01552       return parseDirectiveError(IDLoc, false);
01553     case DK_ERROR:
01554       return parseDirectiveError(IDLoc, true);
01555     case DK_WARNING:
01556       return parseDirectiveWarning(IDLoc);
01557     }
01558 
01559     return Error(IDLoc, "unknown directive");
01560   }
01561 
01562   // __asm _emit or __asm __emit
01563   if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
01564                            IDVal == "_EMIT" || IDVal == "__EMIT"))
01565     return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
01566 
01567   // __asm align
01568   if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
01569     return parseDirectiveMSAlign(IDLoc, Info);
01570 
01571   checkForValidSection();
01572 
01573   // Canonicalize the opcode to lower case.
01574   std::string OpcodeStr = IDVal.lower();
01575   ParseInstructionInfo IInfo(Info.AsmRewrites);
01576   bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
01577                                                      Info.ParsedOperands);
01578   Info.ParseError = HadError;
01579 
01580   // Dump the parsed representation, if requested.
01581   if (getShowParsedOperands()) {
01582     SmallString<256> Str;
01583     raw_svector_ostream OS(Str);
01584     OS << "parsed instruction: [";
01585     for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
01586       if (i != 0)
01587         OS << ", ";
01588       Info.ParsedOperands[i]->print(OS);
01589     }
01590     OS << "]";
01591 
01592     printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
01593   }
01594 
01595   // If we are generating dwarf for the current section then generate a .loc
01596   // directive for the instruction.
01597   if (!HadError && getContext().getGenDwarfForAssembly() &&
01598       getContext().getGenDwarfSectionSyms().count(
01599         getStreamer().getCurrentSection().first)) {
01600 
01601     unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
01602 
01603     // If we previously parsed a cpp hash file line comment then make sure the
01604     // current Dwarf File is for the CppHashFilename if not then emit the
01605     // Dwarf File table for it and adjust the line number for the .loc.
01606     if (CppHashFilename.size() != 0) {
01607       unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
01608           0, StringRef(), CppHashFilename);
01609       getContext().setGenDwarfFileNumber(FileNumber);
01610 
01611       // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
01612       // cache with the different Loc from the call above we save the last
01613       // info we queried here with SrcMgr.FindLineNumber().
01614       unsigned CppHashLocLineNo;
01615       if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
01616         CppHashLocLineNo = LastQueryLine;
01617       else {
01618         CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
01619         LastQueryLine = CppHashLocLineNo;
01620         LastQueryIDLoc = CppHashLoc;
01621         LastQueryBuffer = CppHashBuf;
01622       }
01623       Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
01624     }
01625 
01626     getStreamer().EmitDwarfLocDirective(
01627         getContext().getGenDwarfFileNumber(), Line, 0,
01628         DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
01629         StringRef());
01630   }
01631 
01632   // If parsing succeeded, match the instruction.
01633   if (!HadError) {
01634     uint64_t ErrorInfo;
01635     getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
01636                                               Info.ParsedOperands, Out,
01637                                               ErrorInfo, ParsingInlineAsm);
01638   }
01639 
01640   // Don't skip the rest of the line, the instruction parser is responsible for
01641   // that.
01642   return false;
01643 }
01644 
01645 /// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
01646 /// since they may not be able to be tokenized to get to the end of line token.
01647 void AsmParser::eatToEndOfLine() {
01648   if (!Lexer.is(AsmToken::EndOfStatement))
01649     Lexer.LexUntilEndOfLine();
01650   // Eat EOL.
01651   Lex();
01652 }
01653 
01654 /// parseCppHashLineFilenameComment as this:
01655 ///   ::= # number "filename"
01656 /// or just as a full line comment if it doesn't have a number and a string.
01657 bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
01658   Lex(); // Eat the hash token.
01659 
01660   if (getLexer().isNot(AsmToken::Integer)) {
01661     // Consume the line since in cases it is not a well-formed line directive,
01662     // as if were simply a full line comment.
01663     eatToEndOfLine();
01664     return false;
01665   }
01666 
01667   int64_t LineNumber = getTok().getIntVal();
01668   Lex();
01669 
01670   if (getLexer().isNot(AsmToken::String)) {
01671     eatToEndOfLine();
01672     return false;
01673   }
01674 
01675   StringRef Filename = getTok().getString();
01676   // Get rid of the enclosing quotes.
01677   Filename = Filename.substr(1, Filename.size() - 2);
01678 
01679   // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
01680   CppHashLoc = L;
01681   CppHashFilename = Filename;
01682   CppHashLineNumber = LineNumber;
01683   CppHashBuf = CurBuffer;
01684 
01685   // Ignore any trailing characters, they're just comment.
01686   eatToEndOfLine();
01687   return false;
01688 }
01689 
01690 /// \brief will use the last parsed cpp hash line filename comment
01691 /// for the Filename and LineNo if any in the diagnostic.
01692 void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
01693   const AsmParser *Parser = static_cast<const AsmParser *>(Context);
01694   raw_ostream &OS = errs();
01695 
01696   const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
01697   const SMLoc &DiagLoc = Diag.getLoc();
01698   unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
01699   unsigned CppHashBuf =
01700       Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
01701 
01702   // Like SourceMgr::printMessage() we need to print the include stack if any
01703   // before printing the message.
01704   unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
01705   if (!Parser->SavedDiagHandler && DiagCurBuffer &&
01706       DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
01707     SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
01708     DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
01709   }
01710 
01711   // If we have not parsed a cpp hash line filename comment or the source
01712   // manager changed or buffer changed (like in a nested include) then just
01713   // print the normal diagnostic using its Filename and LineNo.
01714   if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
01715       DiagBuf != CppHashBuf) {
01716     if (Parser->SavedDiagHandler)
01717       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
01718     else
01719       Diag.print(nullptr, OS);
01720     return;
01721   }
01722 
01723   // Use the CppHashFilename and calculate a line number based on the
01724   // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
01725   // the diagnostic.
01726   const std::string &Filename = Parser->CppHashFilename;
01727 
01728   int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
01729   int CppHashLocLineNo =
01730       Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
01731   int LineNo =
01732       Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
01733 
01734   SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
01735                        Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
01736                        Diag.getLineContents(), Diag.getRanges());
01737 
01738   if (Parser->SavedDiagHandler)
01739     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
01740   else
01741     NewDiag.print(nullptr, OS);
01742 }
01743 
01744 // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
01745 // difference being that that function accepts '@' as part of identifiers and
01746 // we can't do that. AsmLexer.cpp should probably be changed to handle
01747 // '@' as a special case when needed.
01748 static bool isIdentifierChar(char c) {
01749   return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
01750          c == '.';
01751 }
01752 
01753 bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
01754                             ArrayRef<MCAsmMacroParameter> Parameters,
01755                             ArrayRef<MCAsmMacroArgument> A, const SMLoc &L) {
01756   unsigned NParameters = Parameters.size();
01757   bool HasVararg = NParameters ? Parameters.back().Vararg : false;
01758   if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
01759     return Error(L, "Wrong number of arguments");
01760 
01761   // A macro without parameters is handled differently on Darwin:
01762   // gas accepts no arguments and does no substitutions
01763   while (!Body.empty()) {
01764     // Scan for the next substitution.
01765     std::size_t End = Body.size(), Pos = 0;
01766     for (; Pos != End; ++Pos) {
01767       // Check for a substitution or escape.
01768       if (IsDarwin && !NParameters) {
01769         // This macro has no parameters, look for $0, $1, etc.
01770         if (Body[Pos] != '$' || Pos + 1 == End)
01771           continue;
01772 
01773         char Next = Body[Pos + 1];
01774         if (Next == '$' || Next == 'n' ||
01775             isdigit(static_cast<unsigned char>(Next)))
01776           break;
01777       } else {
01778         // This macro has parameters, look for \foo, \bar, etc.
01779         if (Body[Pos] == '\\' && Pos + 1 != End)
01780           break;
01781       }
01782     }
01783 
01784     // Add the prefix.
01785     OS << Body.slice(0, Pos);
01786 
01787     // Check if we reached the end.
01788     if (Pos == End)
01789       break;
01790 
01791     if (IsDarwin && !NParameters) {
01792       switch (Body[Pos + 1]) {
01793       // $$ => $
01794       case '$':
01795         OS << '$';
01796         break;
01797 
01798       // $n => number of arguments
01799       case 'n':
01800         OS << A.size();
01801         break;
01802 
01803       // $[0-9] => argument
01804       default: {
01805         // Missing arguments are ignored.
01806         unsigned Index = Body[Pos + 1] - '0';
01807         if (Index >= A.size())
01808           break;
01809 
01810         // Otherwise substitute with the token values, with spaces eliminated.
01811         for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
01812                                                 ie = A[Index].end();
01813              it != ie; ++it)
01814           OS << it->getString();
01815         break;
01816       }
01817       }
01818       Pos += 2;
01819     } else {
01820       unsigned I = Pos + 1;
01821       while (isIdentifierChar(Body[I]) && I + 1 != End)
01822         ++I;
01823 
01824       const char *Begin = Body.data() + Pos + 1;
01825       StringRef Argument(Begin, I - (Pos + 1));
01826       unsigned Index = 0;
01827       for (; Index < NParameters; ++Index)
01828         if (Parameters[Index].Name == Argument)
01829           break;
01830 
01831       if (Index == NParameters) {
01832         if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
01833           Pos += 3;
01834         else {
01835           OS << '\\' << Argument;
01836           Pos = I;
01837         }
01838       } else {
01839         bool VarargParameter = HasVararg && Index == (NParameters - 1);
01840         for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
01841                                                 ie = A[Index].end();
01842              it != ie; ++it)
01843           // We expect no quotes around the string's contents when
01844           // parsing for varargs.
01845           if (it->getKind() != AsmToken::String || VarargParameter)
01846             OS << it->getString();
01847           else
01848             OS << it->getStringContents();
01849 
01850         Pos += 1 + Argument.size();
01851       }
01852     }
01853     // Update the scan point.
01854     Body = Body.substr(Pos);
01855   }
01856 
01857   return false;
01858 }
01859 
01860 MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
01861                                        size_t CondStackDepth)
01862     : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
01863       CondStackDepth(CondStackDepth) {}
01864 
01865 static bool isOperator(AsmToken::TokenKind kind) {
01866   switch (kind) {
01867   default:
01868     return false;
01869   case AsmToken::Plus:
01870   case AsmToken::Minus:
01871   case AsmToken::Tilde:
01872   case AsmToken::Slash:
01873   case AsmToken::Star:
01874   case AsmToken::Dot:
01875   case AsmToken::Equal:
01876   case AsmToken::EqualEqual:
01877   case AsmToken::Pipe:
01878   case AsmToken::PipePipe:
01879   case AsmToken::Caret:
01880   case AsmToken::Amp:
01881   case AsmToken::AmpAmp:
01882   case AsmToken::Exclaim:
01883   case AsmToken::ExclaimEqual:
01884   case AsmToken::Percent:
01885   case AsmToken::Less:
01886   case AsmToken::LessEqual:
01887   case AsmToken::LessLess:
01888   case AsmToken::LessGreater:
01889   case AsmToken::Greater:
01890   case AsmToken::GreaterEqual:
01891   case AsmToken::GreaterGreater:
01892     return true;
01893   }
01894 }
01895 
01896 namespace {
01897 class AsmLexerSkipSpaceRAII {
01898 public:
01899   AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
01900     Lexer.setSkipSpace(SkipSpace);
01901   }
01902 
01903   ~AsmLexerSkipSpaceRAII() {
01904     Lexer.setSkipSpace(true);
01905   }
01906 
01907 private:
01908   AsmLexer &Lexer;
01909 };
01910 }
01911 
01912 bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
01913 
01914   if (Vararg) {
01915     if (Lexer.isNot(AsmToken::EndOfStatement)) {
01916       StringRef Str = parseStringToEndOfStatement();
01917       MA.push_back(AsmToken(AsmToken::String, Str));
01918     }
01919     return false;
01920   }
01921 
01922   unsigned ParenLevel = 0;
01923   unsigned AddTokens = 0;
01924 
01925   // Darwin doesn't use spaces to delmit arguments.
01926   AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
01927 
01928   for (;;) {
01929     if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
01930       return TokError("unexpected token in macro instantiation");
01931 
01932     if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
01933       break;
01934 
01935     if (Lexer.is(AsmToken::Space)) {
01936       Lex(); // Eat spaces
01937 
01938       // Spaces can delimit parameters, but could also be part an expression.
01939       // If the token after a space is an operator, add the token and the next
01940       // one into this argument
01941       if (!IsDarwin) {
01942         if (isOperator(Lexer.getKind())) {
01943           // Check to see whether the token is used as an operator,
01944           // or part of an identifier
01945           const char *NextChar = getTok().getEndLoc().getPointer();
01946           if (*NextChar == ' ')
01947             AddTokens = 2;
01948         }
01949 
01950         if (!AddTokens && ParenLevel == 0) {
01951           break;
01952         }
01953       }
01954     }
01955 
01956     // handleMacroEntry relies on not advancing the lexer here
01957     // to be able to fill in the remaining default parameter values
01958     if (Lexer.is(AsmToken::EndOfStatement))
01959       break;
01960 
01961     // Adjust the current parentheses level.
01962     if (Lexer.is(AsmToken::LParen))
01963       ++ParenLevel;
01964     else if (Lexer.is(AsmToken::RParen) && ParenLevel)
01965       --ParenLevel;
01966 
01967     // Append the token to the current argument list.
01968     MA.push_back(getTok());
01969     if (AddTokens)
01970       AddTokens--;
01971     Lex();
01972   }
01973 
01974   if (ParenLevel != 0)
01975     return TokError("unbalanced parentheses in macro argument");
01976   return false;
01977 }
01978 
01979 // Parse the macro instantiation arguments.
01980 bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
01981                                     MCAsmMacroArguments &A) {
01982   const unsigned NParameters = M ? M->Parameters.size() : 0;
01983   bool NamedParametersFound = false;
01984   SmallVector<SMLoc, 4> FALocs;
01985 
01986   A.resize(NParameters);
01987   FALocs.resize(NParameters);
01988 
01989   // Parse two kinds of macro invocations:
01990   // - macros defined without any parameters accept an arbitrary number of them
01991   // - macros defined with parameters accept at most that many of them
01992   bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
01993   for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
01994        ++Parameter) {
01995     SMLoc IDLoc = Lexer.getLoc();
01996     MCAsmMacroParameter FA;
01997 
01998     if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
01999       if (parseIdentifier(FA.Name)) {
02000         Error(IDLoc, "invalid argument identifier for formal argument");
02001         eatToEndOfStatement();
02002         return true;
02003       }
02004 
02005       if (!Lexer.is(AsmToken::Equal)) {
02006         TokError("expected '=' after formal parameter identifier");
02007         eatToEndOfStatement();
02008         return true;
02009       }
02010       Lex();
02011 
02012       NamedParametersFound = true;
02013     }
02014 
02015     if (NamedParametersFound && FA.Name.empty()) {
02016       Error(IDLoc, "cannot mix positional and keyword arguments");
02017       eatToEndOfStatement();
02018       return true;
02019     }
02020 
02021     bool Vararg = HasVararg && Parameter == (NParameters - 1);
02022     if (parseMacroArgument(FA.Value, Vararg))
02023       return true;
02024 
02025     unsigned PI = Parameter;
02026     if (!FA.Name.empty()) {
02027       unsigned FAI = 0;
02028       for (FAI = 0; FAI < NParameters; ++FAI)
02029         if (M->Parameters[FAI].Name == FA.Name)
02030           break;
02031 
02032       if (FAI >= NParameters) {
02033     assert(M && "expected macro to be defined");
02034         Error(IDLoc,
02035               "parameter named '" + FA.Name + "' does not exist for macro '" +
02036               M->Name + "'");
02037         return true;
02038       }
02039       PI = FAI;
02040     }
02041 
02042     if (!FA.Value.empty()) {
02043       if (A.size() <= PI)
02044         A.resize(PI + 1);
02045       A[PI] = FA.Value;
02046 
02047       if (FALocs.size() <= PI)
02048         FALocs.resize(PI + 1);
02049 
02050       FALocs[PI] = Lexer.getLoc();
02051     }
02052 
02053     // At the end of the statement, fill in remaining arguments that have
02054     // default values. If there aren't any, then the next argument is
02055     // required but missing
02056     if (Lexer.is(AsmToken::EndOfStatement)) {
02057       bool Failure = false;
02058       for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
02059         if (A[FAI].empty()) {
02060           if (M->Parameters[FAI].Required) {
02061             Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
02062                   "missing value for required parameter "
02063                   "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
02064             Failure = true;
02065           }
02066 
02067           if (!M->Parameters[FAI].Value.empty())
02068             A[FAI] = M->Parameters[FAI].Value;
02069         }
02070       }
02071       return Failure;
02072     }
02073 
02074     if (Lexer.is(AsmToken::Comma))
02075       Lex();
02076   }
02077 
02078   return TokError("too many positional arguments");
02079 }
02080 
02081 const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
02082   StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
02083   return (I == MacroMap.end()) ? nullptr : I->getValue();
02084 }
02085 
02086 void AsmParser::defineMacro(StringRef Name, const MCAsmMacro &Macro) {
02087   MacroMap[Name] = new MCAsmMacro(Macro);
02088 }
02089 
02090 void AsmParser::undefineMacro(StringRef Name) {
02091   StringMap<MCAsmMacro *>::iterator I = MacroMap.find(Name);
02092   if (I != MacroMap.end()) {
02093     delete I->getValue();
02094     MacroMap.erase(I);
02095   }
02096 }
02097 
02098 bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
02099   // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
02100   // this, although we should protect against infinite loops.
02101   if (ActiveMacros.size() == 20)
02102     return TokError("macros cannot be nested more than 20 levels deep");
02103 
02104   MCAsmMacroArguments A;
02105   if (parseMacroArguments(M, A))
02106     return true;
02107 
02108   // Macro instantiation is lexical, unfortunately. We construct a new buffer
02109   // to hold the macro body with substitutions.
02110   SmallString<256> Buf;
02111   StringRef Body = M->Body;
02112   raw_svector_ostream OS(Buf);
02113 
02114   if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
02115     return true;
02116 
02117   // We include the .endmacro in the buffer as our cue to exit the macro
02118   // instantiation.
02119   OS << ".endmacro\n";
02120 
02121   std::unique_ptr<MemoryBuffer> Instantiation =
02122       MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
02123 
02124   // Create the macro instantiation object and add to the current macro
02125   // instantiation stack.
02126   MacroInstantiation *MI = new MacroInstantiation(
02127       NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
02128   ActiveMacros.push_back(MI);
02129 
02130   // Jump to the macro instantiation and prime the lexer.
02131   CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
02132   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
02133   Lex();
02134 
02135   return false;
02136 }
02137 
02138 void AsmParser::handleMacroExit() {
02139   // Jump to the EndOfStatement we should return to, and consume it.
02140   jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
02141   Lex();
02142 
02143   // Pop the instantiation entry.
02144   delete ActiveMacros.back();
02145   ActiveMacros.pop_back();
02146 }
02147 
02148 static bool isUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
02149   switch (Value->getKind()) {
02150   case MCExpr::Binary: {
02151     const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
02152     return isUsedIn(Sym, BE->getLHS()) || isUsedIn(Sym, BE->getRHS());
02153   }
02154   case MCExpr::Target:
02155   case MCExpr::Constant:
02156     return false;
02157   case MCExpr::SymbolRef: {
02158     const MCSymbol &S =
02159         static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
02160     if (S.isVariable())
02161       return isUsedIn(Sym, S.getVariableValue());
02162     return &S == Sym;
02163   }
02164   case MCExpr::Unary:
02165     return isUsedIn(Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
02166   }
02167 
02168   llvm_unreachable("Unknown expr kind!");
02169 }
02170 
02171 bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
02172                                 bool NoDeadStrip) {
02173   // FIXME: Use better location, we should use proper tokens.
02174   SMLoc EqualLoc = Lexer.getLoc();
02175 
02176   const MCExpr *Value;
02177   if (parseExpression(Value))
02178     return true;
02179 
02180   // Note: we don't count b as used in "a = b". This is to allow
02181   // a = b
02182   // b = c
02183 
02184   if (Lexer.isNot(AsmToken::EndOfStatement))
02185     return TokError("unexpected token in assignment");
02186 
02187   // Eat the end of statement marker.
02188   Lex();
02189 
02190   // Validate that the LHS is allowed to be a variable (either it has not been
02191   // used as a symbol, or it is an absolute symbol).
02192   MCSymbol *Sym = getContext().LookupSymbol(Name);
02193   if (Sym) {
02194     // Diagnose assignment to a label.
02195     //
02196     // FIXME: Diagnostics. Note the location of the definition as a label.
02197     // FIXME: Diagnose assignment to protected identifier (e.g., register name).
02198     if (isUsedIn(Sym, Value))
02199       return Error(EqualLoc, "Recursive use of '" + Name + "'");
02200     else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
02201       ; // Allow redefinitions of undefined symbols only used in directives.
02202     else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
02203       ; // Allow redefinitions of variables that haven't yet been used.
02204     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
02205       return Error(EqualLoc, "redefinition of '" + Name + "'");
02206     else if (!Sym->isVariable())
02207       return Error(EqualLoc, "invalid assignment to '" + Name + "'");
02208     else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
02209       return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
02210                                  Name + "'");
02211 
02212     // Don't count these checks as uses.
02213     Sym->setUsed(false);
02214   } else if (Name == ".") {
02215     if (Out.EmitValueToOffset(Value, 0)) {
02216       Error(EqualLoc, "expected absolute expression");
02217       eatToEndOfStatement();
02218     }
02219     return false;
02220   } else
02221     Sym = getContext().GetOrCreateSymbol(Name);
02222 
02223   // Do the assignment.
02224   Out.EmitAssignment(Sym, Value);
02225   if (NoDeadStrip)
02226     Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
02227 
02228   return false;
02229 }
02230 
02231 /// parseIdentifier:
02232 ///   ::= identifier
02233 ///   ::= string
02234 bool AsmParser::parseIdentifier(StringRef &Res) {
02235   // The assembler has relaxed rules for accepting identifiers, in particular we
02236   // allow things like '.globl $foo' and '.def @feat.00', which would normally be
02237   // separate tokens. At this level, we have already lexed so we cannot (currently)
02238   // handle this as a context dependent token, instead we detect adjacent tokens
02239   // and return the combined identifier.
02240   if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
02241     SMLoc PrefixLoc = getLexer().getLoc();
02242 
02243     // Consume the prefix character, and check for a following identifier.
02244     Lex();
02245     if (Lexer.isNot(AsmToken::Identifier))
02246       return true;
02247 
02248     // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
02249     if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
02250       return true;
02251 
02252     // Construct the joined identifier and consume the token.
02253     Res =
02254         StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
02255     Lex();
02256     return false;
02257   }
02258 
02259   if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
02260     return true;
02261 
02262   Res = getTok().getIdentifier();
02263 
02264   Lex(); // Consume the identifier token.
02265 
02266   return false;
02267 }
02268 
02269 /// parseDirectiveSet:
02270 ///   ::= .equ identifier ',' expression
02271 ///   ::= .equiv identifier ',' expression
02272 ///   ::= .set identifier ',' expression
02273 bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
02274   StringRef Name;
02275 
02276   if (parseIdentifier(Name))
02277     return TokError("expected identifier after '" + Twine(IDVal) + "'");
02278 
02279   if (getLexer().isNot(AsmToken::Comma))
02280     return TokError("unexpected token in '" + Twine(IDVal) + "'");
02281   Lex();
02282 
02283   return parseAssignment(Name, allow_redef, true);
02284 }
02285 
02286 bool AsmParser::parseEscapedString(std::string &Data) {
02287   assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
02288 
02289   Data = "";
02290   StringRef Str = getTok().getStringContents();
02291   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
02292     if (Str[i] != '\\') {
02293       Data += Str[i];
02294       continue;
02295     }
02296 
02297     // Recognize escaped characters. Note that this escape semantics currently
02298     // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
02299     ++i;
02300     if (i == e)
02301       return TokError("unexpected backslash at end of string");
02302 
02303     // Recognize octal sequences.
02304     if ((unsigned)(Str[i] - '0') <= 7) {
02305       // Consume up to three octal characters.
02306       unsigned Value = Str[i] - '0';
02307 
02308       if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
02309         ++i;
02310         Value = Value * 8 + (Str[i] - '0');
02311 
02312         if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
02313           ++i;
02314           Value = Value * 8 + (Str[i] - '0');
02315         }
02316       }
02317 
02318       if (Value > 255)
02319         return TokError("invalid octal escape sequence (out of range)");
02320 
02321       Data += (unsigned char)Value;
02322       continue;
02323     }
02324 
02325     // Otherwise recognize individual escapes.
02326     switch (Str[i]) {
02327     default:
02328       // Just reject invalid escape sequences for now.
02329       return TokError("invalid escape sequence (unrecognized character)");
02330 
02331     case 'b': Data += '\b'; break;
02332     case 'f': Data += '\f'; break;
02333     case 'n': Data += '\n'; break;
02334     case 'r': Data += '\r'; break;
02335     case 't': Data += '\t'; break;
02336     case '"': Data += '"'; break;
02337     case '\\': Data += '\\'; break;
02338     }
02339   }
02340 
02341   return false;
02342 }
02343 
02344 /// parseDirectiveAscii:
02345 ///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
02346 bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
02347   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02348     checkForValidSection();
02349 
02350     for (;;) {
02351       if (getLexer().isNot(AsmToken::String))
02352         return TokError("expected string in '" + Twine(IDVal) + "' directive");
02353 
02354       std::string Data;
02355       if (parseEscapedString(Data))
02356         return true;
02357 
02358       getStreamer().EmitBytes(Data);
02359       if (ZeroTerminated)
02360         getStreamer().EmitBytes(StringRef("\0", 1));
02361 
02362       Lex();
02363 
02364       if (getLexer().is(AsmToken::EndOfStatement))
02365         break;
02366 
02367       if (getLexer().isNot(AsmToken::Comma))
02368         return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
02369       Lex();
02370     }
02371   }
02372 
02373   Lex();
02374   return false;
02375 }
02376 
02377 /// parseDirectiveValue
02378 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
02379 bool AsmParser::parseDirectiveValue(unsigned Size) {
02380   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02381     checkForValidSection();
02382 
02383     for (;;) {
02384       const MCExpr *Value;
02385       SMLoc ExprLoc = getLexer().getLoc();
02386       if (parseExpression(Value))
02387         return true;
02388 
02389       // Special case constant expressions to match code generator.
02390       if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
02391         assert(Size <= 8 && "Invalid size");
02392         uint64_t IntValue = MCE->getValue();
02393         if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
02394           return Error(ExprLoc, "literal value out of range for directive");
02395         getStreamer().EmitIntValue(IntValue, Size);
02396       } else
02397         getStreamer().EmitValue(Value, Size, ExprLoc);
02398 
02399       if (getLexer().is(AsmToken::EndOfStatement))
02400         break;
02401 
02402       // FIXME: Improve diagnostic.
02403       if (getLexer().isNot(AsmToken::Comma))
02404         return TokError("unexpected token in directive");
02405       Lex();
02406     }
02407   }
02408 
02409   Lex();
02410   return false;
02411 }
02412 
02413 /// ParseDirectiveOctaValue
02414 ///  ::= .octa [ hexconstant (, hexconstant)* ]
02415 bool AsmParser::parseDirectiveOctaValue() {
02416   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02417     checkForValidSection();
02418 
02419     for (;;) {
02420       if (Lexer.getKind() == AsmToken::Error)
02421         return true;
02422       if (Lexer.getKind() != AsmToken::Integer &&
02423           Lexer.getKind() != AsmToken::BigNum)
02424         return TokError("unknown token in expression");
02425 
02426       SMLoc ExprLoc = getLexer().getLoc();
02427       APInt IntValue = getTok().getAPIntVal();
02428       Lex();
02429 
02430       uint64_t hi, lo;
02431       if (IntValue.isIntN(64)) {
02432         hi = 0;
02433         lo = IntValue.getZExtValue();
02434       } else if (IntValue.isIntN(128)) {
02435         // It might actually have more than 128 bits, but the top ones are zero.
02436         hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
02437         lo = IntValue.getLoBits(64).getZExtValue();
02438       } else
02439         return Error(ExprLoc, "literal value out of range for directive");
02440 
02441       if (MAI.isLittleEndian()) {
02442         getStreamer().EmitIntValue(lo, 8);
02443         getStreamer().EmitIntValue(hi, 8);
02444       } else {
02445         getStreamer().EmitIntValue(hi, 8);
02446         getStreamer().EmitIntValue(lo, 8);
02447       }
02448 
02449       if (getLexer().is(AsmToken::EndOfStatement))
02450         break;
02451 
02452       // FIXME: Improve diagnostic.
02453       if (getLexer().isNot(AsmToken::Comma))
02454         return TokError("unexpected token in directive");
02455       Lex();
02456     }
02457   }
02458 
02459   Lex();
02460   return false;
02461 }
02462 
02463 /// parseDirectiveRealValue
02464 ///  ::= (.single | .double) [ expression (, expression)* ]
02465 bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
02466   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02467     checkForValidSection();
02468 
02469     for (;;) {
02470       // We don't truly support arithmetic on floating point expressions, so we
02471       // have to manually parse unary prefixes.
02472       bool IsNeg = false;
02473       if (getLexer().is(AsmToken::Minus)) {
02474         Lex();
02475         IsNeg = true;
02476       } else if (getLexer().is(AsmToken::Plus))
02477         Lex();
02478 
02479       if (getLexer().isNot(AsmToken::Integer) &&
02480           getLexer().isNot(AsmToken::Real) &&
02481           getLexer().isNot(AsmToken::Identifier))
02482         return TokError("unexpected token in directive");
02483 
02484       // Convert to an APFloat.
02485       APFloat Value(Semantics);
02486       StringRef IDVal = getTok().getString();
02487       if (getLexer().is(AsmToken::Identifier)) {
02488         if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
02489           Value = APFloat::getInf(Semantics);
02490         else if (!IDVal.compare_lower("nan"))
02491           Value = APFloat::getNaN(Semantics, false, ~0);
02492         else
02493           return TokError("invalid floating point literal");
02494       } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
02495                  APFloat::opInvalidOp)
02496         return TokError("invalid floating point literal");
02497       if (IsNeg)
02498         Value.changeSign();
02499 
02500       // Consume the numeric token.
02501       Lex();
02502 
02503       // Emit the value as an integer.
02504       APInt AsInt = Value.bitcastToAPInt();
02505       getStreamer().EmitIntValue(AsInt.getLimitedValue(),
02506                                  AsInt.getBitWidth() / 8);
02507 
02508       if (getLexer().is(AsmToken::EndOfStatement))
02509         break;
02510 
02511       if (getLexer().isNot(AsmToken::Comma))
02512         return TokError("unexpected token in directive");
02513       Lex();
02514     }
02515   }
02516 
02517   Lex();
02518   return false;
02519 }
02520 
02521 /// parseDirectiveZero
02522 ///  ::= .zero expression
02523 bool AsmParser::parseDirectiveZero() {
02524   checkForValidSection();
02525 
02526   int64_t NumBytes;
02527   if (parseAbsoluteExpression(NumBytes))
02528     return true;
02529 
02530   int64_t Val = 0;
02531   if (getLexer().is(AsmToken::Comma)) {
02532     Lex();
02533     if (parseAbsoluteExpression(Val))
02534       return true;
02535   }
02536 
02537   if (getLexer().isNot(AsmToken::EndOfStatement))
02538     return TokError("unexpected token in '.zero' directive");
02539 
02540   Lex();
02541 
02542   getStreamer().EmitFill(NumBytes, Val);
02543 
02544   return false;
02545 }
02546 
02547 /// parseDirectiveFill
02548 ///  ::= .fill expression [ , expression [ , expression ] ]
02549 bool AsmParser::parseDirectiveFill() {
02550   checkForValidSection();
02551 
02552   SMLoc RepeatLoc = getLexer().getLoc();
02553   int64_t NumValues;
02554   if (parseAbsoluteExpression(NumValues))
02555     return true;
02556 
02557   if (NumValues < 0) {
02558     Warning(RepeatLoc,
02559             "'.fill' directive with negative repeat count has no effect");
02560     NumValues = 0;
02561   }
02562 
02563   int64_t FillSize = 1;
02564   int64_t FillExpr = 0;
02565 
02566   SMLoc SizeLoc, ExprLoc;
02567   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02568     if (getLexer().isNot(AsmToken::Comma))
02569       return TokError("unexpected token in '.fill' directive");
02570     Lex();
02571 
02572     SizeLoc = getLexer().getLoc();
02573     if (parseAbsoluteExpression(FillSize))
02574       return true;
02575 
02576     if (getLexer().isNot(AsmToken::EndOfStatement)) {
02577       if (getLexer().isNot(AsmToken::Comma))
02578         return TokError("unexpected token in '.fill' directive");
02579       Lex();
02580 
02581       ExprLoc = getLexer().getLoc();
02582       if (parseAbsoluteExpression(FillExpr))
02583         return true;
02584 
02585       if (getLexer().isNot(AsmToken::EndOfStatement))
02586         return TokError("unexpected token in '.fill' directive");
02587 
02588       Lex();
02589     }
02590   }
02591 
02592   if (FillSize < 0) {
02593     Warning(SizeLoc, "'.fill' directive with negative size has no effect");
02594     NumValues = 0;
02595   }
02596   if (FillSize > 8) {
02597     Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
02598     FillSize = 8;
02599   }
02600 
02601   if (!isUInt<32>(FillExpr) && FillSize > 4)
02602     Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
02603 
02604   if (NumValues > 0) {
02605     int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
02606     FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
02607     for (uint64_t i = 0, e = NumValues; i != e; ++i) {
02608       getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
02609       if (NonZeroFillSize < FillSize)
02610         getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
02611     }
02612   }
02613 
02614   return false;
02615 }
02616 
02617 /// parseDirectiveOrg
02618 ///  ::= .org expression [ , expression ]
02619 bool AsmParser::parseDirectiveOrg() {
02620   checkForValidSection();
02621 
02622   const MCExpr *Offset;
02623   SMLoc Loc = getTok().getLoc();
02624   if (parseExpression(Offset))
02625     return true;
02626 
02627   // Parse optional fill expression.
02628   int64_t FillExpr = 0;
02629   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02630     if (getLexer().isNot(AsmToken::Comma))
02631       return TokError("unexpected token in '.org' directive");
02632     Lex();
02633 
02634     if (parseAbsoluteExpression(FillExpr))
02635       return true;
02636 
02637     if (getLexer().isNot(AsmToken::EndOfStatement))
02638       return TokError("unexpected token in '.org' directive");
02639   }
02640 
02641   Lex();
02642 
02643   // Only limited forms of relocatable expressions are accepted here, it
02644   // has to be relative to the current section. The streamer will return
02645   // 'true' if the expression wasn't evaluatable.
02646   if (getStreamer().EmitValueToOffset(Offset, FillExpr))
02647     return Error(Loc, "expected assembly-time absolute expression");
02648 
02649   return false;
02650 }
02651 
02652 /// parseDirectiveAlign
02653 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
02654 bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
02655   checkForValidSection();
02656 
02657   SMLoc AlignmentLoc = getLexer().getLoc();
02658   int64_t Alignment;
02659   if (parseAbsoluteExpression(Alignment))
02660     return true;
02661 
02662   SMLoc MaxBytesLoc;
02663   bool HasFillExpr = false;
02664   int64_t FillExpr = 0;
02665   int64_t MaxBytesToFill = 0;
02666   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02667     if (getLexer().isNot(AsmToken::Comma))
02668       return TokError("unexpected token in directive");
02669     Lex();
02670 
02671     // The fill expression can be omitted while specifying a maximum number of
02672     // alignment bytes, e.g:
02673     //  .align 3,,4
02674     if (getLexer().isNot(AsmToken::Comma)) {
02675       HasFillExpr = true;
02676       if (parseAbsoluteExpression(FillExpr))
02677         return true;
02678     }
02679 
02680     if (getLexer().isNot(AsmToken::EndOfStatement)) {
02681       if (getLexer().isNot(AsmToken::Comma))
02682         return TokError("unexpected token in directive");
02683       Lex();
02684 
02685       MaxBytesLoc = getLexer().getLoc();
02686       if (parseAbsoluteExpression(MaxBytesToFill))
02687         return true;
02688 
02689       if (getLexer().isNot(AsmToken::EndOfStatement))
02690         return TokError("unexpected token in directive");
02691     }
02692   }
02693 
02694   Lex();
02695 
02696   if (!HasFillExpr)
02697     FillExpr = 0;
02698 
02699   // Compute alignment in bytes.
02700   if (IsPow2) {
02701     // FIXME: Diagnose overflow.
02702     if (Alignment >= 32) {
02703       Error(AlignmentLoc, "invalid alignment value");
02704       Alignment = 31;
02705     }
02706 
02707     Alignment = 1ULL << Alignment;
02708   } else {
02709     // Reject alignments that aren't a power of two, for gas compatibility.
02710     if (!isPowerOf2_64(Alignment))
02711       Error(AlignmentLoc, "alignment must be a power of 2");
02712   }
02713 
02714   // Diagnose non-sensical max bytes to align.
02715   if (MaxBytesLoc.isValid()) {
02716     if (MaxBytesToFill < 1) {
02717       Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
02718                          "many bytes, ignoring maximum bytes expression");
02719       MaxBytesToFill = 0;
02720     }
02721 
02722     if (MaxBytesToFill >= Alignment) {
02723       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
02724                            "has no effect");
02725       MaxBytesToFill = 0;
02726     }
02727   }
02728 
02729   // Check whether we should use optimal code alignment for this .align
02730   // directive.
02731   const MCSection *Section = getStreamer().getCurrentSection().first;
02732   assert(Section && "must have section to emit alignment");
02733   bool UseCodeAlign = Section->UseCodeAlign();
02734   if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
02735       ValueSize == 1 && UseCodeAlign) {
02736     getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
02737   } else {
02738     // FIXME: Target specific behavior about how the "extra" bytes are filled.
02739     getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
02740                                        MaxBytesToFill);
02741   }
02742 
02743   return false;
02744 }
02745 
02746 /// parseDirectiveFile
02747 /// ::= .file [number] filename
02748 /// ::= .file number directory filename
02749 bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
02750   // FIXME: I'm not sure what this is.
02751   int64_t FileNumber = -1;
02752   SMLoc FileNumberLoc = getLexer().getLoc();
02753   if (getLexer().is(AsmToken::Integer)) {
02754     FileNumber = getTok().getIntVal();
02755     Lex();
02756 
02757     if (FileNumber < 1)
02758       return TokError("file number less than one");
02759   }
02760 
02761   if (getLexer().isNot(AsmToken::String))
02762     return TokError("unexpected token in '.file' directive");
02763 
02764   // Usually the directory and filename together, otherwise just the directory.
02765   // Allow the strings to have escaped octal character sequence.
02766   std::string Path = getTok().getString();
02767   if (parseEscapedString(Path))
02768     return true;
02769   Lex();
02770 
02771   StringRef Directory;
02772   StringRef Filename;
02773   std::string FilenameData;
02774   if (getLexer().is(AsmToken::String)) {
02775     if (FileNumber == -1)
02776       return TokError("explicit path specified, but no file number");
02777     if (parseEscapedString(FilenameData))
02778       return true;
02779     Filename = FilenameData;
02780     Directory = Path;
02781     Lex();
02782   } else {
02783     Filename = Path;
02784   }
02785 
02786   if (getLexer().isNot(AsmToken::EndOfStatement))
02787     return TokError("unexpected token in '.file' directive");
02788 
02789   if (FileNumber == -1)
02790     getStreamer().EmitFileDirective(Filename);
02791   else {
02792     if (getContext().getGenDwarfForAssembly() == true)
02793       Error(DirectiveLoc,
02794             "input can't have .file dwarf directives when -g is "
02795             "used to generate dwarf debug info for assembly code");
02796 
02797     if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
02798         0)
02799       Error(FileNumberLoc, "file number already allocated");
02800   }
02801 
02802   return false;
02803 }
02804 
02805 /// parseDirectiveLine
02806 /// ::= .line [number]
02807 bool AsmParser::parseDirectiveLine() {
02808   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02809     if (getLexer().isNot(AsmToken::Integer))
02810       return TokError("unexpected token in '.line' directive");
02811 
02812     int64_t LineNumber = getTok().getIntVal();
02813     (void)LineNumber;
02814     Lex();
02815 
02816     // FIXME: Do something with the .line.
02817   }
02818 
02819   if (getLexer().isNot(AsmToken::EndOfStatement))
02820     return TokError("unexpected token in '.line' directive");
02821 
02822   return false;
02823 }
02824 
02825 /// parseDirectiveLoc
02826 /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
02827 ///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
02828 /// The first number is a file number, must have been previously assigned with
02829 /// a .file directive, the second number is the line number and optionally the
02830 /// third number is a column position (zero if not specified).  The remaining
02831 /// optional items are .loc sub-directives.
02832 bool AsmParser::parseDirectiveLoc() {
02833   if (getLexer().isNot(AsmToken::Integer))
02834     return TokError("unexpected token in '.loc' directive");
02835   int64_t FileNumber = getTok().getIntVal();
02836   if (FileNumber < 1)
02837     return TokError("file number less than one in '.loc' directive");
02838   if (!getContext().isValidDwarfFileNumber(FileNumber))
02839     return TokError("unassigned file number in '.loc' directive");
02840   Lex();
02841 
02842   int64_t LineNumber = 0;
02843   if (getLexer().is(AsmToken::Integer)) {
02844     LineNumber = getTok().getIntVal();
02845     if (LineNumber < 0)
02846       return TokError("line number less than zero in '.loc' directive");
02847     Lex();
02848   }
02849 
02850   int64_t ColumnPos = 0;
02851   if (getLexer().is(AsmToken::Integer)) {
02852     ColumnPos = getTok().getIntVal();
02853     if (ColumnPos < 0)
02854       return TokError("column position less than zero in '.loc' directive");
02855     Lex();
02856   }
02857 
02858   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
02859   unsigned Isa = 0;
02860   int64_t Discriminator = 0;
02861   if (getLexer().isNot(AsmToken::EndOfStatement)) {
02862     for (;;) {
02863       if (getLexer().is(AsmToken::EndOfStatement))
02864         break;
02865 
02866       StringRef Name;
02867       SMLoc Loc = getTok().getLoc();
02868       if (parseIdentifier(Name))
02869         return TokError("unexpected token in '.loc' directive");
02870 
02871       if (Name == "basic_block")
02872         Flags |= DWARF2_FLAG_BASIC_BLOCK;
02873       else if (Name == "prologue_end")
02874         Flags |= DWARF2_FLAG_PROLOGUE_END;
02875       else if (Name == "epilogue_begin")
02876         Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
02877       else if (Name == "is_stmt") {
02878         Loc = getTok().getLoc();
02879         const MCExpr *Value;
02880         if (parseExpression(Value))
02881           return true;
02882         // The expression must be the constant 0 or 1.
02883         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
02884           int Value = MCE->getValue();
02885           if (Value == 0)
02886             Flags &= ~DWARF2_FLAG_IS_STMT;
02887           else if (Value == 1)
02888             Flags |= DWARF2_FLAG_IS_STMT;
02889           else
02890             return Error(Loc, "is_stmt value not 0 or 1");
02891         } else {
02892           return Error(Loc, "is_stmt value not the constant value of 0 or 1");
02893         }
02894       } else if (Name == "isa") {
02895         Loc = getTok().getLoc();
02896         const MCExpr *Value;
02897         if (parseExpression(Value))
02898           return true;
02899         // The expression must be a constant greater or equal to 0.
02900         if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
02901           int Value = MCE->getValue();
02902           if (Value < 0)
02903             return Error(Loc, "isa number less than zero");
02904           Isa = Value;
02905         } else {
02906           return Error(Loc, "isa number not a constant value");
02907         }
02908       } else if (Name == "discriminator") {
02909         if (parseAbsoluteExpression(Discriminator))
02910           return true;
02911       } else {
02912         return Error(Loc, "unknown sub-directive in '.loc' directive");
02913       }
02914 
02915       if (getLexer().is(AsmToken::EndOfStatement))
02916         break;
02917     }
02918   }
02919 
02920   getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
02921                                       Isa, Discriminator, StringRef());
02922 
02923   return false;
02924 }
02925 
02926 /// parseDirectiveStabs
02927 /// ::= .stabs string, number, number, number
02928 bool AsmParser::parseDirectiveStabs() {
02929   return TokError("unsupported directive '.stabs'");
02930 }
02931 
02932 /// parseDirectiveCFISections
02933 /// ::= .cfi_sections section [, section]
02934 bool AsmParser::parseDirectiveCFISections() {
02935   StringRef Name;
02936   bool EH = false;
02937   bool Debug = false;
02938 
02939   if (parseIdentifier(Name))
02940     return TokError("Expected an identifier");
02941 
02942   if (Name == ".eh_frame")
02943     EH = true;
02944   else if (Name == ".debug_frame")
02945     Debug = true;
02946 
02947   if (getLexer().is(AsmToken::Comma)) {
02948     Lex();
02949 
02950     if (parseIdentifier(Name))
02951       return TokError("Expected an identifier");
02952 
02953     if (Name == ".eh_frame")
02954       EH = true;
02955     else if (Name == ".debug_frame")
02956       Debug = true;
02957   }
02958 
02959   getStreamer().EmitCFISections(EH, Debug);
02960   return false;
02961 }
02962 
02963 /// parseDirectiveCFIStartProc
02964 /// ::= .cfi_startproc [simple]
02965 bool AsmParser::parseDirectiveCFIStartProc() {
02966   StringRef Simple;
02967   if (getLexer().isNot(AsmToken::EndOfStatement))
02968     if (parseIdentifier(Simple) || Simple != "simple")
02969       return TokError("unexpected token in .cfi_startproc directive");
02970 
02971   getStreamer().EmitCFIStartProc(!Simple.empty());
02972   return false;
02973 }
02974 
02975 /// parseDirectiveCFIEndProc
02976 /// ::= .cfi_endproc
02977 bool AsmParser::parseDirectiveCFIEndProc() {
02978   getStreamer().EmitCFIEndProc();
02979   return false;
02980 }
02981 
02982 /// \brief parse register name or number.
02983 bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
02984                                               SMLoc DirectiveLoc) {
02985   unsigned RegNo;
02986 
02987   if (getLexer().isNot(AsmToken::Integer)) {
02988     if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
02989       return true;
02990     Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
02991   } else
02992     return parseAbsoluteExpression(Register);
02993 
02994   return false;
02995 }
02996 
02997 /// parseDirectiveCFIDefCfa
02998 /// ::= .cfi_def_cfa register,  offset
02999 bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
03000   int64_t Register = 0;
03001   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03002     return true;
03003 
03004   if (getLexer().isNot(AsmToken::Comma))
03005     return TokError("unexpected token in directive");
03006   Lex();
03007 
03008   int64_t Offset = 0;
03009   if (parseAbsoluteExpression(Offset))
03010     return true;
03011 
03012   getStreamer().EmitCFIDefCfa(Register, Offset);
03013   return false;
03014 }
03015 
03016 /// parseDirectiveCFIDefCfaOffset
03017 /// ::= .cfi_def_cfa_offset offset
03018 bool AsmParser::parseDirectiveCFIDefCfaOffset() {
03019   int64_t Offset = 0;
03020   if (parseAbsoluteExpression(Offset))
03021     return true;
03022 
03023   getStreamer().EmitCFIDefCfaOffset(Offset);
03024   return false;
03025 }
03026 
03027 /// parseDirectiveCFIRegister
03028 /// ::= .cfi_register register, register
03029 bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
03030   int64_t Register1 = 0;
03031   if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
03032     return true;
03033 
03034   if (getLexer().isNot(AsmToken::Comma))
03035     return TokError("unexpected token in directive");
03036   Lex();
03037 
03038   int64_t Register2 = 0;
03039   if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
03040     return true;
03041 
03042   getStreamer().EmitCFIRegister(Register1, Register2);
03043   return false;
03044 }
03045 
03046 /// parseDirectiveCFIWindowSave
03047 /// ::= .cfi_window_save
03048 bool AsmParser::parseDirectiveCFIWindowSave() {
03049   getStreamer().EmitCFIWindowSave();
03050   return false;
03051 }
03052 
03053 /// parseDirectiveCFIAdjustCfaOffset
03054 /// ::= .cfi_adjust_cfa_offset adjustment
03055 bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
03056   int64_t Adjustment = 0;
03057   if (parseAbsoluteExpression(Adjustment))
03058     return true;
03059 
03060   getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
03061   return false;
03062 }
03063 
03064 /// parseDirectiveCFIDefCfaRegister
03065 /// ::= .cfi_def_cfa_register register
03066 bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
03067   int64_t Register = 0;
03068   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03069     return true;
03070 
03071   getStreamer().EmitCFIDefCfaRegister(Register);
03072   return false;
03073 }
03074 
03075 /// parseDirectiveCFIOffset
03076 /// ::= .cfi_offset register, offset
03077 bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
03078   int64_t Register = 0;
03079   int64_t Offset = 0;
03080 
03081   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03082     return true;
03083 
03084   if (getLexer().isNot(AsmToken::Comma))
03085     return TokError("unexpected token in directive");
03086   Lex();
03087 
03088   if (parseAbsoluteExpression(Offset))
03089     return true;
03090 
03091   getStreamer().EmitCFIOffset(Register, Offset);
03092   return false;
03093 }
03094 
03095 /// parseDirectiveCFIRelOffset
03096 /// ::= .cfi_rel_offset register, offset
03097 bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
03098   int64_t Register = 0;
03099 
03100   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03101     return true;
03102 
03103   if (getLexer().isNot(AsmToken::Comma))
03104     return TokError("unexpected token in directive");
03105   Lex();
03106 
03107   int64_t Offset = 0;
03108   if (parseAbsoluteExpression(Offset))
03109     return true;
03110 
03111   getStreamer().EmitCFIRelOffset(Register, Offset);
03112   return false;
03113 }
03114 
03115 static bool isValidEncoding(int64_t Encoding) {
03116   if (Encoding & ~0xff)
03117     return false;
03118 
03119   if (Encoding == dwarf::DW_EH_PE_omit)
03120     return true;
03121 
03122   const unsigned Format = Encoding & 0xf;
03123   if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
03124       Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
03125       Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
03126       Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
03127     return false;
03128 
03129   const unsigned Application = Encoding & 0x70;
03130   if (Application != dwarf::DW_EH_PE_absptr &&
03131       Application != dwarf::DW_EH_PE_pcrel)
03132     return false;
03133 
03134   return true;
03135 }
03136 
03137 /// parseDirectiveCFIPersonalityOrLsda
03138 /// IsPersonality true for cfi_personality, false for cfi_lsda
03139 /// ::= .cfi_personality encoding, [symbol_name]
03140 /// ::= .cfi_lsda encoding, [symbol_name]
03141 bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
03142   int64_t Encoding = 0;
03143   if (parseAbsoluteExpression(Encoding))
03144     return true;
03145   if (Encoding == dwarf::DW_EH_PE_omit)
03146     return false;
03147 
03148   if (!isValidEncoding(Encoding))
03149     return TokError("unsupported encoding.");
03150 
03151   if (getLexer().isNot(AsmToken::Comma))
03152     return TokError("unexpected token in directive");
03153   Lex();
03154 
03155   StringRef Name;
03156   if (parseIdentifier(Name))
03157     return TokError("expected identifier in directive");
03158 
03159   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
03160 
03161   if (IsPersonality)
03162     getStreamer().EmitCFIPersonality(Sym, Encoding);
03163   else
03164     getStreamer().EmitCFILsda(Sym, Encoding);
03165   return false;
03166 }
03167 
03168 /// parseDirectiveCFIRememberState
03169 /// ::= .cfi_remember_state
03170 bool AsmParser::parseDirectiveCFIRememberState() {
03171   getStreamer().EmitCFIRememberState();
03172   return false;
03173 }
03174 
03175 /// parseDirectiveCFIRestoreState
03176 /// ::= .cfi_remember_state
03177 bool AsmParser::parseDirectiveCFIRestoreState() {
03178   getStreamer().EmitCFIRestoreState();
03179   return false;
03180 }
03181 
03182 /// parseDirectiveCFISameValue
03183 /// ::= .cfi_same_value register
03184 bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
03185   int64_t Register = 0;
03186 
03187   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03188     return true;
03189 
03190   getStreamer().EmitCFISameValue(Register);
03191   return false;
03192 }
03193 
03194 /// parseDirectiveCFIRestore
03195 /// ::= .cfi_restore register
03196 bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
03197   int64_t Register = 0;
03198   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03199     return true;
03200 
03201   getStreamer().EmitCFIRestore(Register);
03202   return false;
03203 }
03204 
03205 /// parseDirectiveCFIEscape
03206 /// ::= .cfi_escape expression[,...]
03207 bool AsmParser::parseDirectiveCFIEscape() {
03208   std::string Values;
03209   int64_t CurrValue;
03210   if (parseAbsoluteExpression(CurrValue))
03211     return true;
03212 
03213   Values.push_back((uint8_t)CurrValue);
03214 
03215   while (getLexer().is(AsmToken::Comma)) {
03216     Lex();
03217 
03218     if (parseAbsoluteExpression(CurrValue))
03219       return true;
03220 
03221     Values.push_back((uint8_t)CurrValue);
03222   }
03223 
03224   getStreamer().EmitCFIEscape(Values);
03225   return false;
03226 }
03227 
03228 /// parseDirectiveCFISignalFrame
03229 /// ::= .cfi_signal_frame
03230 bool AsmParser::parseDirectiveCFISignalFrame() {
03231   if (getLexer().isNot(AsmToken::EndOfStatement))
03232     return Error(getLexer().getLoc(),
03233                  "unexpected token in '.cfi_signal_frame'");
03234 
03235   getStreamer().EmitCFISignalFrame();
03236   return false;
03237 }
03238 
03239 /// parseDirectiveCFIUndefined
03240 /// ::= .cfi_undefined register
03241 bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
03242   int64_t Register = 0;
03243 
03244   if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
03245     return true;
03246 
03247   getStreamer().EmitCFIUndefined(Register);
03248   return false;
03249 }
03250 
03251 /// parseDirectiveMacrosOnOff
03252 /// ::= .macros_on
03253 /// ::= .macros_off
03254 bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
03255   if (getLexer().isNot(AsmToken::EndOfStatement))
03256     return Error(getLexer().getLoc(),
03257                  "unexpected token in '" + Directive + "' directive");
03258 
03259   setMacrosEnabled(Directive == ".macros_on");
03260   return false;
03261 }
03262 
03263 /// parseDirectiveMacro
03264 /// ::= .macro name[,] [parameters]
03265 bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
03266   StringRef Name;
03267   if (parseIdentifier(Name))
03268     return TokError("expected identifier in '.macro' directive");
03269 
03270   if (getLexer().is(AsmToken::Comma))
03271     Lex();
03272 
03273   MCAsmMacroParameters Parameters;
03274   while (getLexer().isNot(AsmToken::EndOfStatement)) {
03275 
03276     if (Parameters.size() && Parameters.back().Vararg)
03277       return Error(Lexer.getLoc(),
03278                    "Vararg parameter '" + Parameters.back().Name +
03279                    "' should be last one in the list of parameters.");
03280 
03281     MCAsmMacroParameter Parameter;
03282     if (parseIdentifier(Parameter.Name))
03283       return TokError("expected identifier in '.macro' directive");
03284 
03285     if (Lexer.is(AsmToken::Colon)) {
03286       Lex();  // consume ':'
03287 
03288       SMLoc QualLoc;
03289       StringRef Qualifier;
03290 
03291       QualLoc = Lexer.getLoc();
03292       if (parseIdentifier(Qualifier))
03293         return Error(QualLoc, "missing parameter qualifier for "
03294                      "'" + Parameter.Name + "' in macro '" + Name + "'");
03295 
03296       if (Qualifier == "req")
03297         Parameter.Required = true;
03298       else if (Qualifier == "vararg")
03299         Parameter.Vararg = true;
03300       else
03301         return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
03302                      "for '" + Parameter.Name + "' in macro '" + Name + "'");
03303     }
03304 
03305     if (getLexer().is(AsmToken::Equal)) {
03306       Lex();
03307 
03308       SMLoc ParamLoc;
03309 
03310       ParamLoc = Lexer.getLoc();
03311       if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
03312         return true;
03313 
03314       if (Parameter.Required)
03315         Warning(ParamLoc, "pointless default value for required parameter "
03316                 "'" + Parameter.Name + "' in macro '" + Name + "'");
03317     }
03318 
03319     Parameters.push_back(Parameter);
03320 
03321     if (getLexer().is(AsmToken::Comma))
03322       Lex();
03323   }
03324 
03325   // Eat the end of statement.
03326   Lex();
03327 
03328   AsmToken EndToken, StartToken = getTok();
03329   unsigned MacroDepth = 0;
03330 
03331   // Lex the macro definition.
03332   for (;;) {
03333     // Check whether we have reached the end of the file.
03334     if (getLexer().is(AsmToken::Eof))
03335       return Error(DirectiveLoc, "no matching '.endmacro' in definition");
03336 
03337     // Otherwise, check whether we have reach the .endmacro.
03338     if (getLexer().is(AsmToken::Identifier)) {
03339       if (getTok().getIdentifier() == ".endm" ||
03340           getTok().getIdentifier() == ".endmacro") {
03341         if (MacroDepth == 0) { // Outermost macro.
03342           EndToken = getTok();
03343           Lex();
03344           if (getLexer().isNot(AsmToken::EndOfStatement))
03345             return TokError("unexpected token in '" + EndToken.getIdentifier() +
03346                             "' directive");
03347           break;
03348         } else {
03349           // Otherwise we just found the end of an inner macro.
03350           --MacroDepth;
03351         }
03352       } else if (getTok().getIdentifier() == ".macro") {
03353         // We allow nested macros. Those aren't instantiated until the outermost
03354         // macro is expanded so just ignore them for now.
03355         ++MacroDepth;
03356       }
03357     }
03358 
03359     // Otherwise, scan til the end of the statement.
03360     eatToEndOfStatement();
03361   }
03362 
03363   if (lookupMacro(Name)) {
03364     return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
03365   }
03366 
03367   const char *BodyStart = StartToken.getLoc().getPointer();
03368   const char *BodyEnd = EndToken.getLoc().getPointer();
03369   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
03370   checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
03371   defineMacro(Name, MCAsmMacro(Name, Body, Parameters));
03372   return false;
03373 }
03374 
03375 /// checkForBadMacro
03376 ///
03377 /// With the support added for named parameters there may be code out there that
03378 /// is transitioning from positional parameters.  In versions of gas that did
03379 /// not support named parameters they would be ignored on the macro definition.
03380 /// But to support both styles of parameters this is not possible so if a macro
03381 /// definition has named parameters but does not use them and has what appears
03382 /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
03383 /// warning that the positional parameter found in body which have no effect.
03384 /// Hoping the developer will either remove the named parameters from the macro
03385 /// definition so the positional parameters get used if that was what was
03386 /// intended or change the macro to use the named parameters.  It is possible
03387 /// this warning will trigger when the none of the named parameters are used
03388 /// and the strings like $1 are infact to simply to be passed trough unchanged.
03389 void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
03390                                  StringRef Body,
03391                                  ArrayRef<MCAsmMacroParameter> Parameters) {
03392   // If this macro is not defined with named parameters the warning we are
03393   // checking for here doesn't apply.
03394   unsigned NParameters = Parameters.size();
03395   if (NParameters == 0)
03396     return;
03397 
03398   bool NamedParametersFound = false;
03399   bool PositionalParametersFound = false;
03400 
03401   // Look at the body of the macro for use of both the named parameters and what
03402   // are likely to be positional parameters.  This is what expandMacro() is
03403   // doing when it finds the parameters in the body.
03404   while (!Body.empty()) {
03405     // Scan for the next possible parameter.
03406     std::size_t End = Body.size(), Pos = 0;
03407     for (; Pos != End; ++Pos) {
03408       // Check for a substitution or escape.
03409       // This macro is defined with parameters, look for \foo, \bar, etc.
03410       if (Body[Pos] == '\\' && Pos + 1 != End)
03411         break;
03412 
03413       // This macro should have parameters, but look for $0, $1, ..., $n too.
03414       if (Body[Pos] != '$' || Pos + 1 == End)
03415         continue;
03416       char Next = Body[Pos + 1];
03417       if (Next == '$' || Next == 'n' ||
03418           isdigit(static_cast<unsigned char>(Next)))
03419         break;
03420     }
03421 
03422     // Check if we reached the end.
03423     if (Pos == End)
03424       break;
03425 
03426     if (Body[Pos] == '$') {
03427       switch (Body[Pos + 1]) {
03428       // $$ => $
03429       case '$':
03430         break;
03431 
03432       // $n => number of arguments
03433       case 'n':
03434         PositionalParametersFound = true;
03435         break;
03436 
03437       // $[0-9] => argument
03438       default: {
03439         PositionalParametersFound = true;
03440         break;
03441       }
03442       }
03443       Pos += 2;
03444     } else {
03445       unsigned I = Pos + 1;
03446       while (isIdentifierChar(Body[I]) && I + 1 != End)
03447         ++I;
03448 
03449       const char *Begin = Body.data() + Pos + 1;
03450       StringRef Argument(Begin, I - (Pos + 1));
03451       unsigned Index = 0;
03452       for (; Index < NParameters; ++Index)
03453         if (Parameters[Index].Name == Argument)
03454           break;
03455 
03456       if (Index == NParameters) {
03457         if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
03458           Pos += 3;
03459         else {
03460           Pos = I;
03461         }
03462       } else {
03463         NamedParametersFound = true;
03464         Pos += 1 + Argument.size();
03465       }
03466     }
03467     // Update the scan point.
03468     Body = Body.substr(Pos);
03469   }
03470 
03471   if (!NamedParametersFound && PositionalParametersFound)
03472     Warning(DirectiveLoc, "macro defined with named parameters which are not "
03473                           "used in macro body, possible positional parameter "
03474                           "found in body which will have no effect");
03475 }
03476 
03477 /// parseDirectiveExitMacro
03478 /// ::= .exitm
03479 bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
03480   if (getLexer().isNot(AsmToken::EndOfStatement))
03481     return TokError("unexpected token in '" + Directive + "' directive");
03482 
03483   if (!isInsideMacroInstantiation())
03484     return TokError("unexpected '" + Directive + "' in file, "
03485                                                  "no current macro definition");
03486 
03487   // Exit all conditionals that are active in the current macro.
03488   while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
03489     TheCondState = TheCondStack.back();
03490     TheCondStack.pop_back();
03491   }
03492 
03493   handleMacroExit();
03494   return false;
03495 }
03496 
03497 /// parseDirectiveEndMacro
03498 /// ::= .endm
03499 /// ::= .endmacro
03500 bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
03501   if (getLexer().isNot(AsmToken::EndOfStatement))
03502     return TokError("unexpected token in '" + Directive + "' directive");
03503 
03504   // If we are inside a macro instantiation, terminate the current
03505   // instantiation.
03506   if (isInsideMacroInstantiation()) {
03507     handleMacroExit();
03508     return false;
03509   }
03510 
03511   // Otherwise, this .endmacro is a stray entry in the file; well formed
03512   // .endmacro directives are handled during the macro definition parsing.
03513   return TokError("unexpected '" + Directive + "' in file, "
03514                                                "no current macro definition");
03515 }
03516 
03517 /// parseDirectivePurgeMacro
03518 /// ::= .purgem
03519 bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
03520   StringRef Name;
03521   if (parseIdentifier(Name))
03522     return TokError("expected identifier in '.purgem' directive");
03523 
03524   if (getLexer().isNot(AsmToken::EndOfStatement))
03525     return TokError("unexpected token in '.purgem' directive");
03526 
03527   if (!lookupMacro(Name))
03528     return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
03529 
03530   undefineMacro(Name);
03531   return false;
03532 }
03533 
03534 /// parseDirectiveBundleAlignMode
03535 /// ::= {.bundle_align_mode} expression
03536 bool AsmParser::parseDirectiveBundleAlignMode() {
03537   checkForValidSection();
03538 
03539   // Expect a single argument: an expression that evaluates to a constant
03540   // in the inclusive range 0-30.
03541   SMLoc ExprLoc = getLexer().getLoc();
03542   int64_t AlignSizePow2;
03543   if (parseAbsoluteExpression(AlignSizePow2))
03544     return true;
03545   else if (getLexer().isNot(AsmToken::EndOfStatement))
03546     return TokError("unexpected token after expression in"
03547                     " '.bundle_align_mode' directive");
03548   else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
03549     return Error(ExprLoc,
03550                  "invalid bundle alignment size (expected between 0 and 30)");
03551 
03552   Lex();
03553 
03554   // Because of AlignSizePow2's verified range we can safely truncate it to
03555   // unsigned.
03556   getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
03557   return false;
03558 }
03559 
03560 /// parseDirectiveBundleLock
03561 /// ::= {.bundle_lock} [align_to_end]
03562 bool AsmParser::parseDirectiveBundleLock() {
03563   checkForValidSection();
03564   bool AlignToEnd = false;
03565 
03566   if (getLexer().isNot(AsmToken::EndOfStatement)) {
03567     StringRef Option;
03568     SMLoc Loc = getTok().getLoc();
03569     const char *kInvalidOptionError =
03570         "invalid option for '.bundle_lock' directive";
03571 
03572     if (parseIdentifier(Option))
03573       return Error(Loc, kInvalidOptionError);
03574 
03575     if (Option != "align_to_end")
03576       return Error(Loc, kInvalidOptionError);
03577     else if (getLexer().isNot(AsmToken::EndOfStatement))
03578       return Error(Loc,
03579                    "unexpected token after '.bundle_lock' directive option");
03580     AlignToEnd = true;
03581   }
03582 
03583   Lex();
03584 
03585   getStreamer().EmitBundleLock(AlignToEnd);
03586   return false;
03587 }
03588 
03589 /// parseDirectiveBundleLock
03590 /// ::= {.bundle_lock}
03591 bool AsmParser::parseDirectiveBundleUnlock() {
03592   checkForValidSection();
03593 
03594   if (getLexer().isNot(AsmToken::EndOfStatement))
03595     return TokError("unexpected token in '.bundle_unlock' directive");
03596   Lex();
03597 
03598   getStreamer().EmitBundleUnlock();
03599   return false;
03600 }
03601 
03602 /// parseDirectiveSpace
03603 /// ::= (.skip | .space) expression [ , expression ]
03604 bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
03605   checkForValidSection();
03606 
03607   int64_t NumBytes;
03608   if (parseAbsoluteExpression(NumBytes))
03609     return true;
03610 
03611   int64_t FillExpr = 0;
03612   if (getLexer().isNot(AsmToken::EndOfStatement)) {
03613     if (getLexer().isNot(AsmToken::Comma))
03614       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
03615     Lex();
03616 
03617     if (parseAbsoluteExpression(FillExpr))
03618       return true;
03619 
03620     if (getLexer().isNot(AsmToken::EndOfStatement))
03621       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
03622   }
03623 
03624   Lex();
03625 
03626   if (NumBytes <= 0)
03627     return TokError("invalid number of bytes in '" + Twine(IDVal) +
03628                     "' directive");
03629 
03630   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
03631   getStreamer().EmitFill(NumBytes, FillExpr);
03632 
03633   return false;
03634 }
03635 
03636 /// parseDirectiveLEB128
03637 /// ::= (.sleb128 | .uleb128) expression
03638 bool AsmParser::parseDirectiveLEB128(bool Signed) {
03639   checkForValidSection();
03640   const MCExpr *Value;
03641 
03642   if (parseExpression(Value))
03643     return true;
03644 
03645   if (getLexer().isNot(AsmToken::EndOfStatement))
03646     return TokError("unexpected token in directive");
03647 
03648   if (Signed)
03649     getStreamer().EmitSLEB128Value(Value);
03650   else
03651     getStreamer().EmitULEB128Value(Value);
03652 
03653   return false;
03654 }
03655 
03656 /// parseDirectiveSymbolAttribute
03657 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
03658 bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
03659   if (getLexer().isNot(AsmToken::EndOfStatement)) {
03660     for (;;) {
03661       StringRef Name;
03662       SMLoc Loc = getTok().getLoc();
03663 
03664       if (parseIdentifier(Name))
03665         return Error(Loc, "expected identifier in directive");
03666 
03667       MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
03668 
03669       // Assembler local symbols don't make any sense here. Complain loudly.
03670       if (Sym->isTemporary())
03671         return Error(Loc, "non-local symbol required in directive");
03672 
03673       if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
03674         return Error(Loc, "unable to emit symbol attribute");
03675 
03676       if (getLexer().is(AsmToken::EndOfStatement))
03677         break;
03678 
03679       if (getLexer().isNot(AsmToken::Comma))
03680         return TokError("unexpected token in directive");
03681       Lex();
03682     }
03683   }
03684 
03685   Lex();
03686   return false;
03687 }
03688 
03689 /// parseDirectiveComm
03690 ///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
03691 bool AsmParser::parseDirectiveComm(bool IsLocal) {
03692   checkForValidSection();
03693 
03694   SMLoc IDLoc = getLexer().getLoc();
03695   StringRef Name;
03696   if (parseIdentifier(Name))
03697     return TokError("expected identifier in directive");
03698 
03699   // Handle the identifier as the key symbol.
03700   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
03701 
03702   if (getLexer().isNot(AsmToken::Comma))
03703     return TokError("unexpected token in directive");
03704   Lex();
03705 
03706   int64_t Size;
03707   SMLoc SizeLoc = getLexer().getLoc();
03708   if (parseAbsoluteExpression(Size))
03709     return true;
03710 
03711   int64_t Pow2Alignment = 0;
03712   SMLoc Pow2AlignmentLoc;
03713   if (getLexer().is(AsmToken::Comma)) {
03714     Lex();
03715     Pow2AlignmentLoc = getLexer().getLoc();
03716     if (parseAbsoluteExpression(Pow2Alignment))
03717       return true;
03718 
03719     LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
03720     if (IsLocal && LCOMM == LCOMM::NoAlignment)
03721       return Error(Pow2AlignmentLoc, "alignment not supported on this target");
03722 
03723     // If this target takes alignments in bytes (not log) validate and convert.
03724     if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
03725         (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
03726       if (!isPowerOf2_64(Pow2Alignment))
03727         return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
03728       Pow2Alignment = Log2_64(Pow2Alignment);
03729     }
03730   }
03731 
03732   if (getLexer().isNot(AsmToken::EndOfStatement))
03733     return TokError("unexpected token in '.comm' or '.lcomm' directive");
03734 
03735   Lex();
03736 
03737   // NOTE: a size of zero for a .comm should create a undefined symbol
03738   // but a size of .lcomm creates a bss symbol of size zero.
03739   if (Size < 0)
03740     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
03741                           "be less than zero");
03742 
03743   // NOTE: The alignment in the directive is a power of 2 value, the assembler
03744   // may internally end up wanting an alignment in bytes.
03745   // FIXME: Diagnose overflow.
03746   if (Pow2Alignment < 0)
03747     return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
03748                                    "alignment, can't be less than zero");
03749 
03750   if (!Sym->isUndefined())
03751     return Error(IDLoc, "invalid symbol redefinition");
03752 
03753   // Create the Symbol as a common or local common with Size and Pow2Alignment
03754   if (IsLocal) {
03755     getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
03756     return false;
03757   }
03758 
03759   getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
03760   return false;
03761 }
03762 
03763 /// parseDirectiveAbort
03764 ///  ::= .abort [... message ...]
03765 bool AsmParser::parseDirectiveAbort() {
03766   // FIXME: Use loc from directive.
03767   SMLoc Loc = getLexer().getLoc();
03768 
03769   StringRef Str = parseStringToEndOfStatement();
03770   if (getLexer().isNot(AsmToken::EndOfStatement))
03771     return TokError("unexpected token in '.abort' directive");
03772 
03773   Lex();
03774 
03775   if (Str.empty())
03776     Error(Loc, ".abort detected. Assembly stopping.");
03777   else
03778     Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
03779   // FIXME: Actually abort assembly here.
03780 
03781   return false;
03782 }
03783 
03784 /// parseDirectiveInclude
03785 ///  ::= .include "filename"
03786 bool AsmParser::parseDirectiveInclude() {
03787   if (getLexer().isNot(AsmToken::String))
03788     return TokError("expected string in '.include' directive");
03789 
03790   // Allow the strings to have escaped octal character sequence.
03791   std::string Filename;
03792   if (parseEscapedString(Filename))
03793     return true;
03794   SMLoc IncludeLoc = getLexer().getLoc();
03795   Lex();
03796 
03797   if (getLexer().isNot(AsmToken::EndOfStatement))
03798     return TokError("unexpected token in '.include' directive");
03799 
03800   // Attempt to switch the lexer to the included file before consuming the end
03801   // of statement to avoid losing it when we switch.
03802   if (enterIncludeFile(Filename)) {
03803     Error(IncludeLoc, "Could not find include file '" + Filename + "'");
03804     return true;
03805   }
03806 
03807   return false;
03808 }
03809 
03810 /// parseDirectiveIncbin
03811 ///  ::= .incbin "filename"
03812 bool AsmParser::parseDirectiveIncbin() {
03813   if (getLexer().isNot(AsmToken::String))
03814     return TokError("expected string in '.incbin' directive");
03815 
03816   // Allow the strings to have escaped octal character sequence.
03817   std::string Filename;
03818   if (parseEscapedString(Filename))
03819     return true;
03820   SMLoc IncbinLoc = getLexer().getLoc();
03821   Lex();
03822 
03823   if (getLexer().isNot(AsmToken::EndOfStatement))
03824     return TokError("unexpected token in '.incbin' directive");
03825 
03826   // Attempt to process the included file.
03827   if (processIncbinFile(Filename)) {
03828     Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
03829     return true;
03830   }
03831 
03832   return false;
03833 }
03834 
03835 /// parseDirectiveIf
03836 /// ::= .if{,eq,ge,gt,le,lt,ne} expression
03837 bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
03838   TheCondStack.push_back(TheCondState);
03839   TheCondState.TheCond = AsmCond::IfCond;
03840   if (TheCondState.Ignore) {
03841     eatToEndOfStatement();
03842   } else {
03843     int64_t ExprValue;
03844     if (parseAbsoluteExpression(ExprValue))
03845       return true;
03846 
03847     if (getLexer().isNot(AsmToken::EndOfStatement))
03848       return TokError("unexpected token in '.if' directive");
03849 
03850     Lex();
03851 
03852     switch (DirKind) {
03853     default:
03854       llvm_unreachable("unsupported directive");
03855     case DK_IF:
03856     case DK_IFNE:
03857       break;
03858     case DK_IFEQ:
03859       ExprValue = ExprValue == 0;
03860       break;
03861     case DK_IFGE:
03862       ExprValue = ExprValue >= 0;
03863       break;
03864     case DK_IFGT:
03865       ExprValue = ExprValue > 0;
03866       break;
03867     case DK_IFLE:
03868       ExprValue = ExprValue <= 0;
03869       break;
03870     case DK_IFLT:
03871       ExprValue = ExprValue < 0;
03872       break;
03873     }
03874 
03875     TheCondState.CondMet = ExprValue;
03876     TheCondState.Ignore = !TheCondState.CondMet;
03877   }
03878 
03879   return false;
03880 }
03881 
03882 /// parseDirectiveIfb
03883 /// ::= .ifb string
03884 bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
03885   TheCondStack.push_back(TheCondState);
03886   TheCondState.TheCond = AsmCond::IfCond;
03887 
03888   if (TheCondState.Ignore) {
03889     eatToEndOfStatement();
03890   } else {
03891     StringRef Str = parseStringToEndOfStatement();
03892 
03893     if (getLexer().isNot(AsmToken::EndOfStatement))
03894       return TokError("unexpected token in '.ifb' directive");
03895 
03896     Lex();
03897 
03898     TheCondState.CondMet = ExpectBlank == Str.empty();
03899     TheCondState.Ignore = !TheCondState.CondMet;
03900   }
03901 
03902   return false;
03903 }
03904 
03905 /// parseDirectiveIfc
03906 /// ::= .ifc string1, string2
03907 /// ::= .ifnc string1, string2
03908 bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
03909   TheCondStack.push_back(TheCondState);
03910   TheCondState.TheCond = AsmCond::IfCond;
03911 
03912   if (TheCondState.Ignore) {
03913     eatToEndOfStatement();
03914   } else {
03915     StringRef Str1 = parseStringToComma();
03916 
03917     if (getLexer().isNot(AsmToken::Comma))
03918       return TokError("unexpected token in '.ifc' directive");
03919 
03920     Lex();
03921 
03922     StringRef Str2 = parseStringToEndOfStatement();
03923 
03924     if (getLexer().isNot(AsmToken::EndOfStatement))
03925       return TokError("unexpected token in '.ifc' directive");
03926 
03927     Lex();
03928 
03929     TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
03930     TheCondState.Ignore = !TheCondState.CondMet;
03931   }
03932 
03933   return false;
03934 }
03935 
03936 /// parseDirectiveIfeqs
03937 ///   ::= .ifeqs string1, string2
03938 bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc) {
03939   if (Lexer.isNot(AsmToken::String)) {
03940     TokError("expected string parameter for '.ifeqs' directive");
03941     eatToEndOfStatement();
03942     return true;
03943   }
03944 
03945   StringRef String1 = getTok().getStringContents();
03946   Lex();
03947 
03948   if (Lexer.isNot(AsmToken::Comma)) {
03949     TokError("expected comma after first string for '.ifeqs' directive");
03950     eatToEndOfStatement();
03951     return true;
03952   }
03953 
03954   Lex();
03955 
03956   if (Lexer.isNot(AsmToken::String)) {
03957     TokError("expected string parameter for '.ifeqs' directive");
03958     eatToEndOfStatement();
03959     return true;
03960   }
03961 
03962   StringRef String2 = getTok().getStringContents();
03963   Lex();
03964 
03965   TheCondStack.push_back(TheCondState);
03966   TheCondState.TheCond = AsmCond::IfCond;
03967   TheCondState.CondMet = String1 == String2;
03968   TheCondState.Ignore = !TheCondState.CondMet;
03969 
03970   return false;
03971 }
03972 
03973 /// parseDirectiveIfdef
03974 /// ::= .ifdef symbol
03975 bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
03976   StringRef Name;
03977   TheCondStack.push_back(TheCondState);
03978   TheCondState.TheCond = AsmCond::IfCond;
03979 
03980   if (TheCondState.Ignore) {
03981     eatToEndOfStatement();
03982   } else {
03983     if (parseIdentifier(Name))
03984       return TokError("expected identifier after '.ifdef'");
03985 
03986     Lex();
03987 
03988     MCSymbol *Sym = getContext().LookupSymbol(Name);
03989 
03990     if (expect_defined)
03991       TheCondState.CondMet = (Sym && !Sym->isUndefined());
03992     else
03993       TheCondState.CondMet = (!Sym || Sym->isUndefined());
03994     TheCondState.Ignore = !TheCondState.CondMet;
03995   }
03996 
03997   return false;
03998 }
03999 
04000 /// parseDirectiveElseIf
04001 /// ::= .elseif expression
04002 bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
04003   if (TheCondState.TheCond != AsmCond::IfCond &&
04004       TheCondState.TheCond != AsmCond::ElseIfCond)
04005     Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
04006                         " an .elseif");
04007   TheCondState.TheCond = AsmCond::ElseIfCond;
04008 
04009   bool LastIgnoreState = false;
04010   if (!TheCondStack.empty())
04011     LastIgnoreState = TheCondStack.back().Ignore;
04012   if (LastIgnoreState || TheCondState.CondMet) {
04013     TheCondState.Ignore = true;
04014     eatToEndOfStatement();
04015   } else {
04016     int64_t ExprValue;
04017     if (parseAbsoluteExpression(ExprValue))
04018       return true;
04019 
04020     if (getLexer().isNot(AsmToken::EndOfStatement))
04021       return TokError("unexpected token in '.elseif' directive");
04022 
04023     Lex();
04024     TheCondState.CondMet = ExprValue;
04025     TheCondState.Ignore = !TheCondState.CondMet;
04026   }
04027 
04028   return false;
04029 }
04030 
04031 /// parseDirectiveElse
04032 /// ::= .else
04033 bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
04034   if (getLexer().isNot(AsmToken::EndOfStatement))
04035     return TokError("unexpected token in '.else' directive");
04036 
04037   Lex();
04038 
04039   if (TheCondState.TheCond != AsmCond::IfCond &&
04040       TheCondState.TheCond != AsmCond::ElseIfCond)
04041     Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
04042                         ".elseif");
04043   TheCondState.TheCond = AsmCond::ElseCond;
04044   bool LastIgnoreState = false;
04045   if (!TheCondStack.empty())
04046     LastIgnoreState = TheCondStack.back().Ignore;
04047   if (LastIgnoreState || TheCondState.CondMet)
04048     TheCondState.Ignore = true;
04049   else
04050     TheCondState.Ignore = false;
04051 
04052   return false;
04053 }
04054 
04055 /// parseDirectiveEnd
04056 /// ::= .end
04057 bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
04058   if (getLexer().isNot(AsmToken::EndOfStatement))
04059     return TokError("unexpected token in '.end' directive");
04060 
04061   Lex();
04062 
04063   while (Lexer.isNot(AsmToken::Eof))
04064     Lex();
04065 
04066   return false;
04067 }
04068 
04069 /// parseDirectiveError
04070 ///   ::= .err
04071 ///   ::= .error [string]
04072 bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
04073   if (!TheCondStack.empty()) {
04074     if (TheCondStack.back().Ignore) {
04075       eatToEndOfStatement();
04076       return false;
04077     }
04078   }
04079 
04080   if (!WithMessage)
04081     return Error(L, ".err encountered");
04082 
04083   StringRef Message = ".error directive invoked in source file";
04084   if (Lexer.isNot(AsmToken::EndOfStatement)) {
04085     if (Lexer.isNot(AsmToken::String)) {
04086       TokError(".error argument must be a string");
04087       eatToEndOfStatement();
04088       return true;
04089     }
04090 
04091     Message = getTok().getStringContents();
04092     Lex();
04093   }
04094 
04095   Error(L, Message);
04096   return true;
04097 }
04098 
04099 /// parseDirectiveWarning
04100 ///   ::= .warning [string]
04101 bool AsmParser::parseDirectiveWarning(SMLoc L) {
04102   if (!TheCondStack.empty()) {
04103     if (TheCondStack.back().Ignore) {
04104       eatToEndOfStatement();
04105       return false;
04106     }
04107   }
04108 
04109   StringRef Message = ".warning directive invoked in source file";
04110   if (Lexer.isNot(AsmToken::EndOfStatement)) {
04111     if (Lexer.isNot(AsmToken::String)) {
04112       TokError(".warning argument must be a string");
04113       eatToEndOfStatement();
04114       return true;
04115     }
04116 
04117     Message = getTok().getStringContents();
04118     Lex();
04119   }
04120 
04121   Warning(L, Message);
04122   return false;
04123 }
04124 
04125 /// parseDirectiveEndIf
04126 /// ::= .endif
04127 bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
04128   if (getLexer().isNot(AsmToken::EndOfStatement))
04129     return TokError("unexpected token in '.endif' directive");
04130 
04131   Lex();
04132 
04133   if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
04134     Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
04135                         ".else");
04136   if (!TheCondStack.empty()) {
04137     TheCondState = TheCondStack.back();
04138     TheCondStack.pop_back();
04139   }
04140 
04141   return false;
04142 }
04143 
04144 void AsmParser::initializeDirectiveKindMap() {
04145   DirectiveKindMap[".set"] = DK_SET;
04146   DirectiveKindMap[".equ"] = DK_EQU;
04147   DirectiveKindMap[".equiv"] = DK_EQUIV;
04148   DirectiveKindMap[".ascii"] = DK_ASCII;
04149   DirectiveKindMap[".asciz"] = DK_ASCIZ;
04150   DirectiveKindMap[".string"] = DK_STRING;
04151   DirectiveKindMap[".byte"] = DK_BYTE;
04152   DirectiveKindMap[".short"] = DK_SHORT;
04153   DirectiveKindMap[".value"] = DK_VALUE;
04154   DirectiveKindMap[".2byte"] = DK_2BYTE;
04155   DirectiveKindMap[".long"] = DK_LONG;
04156   DirectiveKindMap[".int"] = DK_INT;
04157   DirectiveKindMap[".4byte"] = DK_4BYTE;
04158   DirectiveKindMap[".quad"] = DK_QUAD;
04159   DirectiveKindMap[".8byte"] = DK_8BYTE;
04160   DirectiveKindMap[".octa"] = DK_OCTA;
04161   DirectiveKindMap[".single"] = DK_SINGLE;
04162   DirectiveKindMap[".float"] = DK_FLOAT;
04163   DirectiveKindMap[".double"] = DK_DOUBLE;
04164   DirectiveKindMap[".align"] = DK_ALIGN;
04165   DirectiveKindMap[".align32"] = DK_ALIGN32;
04166   DirectiveKindMap[".balign"] = DK_BALIGN;
04167   DirectiveKindMap[".balignw"] = DK_BALIGNW;
04168   DirectiveKindMap[".balignl"] = DK_BALIGNL;
04169   DirectiveKindMap[".p2align"] = DK_P2ALIGN;
04170   DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
04171   DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
04172   DirectiveKindMap[".org"] = DK_ORG;
04173   DirectiveKindMap[".fill"] = DK_FILL;
04174   DirectiveKindMap[".zero"] = DK_ZERO;
04175   DirectiveKindMap[".extern"] = DK_EXTERN;
04176   DirectiveKindMap[".globl"] = DK_GLOBL;
04177   DirectiveKindMap[".global"] = DK_GLOBAL;
04178   DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
04179   DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
04180   DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
04181   DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
04182   DirectiveKindMap[".reference"] = DK_REFERENCE;
04183   DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
04184   DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
04185   DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
04186   DirectiveKindMap[".comm"] = DK_COMM;
04187   DirectiveKindMap[".common"] = DK_COMMON;
04188   DirectiveKindMap[".lcomm"] = DK_LCOMM;
04189   DirectiveKindMap[".abort"] = DK_ABORT;
04190   DirectiveKindMap[".include"] = DK_INCLUDE;
04191   DirectiveKindMap[".incbin"] = DK_INCBIN;
04192   DirectiveKindMap[".code16"] = DK_CODE16;
04193   DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
04194   DirectiveKindMap[".rept"] = DK_REPT;
04195   DirectiveKindMap[".rep"] = DK_REPT;
04196   DirectiveKindMap[".irp"] = DK_IRP;
04197   DirectiveKindMap[".irpc"] = DK_IRPC;
04198   DirectiveKindMap[".endr"] = DK_ENDR;
04199   DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
04200   DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
04201   DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
04202   DirectiveKindMap[".if"] = DK_IF;
04203   DirectiveKindMap[".ifeq"] = DK_IFEQ;
04204   DirectiveKindMap[".ifge"] = DK_IFGE;
04205   DirectiveKindMap[".ifgt"] = DK_IFGT;
04206   DirectiveKindMap[".ifle"] = DK_IFLE;
04207   DirectiveKindMap[".iflt"] = DK_IFLT;
04208   DirectiveKindMap[".ifne"] = DK_IFNE;
04209   DirectiveKindMap[".ifb"] = DK_IFB;
04210   DirectiveKindMap[".ifnb"] = DK_IFNB;
04211   DirectiveKindMap[".ifc"] = DK_IFC;
04212   DirectiveKindMap[".ifeqs"] = DK_IFEQS;
04213   DirectiveKindMap[".ifnc"] = DK_IFNC;
04214   DirectiveKindMap[".ifdef"] = DK_IFDEF;
04215   DirectiveKindMap[".ifndef"] = DK_IFNDEF;
04216   DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
04217   DirectiveKindMap[".elseif"] = DK_ELSEIF;
04218   DirectiveKindMap[".else"] = DK_ELSE;
04219   DirectiveKindMap[".end"] = DK_END;
04220   DirectiveKindMap[".endif"] = DK_ENDIF;
04221   DirectiveKindMap[".skip"] = DK_SKIP;
04222   DirectiveKindMap[".space"] = DK_SPACE;
04223   DirectiveKindMap[".file"] = DK_FILE;
04224   DirectiveKindMap[".line"] = DK_LINE;
04225   DirectiveKindMap[".loc"] = DK_LOC;
04226   DirectiveKindMap[".stabs"] = DK_STABS;
04227   DirectiveKindMap[".sleb128"] = DK_SLEB128;
04228   DirectiveKindMap[".uleb128"] = DK_ULEB128;
04229   DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
04230   DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
04231   DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
04232   DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
04233   DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
04234   DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
04235   DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
04236   DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
04237   DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
04238   DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
04239   DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
04240   DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
04241   DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
04242   DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
04243   DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
04244   DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
04245   DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
04246   DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
04247   DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
04248   DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
04249   DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
04250   DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
04251   DirectiveKindMap[".macro"] = DK_MACRO;
04252   DirectiveKindMap[".exitm"] = DK_EXITM;
04253   DirectiveKindMap[".endm"] = DK_ENDM;
04254   DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
04255   DirectiveKindMap[".purgem"] = DK_PURGEM;
04256   DirectiveKindMap[".err"] = DK_ERR;
04257   DirectiveKindMap[".error"] = DK_ERROR;
04258   DirectiveKindMap[".warning"] = DK_WARNING;
04259 }
04260 
04261 MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
04262   AsmToken EndToken, StartToken = getTok();
04263 
04264   unsigned NestLevel = 0;
04265   for (;;) {
04266     // Check whether we have reached the end of the file.
04267     if (getLexer().is(AsmToken::Eof)) {
04268       Error(DirectiveLoc, "no matching '.endr' in definition");
04269       return nullptr;
04270     }
04271 
04272     if (Lexer.is(AsmToken::Identifier) &&
04273         (getTok().getIdentifier() == ".rept")) {
04274       ++NestLevel;
04275     }
04276 
04277     // Otherwise, check whether we have reached the .endr.
04278     if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
04279       if (NestLevel == 0) {
04280         EndToken = getTok();
04281         Lex();
04282         if (Lexer.isNot(AsmToken::EndOfStatement)) {
04283           TokError("unexpected token in '.endr' directive");
04284           return nullptr;
04285         }
04286         break;
04287       }
04288       --NestLevel;
04289     }
04290 
04291     // Otherwise, scan till the end of the statement.
04292     eatToEndOfStatement();
04293   }
04294 
04295   const char *BodyStart = StartToken.getLoc().getPointer();
04296   const char *BodyEnd = EndToken.getLoc().getPointer();
04297   StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
04298 
04299   // We Are Anonymous.
04300   MacroLikeBodies.push_back(MCAsmMacro(StringRef(), Body, None));
04301   return &MacroLikeBodies.back();
04302 }
04303 
04304 void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
04305                                          raw_svector_ostream &OS) {
04306   OS << ".endr\n";
04307 
04308   std::unique_ptr<MemoryBuffer> Instantiation =
04309       MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
04310 
04311   // Create the macro instantiation object and add to the current macro
04312   // instantiation stack.
04313   MacroInstantiation *MI = new MacroInstantiation(
04314       DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
04315   ActiveMacros.push_back(MI);
04316 
04317   // Jump to the macro instantiation and prime the lexer.
04318   CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
04319   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
04320   Lex();
04321 }
04322 
04323 /// parseDirectiveRept
04324 ///   ::= .rep | .rept count
04325 bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
04326   const MCExpr *CountExpr;
04327   SMLoc CountLoc = getTok().getLoc();
04328   if (parseExpression(CountExpr))
04329     return true;
04330 
04331   int64_t Count;
04332   if (!CountExpr->EvaluateAsAbsolute(Count)) {
04333     eatToEndOfStatement();
04334     return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
04335   }
04336 
04337   if (Count < 0)
04338     return Error(CountLoc, "Count is negative");
04339 
04340   if (Lexer.isNot(AsmToken::EndOfStatement))
04341     return TokError("unexpected token in '" + Dir + "' directive");
04342 
04343   // Eat the end of statement.
04344   Lex();
04345 
04346   // Lex the rept definition.
04347   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
04348   if (!M)
04349     return true;
04350 
04351   // Macro instantiation is lexical, unfortunately. We construct a new buffer
04352   // to hold the macro body with substitutions.
04353   SmallString<256> Buf;
04354   raw_svector_ostream OS(Buf);
04355   while (Count--) {
04356     if (expandMacro(OS, M->Body, None, None, getTok().getLoc()))
04357       return true;
04358   }
04359   instantiateMacroLikeBody(M, DirectiveLoc, OS);
04360 
04361   return false;
04362 }
04363 
04364 /// parseDirectiveIrp
04365 /// ::= .irp symbol,values
04366 bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
04367   MCAsmMacroParameter Parameter;
04368 
04369   if (parseIdentifier(Parameter.Name))
04370     return TokError("expected identifier in '.irp' directive");
04371 
04372   if (Lexer.isNot(AsmToken::Comma))
04373     return TokError("expected comma in '.irp' directive");
04374 
04375   Lex();
04376 
04377   MCAsmMacroArguments A;
04378   if (parseMacroArguments(nullptr, A))
04379     return true;
04380 
04381   // Eat the end of statement.
04382   Lex();
04383 
04384   // Lex the irp definition.
04385   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
04386   if (!M)
04387     return true;
04388 
04389   // Macro instantiation is lexical, unfortunately. We construct a new buffer
04390   // to hold the macro body with substitutions.
04391   SmallString<256> Buf;
04392   raw_svector_ostream OS(Buf);
04393 
04394   for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
04395     if (expandMacro(OS, M->Body, Parameter, *i, getTok().getLoc()))
04396       return true;
04397   }
04398 
04399   instantiateMacroLikeBody(M, DirectiveLoc, OS);
04400 
04401   return false;
04402 }
04403 
04404 /// parseDirectiveIrpc
04405 /// ::= .irpc symbol,values
04406 bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
04407   MCAsmMacroParameter Parameter;
04408 
04409   if (parseIdentifier(Parameter.Name))
04410     return TokError("expected identifier in '.irpc' directive");
04411 
04412   if (Lexer.isNot(AsmToken::Comma))
04413     return TokError("expected comma in '.irpc' directive");
04414 
04415   Lex();
04416 
04417   MCAsmMacroArguments A;
04418   if (parseMacroArguments(nullptr, A))
04419     return true;
04420 
04421   if (A.size() != 1 || A.front().size() != 1)
04422     return TokError("unexpected token in '.irpc' directive");
04423 
04424   // Eat the end of statement.
04425   Lex();
04426 
04427   // Lex the irpc definition.
04428   MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
04429   if (!M)
04430     return true;
04431 
04432   // Macro instantiation is lexical, unfortunately. We construct a new buffer
04433   // to hold the macro body with substitutions.
04434   SmallString<256> Buf;
04435   raw_svector_ostream OS(Buf);
04436 
04437   StringRef Values = A.front().front().getString();
04438   for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
04439     MCAsmMacroArgument Arg;
04440     Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I + 1)));
04441 
04442     if (expandMacro(OS, M->Body, Parameter, Arg, getTok().getLoc()))
04443       return true;
04444   }
04445 
04446   instantiateMacroLikeBody(M, DirectiveLoc, OS);
04447 
04448   return false;
04449 }
04450 
04451 bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
04452   if (ActiveMacros.empty())
04453     return TokError("unmatched '.endr' directive");
04454 
04455   // The only .repl that should get here are the ones created by
04456   // instantiateMacroLikeBody.
04457   assert(getLexer().is(AsmToken::EndOfStatement));
04458 
04459   handleMacroExit();
04460   return false;
04461 }
04462 
04463 bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
04464                                      size_t Len) {
04465   const MCExpr *Value;
04466   SMLoc ExprLoc = getLexer().getLoc();
04467   if (parseExpression(Value))
04468     return true;
04469   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
04470   if (!MCE)
04471     return Error(ExprLoc, "unexpected expression in _emit");
04472   uint64_t IntValue = MCE->getValue();
04473   if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
04474     return Error(ExprLoc, "literal value out of range for directive");
04475 
04476   Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
04477   return false;
04478 }
04479 
04480 bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
04481   const MCExpr *Value;
04482   SMLoc ExprLoc = getLexer().getLoc();
04483   if (parseExpression(Value))
04484     return true;
04485   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
04486   if (!MCE)
04487     return Error(ExprLoc, "unexpected expression in align");
04488   uint64_t IntValue = MCE->getValue();
04489   if (!isPowerOf2_64(IntValue))
04490     return Error(ExprLoc, "literal value not a power of two greater then zero");
04491 
04492   Info.AsmRewrites->push_back(
04493       AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
04494   return false;
04495 }
04496 
04497 // We are comparing pointers, but the pointers are relative to a single string.
04498 // Thus, this should always be deterministic.
04499 static int rewritesSort(const AsmRewrite *AsmRewriteA,
04500                         const AsmRewrite *AsmRewriteB) {
04501   if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
04502     return -1;
04503   if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
04504     return 1;
04505 
04506   // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
04507   // rewrite to the same location.  Make sure the SizeDirective rewrite is
04508   // performed first, then the Imm/ImmPrefix and finally the Input/Output.  This
04509   // ensures the sort algorithm is stable.
04510   if (AsmRewritePrecedence[AsmRewriteA->Kind] >
04511       AsmRewritePrecedence[AsmRewriteB->Kind])
04512     return -1;
04513 
04514   if (AsmRewritePrecedence[AsmRewriteA->Kind] <
04515       AsmRewritePrecedence[AsmRewriteB->Kind])
04516     return 1;
04517   llvm_unreachable("Unstable rewrite sort.");
04518 }
04519 
04520 bool AsmParser::parseMSInlineAsm(
04521     void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
04522     unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
04523     SmallVectorImpl<std::string> &Constraints,
04524     SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
04525     const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
04526   SmallVector<void *, 4> InputDecls;
04527   SmallVector<void *, 4> OutputDecls;
04528   SmallVector<bool, 4> InputDeclsAddressOf;
04529   SmallVector<bool, 4> OutputDeclsAddressOf;
04530   SmallVector<std::string, 4> InputConstraints;
04531   SmallVector<std::string, 4> OutputConstraints;
04532   SmallVector<unsigned, 4> ClobberRegs;
04533 
04534   SmallVector<AsmRewrite, 4> AsmStrRewrites;
04535 
04536   // Prime the lexer.
04537   Lex();
04538 
04539   // While we have input, parse each statement.
04540   unsigned InputIdx = 0;
04541   unsigned OutputIdx = 0;
04542   while (getLexer().isNot(AsmToken::Eof)) {
04543     ParseStatementInfo Info(&AsmStrRewrites);
04544     if (parseStatement(Info))
04545       return true;
04546 
04547     if (Info.ParseError)
04548       return true;
04549 
04550     if (Info.Opcode == ~0U)
04551       continue;
04552 
04553     const MCInstrDesc &Desc = MII->get(Info.Opcode);
04554 
04555     // Build the list of clobbers, outputs and inputs.
04556     for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
04557       MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
04558 
04559       // Immediate.
04560       if (Operand.isImm())
04561         continue;
04562 
04563       // Register operand.
04564       if (Operand.isReg() && !Operand.needAddressOf() &&
04565           !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
04566         unsigned NumDefs = Desc.getNumDefs();
04567         // Clobber.
04568         if (NumDefs && Operand.getMCOperandNum() < NumDefs)
04569           ClobberRegs.push_back(Operand.getReg());
04570         continue;
04571       }
04572 
04573       // Expr/Input or Output.
04574       StringRef SymName = Operand.getSymName();
04575       if (SymName.empty())
04576         continue;
04577 
04578       void *OpDecl = Operand.getOpDecl();
04579       if (!OpDecl)
04580         continue;
04581 
04582       bool isOutput = (i == 1) && Desc.mayStore();
04583       SMLoc Start = SMLoc::getFromPointer(SymName.data());
04584       if (isOutput) {
04585         ++InputIdx;
04586         OutputDecls.push_back(OpDecl);
04587         OutputDeclsAddressOf.push_back(Operand.needAddressOf());
04588         OutputConstraints.push_back('=' + Operand.getConstraint().str());
04589         AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
04590       } else {
04591         InputDecls.push_back(OpDecl);
04592         InputDeclsAddressOf.push_back(Operand.needAddressOf());
04593         InputConstraints.push_back(Operand.getConstraint().str());
04594         AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
04595       }
04596     }
04597 
04598     // Consider implicit defs to be clobbers.  Think of cpuid and push.
04599     ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
04600                                Desc.getNumImplicitDefs());
04601     ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
04602   }
04603 
04604   // Set the number of Outputs and Inputs.
04605   NumOutputs = OutputDecls.size();
04606   NumInputs = InputDecls.size();
04607 
04608   // Set the unique clobbers.
04609   array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
04610   ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
04611                     ClobberRegs.end());
04612   Clobbers.assign(ClobberRegs.size(), std::string());
04613   for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
04614     raw_string_ostream OS(Clobbers[I]);
04615     IP->printRegName(OS, ClobberRegs[I]);
04616   }
04617 
04618   // Merge the various outputs and inputs.  Output are expected first.
04619   if (NumOutputs || NumInputs) {
04620     unsigned NumExprs = NumOutputs + NumInputs;
04621     OpDecls.resize(NumExprs);
04622     Constraints.resize(NumExprs);
04623     for (unsigned i = 0; i < NumOutputs; ++i) {
04624       OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
04625       Constraints[i] = OutputConstraints[i];
04626     }
04627     for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
04628       OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
04629       Constraints[j] = InputConstraints[i];
04630     }
04631   }
04632 
04633   // Build the IR assembly string.
04634   std::string AsmStringIR;
04635   raw_string_ostream OS(AsmStringIR);
04636   StringRef ASMString =
04637       SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
04638   const char *AsmStart = ASMString.begin();
04639   const char *AsmEnd = ASMString.end();
04640   array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
04641   for (const AsmRewrite &AR : AsmStrRewrites) {
04642     AsmRewriteKind Kind = AR.Kind;
04643     if (Kind == AOK_Delete)
04644       continue;
04645 
04646     const char *Loc = AR.Loc.getPointer();
04647     assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
04648 
04649     // Emit everything up to the immediate/expression.
04650     if (unsigned Len = Loc - AsmStart)
04651       OS << StringRef(AsmStart, Len);
04652 
04653     // Skip the original expression.
04654     if (Kind == AOK_Skip) {
04655       AsmStart = Loc + AR.Len;
04656       continue;
04657     }
04658 
04659     unsigned AdditionalSkip = 0;
04660     // Rewrite expressions in $N notation.
04661     switch (Kind) {
04662     default:
04663       break;
04664     case AOK_Imm:
04665       OS << "$$" << AR.Val;
04666       break;
04667     case AOK_ImmPrefix:
04668       OS << "$$";
04669       break;
04670     case AOK_Input:
04671       OS << '$' << InputIdx++;
04672       break;
04673     case AOK_Output:
04674       OS << '$' << OutputIdx++;
04675       break;
04676     case AOK_SizeDirective:
04677       switch (AR.Val) {
04678       default: break;
04679       case 8:  OS << "byte ptr "; break;
04680       case 16: OS << "word ptr "; break;
04681       case 32: OS << "dword ptr "; break;
04682       case 64: OS << "qword ptr "; break;
04683       case 80: OS << "xword ptr "; break;
04684       case 128: OS << "xmmword ptr "; break;
04685       case 256: OS << "ymmword ptr "; break;
04686       }
04687       break;
04688     case AOK_Emit:
04689       OS << ".byte";
04690       break;
04691     case AOK_Align: {
04692       unsigned Val = AR.Val;
04693       OS << ".align " << Val;
04694 
04695       // Skip the original immediate.
04696       assert(Val < 10 && "Expected alignment less then 2^10.");
04697       AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
04698       break;
04699     }
04700     case AOK_DotOperator:
04701       // Insert the dot if the user omitted it.
04702       OS.flush();
04703       if (AsmStringIR.back() != '.')
04704         OS << '.';
04705       OS << AR.Val;
04706       break;
04707     }
04708 
04709     // Skip the original expression.
04710     AsmStart = Loc + AR.Len + AdditionalSkip;
04711   }
04712 
04713   // Emit the remainder of the asm string.
04714   if (AsmStart != AsmEnd)
04715     OS << StringRef(AsmStart, AsmEnd - AsmStart);
04716 
04717   AsmString = OS.str();
04718   return false;
04719 }
04720 
04721 /// \brief Create an MCAsmParser instance.
04722 MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
04723                                      MCStreamer &Out, const MCAsmInfo &MAI) {
04724   return new AsmParser(SM, C, Out, MAI);
04725 }