Home | History | Annotate | Line # | Download | only in AsmParser
      1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 //  This file defines the parser class for .ll files.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
     14 #define LLVM_LIB_ASMPARSER_LLPARSER_H
     15 
     16 #include "LLLexer.h"
     17 #include "llvm/ADT/Optional.h"
     18 #include "llvm/ADT/StringMap.h"
     19 #include "llvm/AsmParser/Parser.h"
     20 #include "llvm/IR/Attributes.h"
     21 #include "llvm/IR/Instructions.h"
     22 #include "llvm/IR/ModuleSummaryIndex.h"
     23 #include "llvm/IR/Operator.h"
     24 #include "llvm/IR/Type.h"
     25 #include <map>
     26 
     27 namespace llvm {
     28   class Module;
     29   class Function;
     30   class Value;
     31   class BasicBlock;
     32   class Instruction;
     33   class Constant;
     34   class GlobalValue;
     35   class Comdat;
     36   class MDString;
     37   class MDNode;
     38   struct SlotMapping;
     39 
     40   /// ValID - Represents a reference of a definition of some sort with no type.
     41   /// There are several cases where we have to parse the value but where the
     42   /// type can depend on later context.  This may either be a numeric reference
     43   /// or a symbolic (%var) reference.  This is just a discriminated union.
     44   struct ValID {
     45     enum {
     46       t_LocalID, t_GlobalID,           // ID in UIntVal.
     47       t_LocalName, t_GlobalName,       // Name in StrVal.
     48       t_APSInt, t_APFloat,             // Value in APSIntVal/APFloatVal.
     49       t_Null, t_Undef, t_Zero, t_None, t_Poison, // No value.
     50       t_EmptyArray,                    // No value:  []
     51       t_Constant,                      // Value in ConstantVal.
     52       t_InlineAsm,                     // Value in FTy/StrVal/StrVal2/UIntVal.
     53       t_ConstantStruct,                // Value in ConstantStructElts.
     54       t_PackedConstantStruct           // Value in ConstantStructElts.
     55     } Kind = t_LocalID;
     56 
     57     LLLexer::LocTy Loc;
     58     unsigned UIntVal;
     59     FunctionType *FTy = nullptr;
     60     std::string StrVal, StrVal2;
     61     APSInt APSIntVal;
     62     APFloat APFloatVal{0.0};
     63     Constant *ConstantVal;
     64     std::unique_ptr<Constant *[]> ConstantStructElts;
     65 
     66     ValID() = default;
     67     ValID(const ValID &RHS)
     68         : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
     69           StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
     70           APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal) {
     71       assert(!RHS.ConstantStructElts);
     72     }
     73 
     74     bool operator<(const ValID &RHS) const {
     75       if (Kind == t_LocalID || Kind == t_GlobalID)
     76         return UIntVal < RHS.UIntVal;
     77       assert((Kind == t_LocalName || Kind == t_GlobalName ||
     78               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
     79              "Ordering not defined for this ValID kind yet");
     80       return StrVal < RHS.StrVal;
     81     }
     82   };
     83 
     84   class LLParser {
     85   public:
     86     typedef LLLexer::LocTy LocTy;
     87   private:
     88     LLVMContext &Context;
     89     LLLexer Lex;
     90     // Module being parsed, null if we are only parsing summary index.
     91     Module *M;
     92     // Summary index being parsed, null if we are only parsing Module.
     93     ModuleSummaryIndex *Index;
     94     SlotMapping *Slots;
     95 
     96     // Instruction metadata resolution.  Each instruction can have a list of
     97     // MDRef info associated with them.
     98     //
     99     // The simpler approach of just creating temporary MDNodes and then calling
    100     // RAUW on them when the definition is processed doesn't work because some
    101     // instruction metadata kinds, such as dbg, get stored in the IR in an
    102     // "optimized" format which doesn't participate in the normal value use
    103     // lists. This means that RAUW doesn't work, even on temporary MDNodes
    104     // which otherwise support RAUW. Instead, we defer resolving MDNode
    105     // references until the definitions have been processed.
    106     struct MDRef {
    107       SMLoc Loc;
    108       unsigned MDKind, MDSlot;
    109     };
    110 
    111     SmallVector<Instruction*, 64> InstsWithTBAATag;
    112 
    113     // Type resolution handling data structures.  The location is set when we
    114     // have processed a use of the type but not a definition yet.
    115     StringMap<std::pair<Type*, LocTy> > NamedTypes;
    116     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
    117 
    118     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
    119     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
    120 
    121     // Global Value reference information.
    122     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
    123     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
    124     std::vector<GlobalValue*> NumberedVals;
    125 
    126     // Comdat forward reference information.
    127     std::map<std::string, LocTy> ForwardRefComdats;
    128 
    129     // References to blockaddress.  The key is the function ValID, the value is
    130     // a list of references to blocks in that function.
    131     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
    132     class PerFunctionState;
    133     /// Reference to per-function state to allow basic blocks to be
    134     /// forward-referenced by blockaddress instructions within the same
    135     /// function.
    136     PerFunctionState *BlockAddressPFS;
    137 
    138     // Attribute builder reference information.
    139     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
    140     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
    141 
    142     // Summary global value reference information.
    143     std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
    144         ForwardRefValueInfos;
    145     std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
    146         ForwardRefAliasees;
    147     std::vector<ValueInfo> NumberedValueInfos;
    148 
    149     // Summary type id reference information.
    150     std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
    151         ForwardRefTypeIds;
    152 
    153     // Map of module ID to path.
    154     std::map<unsigned, StringRef> ModuleIdMap;
    155 
    156     /// Only the llvm-as tool may set this to false to bypass
    157     /// UpgradeDebuginfo so it can generate broken bitcode.
    158     bool UpgradeDebugInfo;
    159 
    160     std::string SourceFileName;
    161 
    162   public:
    163     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
    164              ModuleSummaryIndex *Index, LLVMContext &Context,
    165              SlotMapping *Slots = nullptr)
    166         : Context(Context), Lex(F, SM, Err, Context), M(M), Index(Index),
    167           Slots(Slots), BlockAddressPFS(nullptr) {}
    168     bool Run(
    169         bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback =
    170                                    [](StringRef) { return None; });
    171 
    172     bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
    173 
    174     bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
    175                               const SlotMapping *Slots);
    176 
    177     LLVMContext &getContext() { return Context; }
    178 
    179   private:
    180     bool error(LocTy L, const Twine &Msg) const { return Lex.Error(L, Msg); }
    181     bool tokError(const Twine &Msg) const { return error(Lex.getLoc(), Msg); }
    182 
    183     /// Restore the internal name and slot mappings using the mappings that
    184     /// were created at an earlier parsing stage.
    185     void restoreParsingState(const SlotMapping *Slots);
    186 
    187     /// getGlobalVal - Get a value with the specified name or ID, creating a
    188     /// forward reference record if needed.  This can return null if the value
    189     /// exists but does not have the right type.
    190     GlobalValue *getGlobalVal(const std::string &N, Type *Ty, LocTy Loc,
    191                               bool IsCall);
    192     GlobalValue *getGlobalVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
    193 
    194     /// Get a Comdat with the specified name, creating a forward reference
    195     /// record if needed.
    196     Comdat *getComdat(const std::string &Name, LocTy Loc);
    197 
    198     // Helper Routines.
    199     bool parseToken(lltok::Kind T, const char *ErrMsg);
    200     bool EatIfPresent(lltok::Kind T) {
    201       if (Lex.getKind() != T) return false;
    202       Lex.Lex();
    203       return true;
    204     }
    205 
    206     FastMathFlags EatFastMathFlagsIfPresent() {
    207       FastMathFlags FMF;
    208       while (true)
    209         switch (Lex.getKind()) {
    210         case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
    211         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
    212         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
    213         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
    214         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
    215         case lltok::kw_contract:
    216           FMF.setAllowContract(true);
    217           Lex.Lex();
    218           continue;
    219         case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
    220         case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
    221         default: return FMF;
    222         }
    223       return FMF;
    224     }
    225 
    226     bool parseOptionalToken(lltok::Kind T, bool &Present,
    227                             LocTy *Loc = nullptr) {
    228       if (Lex.getKind() != T) {
    229         Present = false;
    230       } else {
    231         if (Loc)
    232           *Loc = Lex.getLoc();
    233         Lex.Lex();
    234         Present = true;
    235       }
    236       return false;
    237     }
    238     bool parseStringConstant(std::string &Result);
    239     bool parseUInt32(unsigned &Val);
    240     bool parseUInt32(unsigned &Val, LocTy &Loc) {
    241       Loc = Lex.getLoc();
    242       return parseUInt32(Val);
    243     }
    244     bool parseUInt64(uint64_t &Val);
    245     bool parseUInt64(uint64_t &Val, LocTy &Loc) {
    246       Loc = Lex.getLoc();
    247       return parseUInt64(Val);
    248     }
    249     bool parseFlag(unsigned &Val);
    250 
    251     bool parseStringAttribute(AttrBuilder &B);
    252 
    253     bool parseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
    254     bool parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
    255     bool parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
    256     bool parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
    257     bool parseOptionalProgramAddrSpace(unsigned &AddrSpace) {
    258       return parseOptionalAddrSpace(
    259           AddrSpace, M->getDataLayout().getProgramAddressSpace());
    260     };
    261     bool parseOptionalParamAttrs(AttrBuilder &B);
    262     bool parseOptionalReturnAttrs(AttrBuilder &B);
    263     bool parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
    264                               unsigned &Visibility, unsigned &DLLStorageClass,
    265                               bool &DSOLocal);
    266     void parseOptionalDSOLocal(bool &DSOLocal);
    267     void parseOptionalVisibility(unsigned &Res);
    268     void parseOptionalDLLStorageClass(unsigned &Res);
    269     bool parseOptionalCallingConv(unsigned &CC);
    270     bool parseOptionalAlignment(MaybeAlign &Alignment,
    271                                 bool AllowParens = false);
    272     bool parseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
    273     bool parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
    274                                AtomicOrdering &Ordering);
    275     bool parseScope(SyncScope::ID &SSID);
    276     bool parseOrdering(AtomicOrdering &Ordering);
    277     bool parseOptionalStackAlignment(unsigned &Alignment);
    278     bool parseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
    279     bool parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
    280                                      bool &AteExtraComma);
    281     bool parseOptionalCommaInAlloca(bool &IsInAlloca);
    282     bool parseAllocSizeArguments(unsigned &BaseSizeArg,
    283                                  Optional<unsigned> &HowManyArg);
    284     bool parseVScaleRangeArguments(unsigned &MinValue, unsigned &MaxValue);
    285     bool parseIndexList(SmallVectorImpl<unsigned> &Indices,
    286                         bool &AteExtraComma);
    287     bool parseIndexList(SmallVectorImpl<unsigned> &Indices) {
    288       bool AteExtraComma;
    289       if (parseIndexList(Indices, AteExtraComma))
    290         return true;
    291       if (AteExtraComma)
    292         return tokError("expected index");
    293       return false;
    294     }
    295 
    296     // Top-Level Entities
    297     bool parseTopLevelEntities();
    298     bool validateEndOfModule(bool UpgradeDebugInfo);
    299     bool validateEndOfIndex();
    300     bool parseTargetDefinitions();
    301     bool parseTargetDefinition();
    302     bool parseModuleAsm();
    303     bool parseSourceFileName();
    304     bool parseDepLibs(); // FIXME: Remove in 4.0.
    305     bool parseUnnamedType();
    306     bool parseNamedType();
    307     bool parseDeclare();
    308     bool parseDefine();
    309 
    310     bool parseGlobalType(bool &IsConstant);
    311     bool parseUnnamedGlobal();
    312     bool parseNamedGlobal();
    313     bool parseGlobal(const std::string &Name, LocTy NameLoc, unsigned Linkage,
    314                      bool HasLinkage, unsigned Visibility,
    315                      unsigned DLLStorageClass, bool DSOLocal,
    316                      GlobalVariable::ThreadLocalMode TLM,
    317                      GlobalVariable::UnnamedAddr UnnamedAddr);
    318     bool parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
    319                              unsigned L, unsigned Visibility,
    320                              unsigned DLLStorageClass, bool DSOLocal,
    321                              GlobalVariable::ThreadLocalMode TLM,
    322                              GlobalVariable::UnnamedAddr UnnamedAddr);
    323     bool parseComdat();
    324     bool parseStandaloneMetadata();
    325     bool parseNamedMetadata();
    326     bool parseMDString(MDString *&Result);
    327     bool parseMDNodeID(MDNode *&Result);
    328     bool parseUnnamedAttrGrp();
    329     bool parseFnAttributeValuePairs(AttrBuilder &B,
    330                                     std::vector<unsigned> &FwdRefAttrGrps,
    331                                     bool inAttrGrp, LocTy &BuiltinLoc);
    332     bool parseRequiredTypeAttr(Type *&Result, lltok::Kind AttrName);
    333     bool parsePreallocated(Type *&Result);
    334     bool parseInalloca(Type *&Result);
    335     bool parseByRef(Type *&Result);
    336 
    337     // Module Summary Index Parsing.
    338     bool skipModuleSummaryEntry();
    339     bool parseSummaryEntry();
    340     bool parseModuleEntry(unsigned ID);
    341     bool parseModuleReference(StringRef &ModulePath);
    342     bool parseGVReference(ValueInfo &VI, unsigned &GVId);
    343     bool parseSummaryIndexFlags();
    344     bool parseBlockCount();
    345     bool parseGVEntry(unsigned ID);
    346     bool parseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
    347     bool parseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
    348     bool parseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
    349     bool parseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
    350     bool parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
    351     bool parseOptionalFFlags(FunctionSummary::FFlags &FFlags);
    352     bool parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
    353     bool parseHotness(CalleeInfo::HotnessType &Hotness);
    354     bool parseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
    355     bool parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
    356     bool parseVFuncIdList(lltok::Kind Kind,
    357                           std::vector<FunctionSummary::VFuncId> &VFuncIdList);
    358     bool parseConstVCallList(
    359         lltok::Kind Kind,
    360         std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
    361     using IdToIndexMapType =
    362         std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
    363     bool parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
    364                          IdToIndexMapType &IdToIndexMap, unsigned Index);
    365     bool parseVFuncId(FunctionSummary::VFuncId &VFuncId,
    366                       IdToIndexMapType &IdToIndexMap, unsigned Index);
    367     bool parseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
    368     bool parseOptionalParamAccesses(
    369         std::vector<FunctionSummary::ParamAccess> &Params);
    370     bool parseParamNo(uint64_t &ParamNo);
    371     using IdLocListType = std::vector<std::pair<unsigned, LocTy>>;
    372     bool parseParamAccess(FunctionSummary::ParamAccess &Param,
    373                           IdLocListType &IdLocList);
    374     bool parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
    375                               IdLocListType &IdLocList);
    376     bool parseParamAccessOffset(ConstantRange &Range);
    377     bool parseOptionalRefs(std::vector<ValueInfo> &Refs);
    378     bool parseTypeIdEntry(unsigned ID);
    379     bool parseTypeIdSummary(TypeIdSummary &TIS);
    380     bool parseTypeIdCompatibleVtableEntry(unsigned ID);
    381     bool parseTypeTestResolution(TypeTestResolution &TTRes);
    382     bool parseOptionalWpdResolutions(
    383         std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
    384     bool parseWpdRes(WholeProgramDevirtResolution &WPDRes);
    385     bool parseOptionalResByArg(
    386         std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
    387             &ResByArg);
    388     bool parseArgs(std::vector<uint64_t> &Args);
    389     void addGlobalValueToIndex(std::string Name, GlobalValue::GUID,
    390                                GlobalValue::LinkageTypes Linkage, unsigned ID,
    391                                std::unique_ptr<GlobalValueSummary> Summary);
    392 
    393     // Type Parsing.
    394     bool parseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
    395     bool parseType(Type *&Result, bool AllowVoid = false) {
    396       return parseType(Result, "expected type", AllowVoid);
    397     }
    398     bool parseType(Type *&Result, const Twine &Msg, LocTy &Loc,
    399                    bool AllowVoid = false) {
    400       Loc = Lex.getLoc();
    401       return parseType(Result, Msg, AllowVoid);
    402     }
    403     bool parseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
    404       Loc = Lex.getLoc();
    405       return parseType(Result, AllowVoid);
    406     }
    407     bool parseAnonStructType(Type *&Result, bool Packed);
    408     bool parseStructBody(SmallVectorImpl<Type *> &Body);
    409     bool parseStructDefinition(SMLoc TypeLoc, StringRef Name,
    410                                std::pair<Type *, LocTy> &Entry,
    411                                Type *&ResultTy);
    412 
    413     bool parseArrayVectorType(Type *&Result, bool IsVector);
    414     bool parseFunctionType(Type *&Result);
    415 
    416     // Function Semantic Analysis.
    417     class PerFunctionState {
    418       LLParser &P;
    419       Function &F;
    420       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
    421       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
    422       std::vector<Value*> NumberedVals;
    423 
    424       /// FunctionNumber - If this is an unnamed function, this is the slot
    425       /// number of it, otherwise it is -1.
    426       int FunctionNumber;
    427     public:
    428       PerFunctionState(LLParser &p, Function &f, int functionNumber);
    429       ~PerFunctionState();
    430 
    431       Function &getFunction() const { return F; }
    432 
    433       bool finishFunction();
    434 
    435       /// GetVal - Get a value with the specified name or ID, creating a
    436       /// forward reference record if needed.  This can return null if the value
    437       /// exists but does not have the right type.
    438       Value *getVal(const std::string &Name, Type *Ty, LocTy Loc, bool IsCall);
    439       Value *getVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
    440 
    441       /// setInstName - After an instruction is parsed and inserted into its
    442       /// basic block, this installs its name.
    443       bool setInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
    444                        Instruction *Inst);
    445 
    446       /// GetBB - Get a basic block with the specified name or ID, creating a
    447       /// forward reference record if needed.  This can return null if the value
    448       /// is not a BasicBlock.
    449       BasicBlock *getBB(const std::string &Name, LocTy Loc);
    450       BasicBlock *getBB(unsigned ID, LocTy Loc);
    451 
    452       /// DefineBB - Define the specified basic block, which is either named or
    453       /// unnamed.  If there is an error, this returns null otherwise it returns
    454       /// the block being defined.
    455       BasicBlock *defineBB(const std::string &Name, int NameID, LocTy Loc);
    456 
    457       bool resolveForwardRefBlockAddresses();
    458     };
    459 
    460     bool convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
    461                              PerFunctionState *PFS, bool IsCall);
    462 
    463     Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
    464                                   Value *Val, bool IsCall);
    465 
    466     bool parseConstantValue(Type *Ty, Constant *&C);
    467     bool parseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
    468     bool parseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
    469       return parseValue(Ty, V, &PFS);
    470     }
    471 
    472     bool parseValue(Type *Ty, Value *&V, LocTy &Loc, PerFunctionState &PFS) {
    473       Loc = Lex.getLoc();
    474       return parseValue(Ty, V, &PFS);
    475     }
    476 
    477     bool parseTypeAndValue(Value *&V, PerFunctionState *PFS);
    478     bool parseTypeAndValue(Value *&V, PerFunctionState &PFS) {
    479       return parseTypeAndValue(V, &PFS);
    480     }
    481     bool parseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
    482       Loc = Lex.getLoc();
    483       return parseTypeAndValue(V, PFS);
    484     }
    485     bool parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
    486                                 PerFunctionState &PFS);
    487     bool parseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
    488       LocTy Loc;
    489       return parseTypeAndBasicBlock(BB, Loc, PFS);
    490     }
    491 
    492     struct ParamInfo {
    493       LocTy Loc;
    494       Value *V;
    495       AttributeSet Attrs;
    496       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
    497           : Loc(loc), V(v), Attrs(attrs) {}
    498     };
    499     bool parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
    500                             PerFunctionState &PFS, bool IsMustTailCall = false,
    501                             bool InVarArgsFunc = false);
    502 
    503     bool
    504     parseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
    505                                 PerFunctionState &PFS);
    506 
    507     bool parseExceptionArgs(SmallVectorImpl<Value *> &Args,
    508                             PerFunctionState &PFS);
    509 
    510     // Constant Parsing.
    511     bool parseValID(ValID &ID, PerFunctionState *PFS = nullptr);
    512     bool parseGlobalValue(Type *Ty, Constant *&C);
    513     bool parseGlobalTypeAndValue(Constant *&V);
    514     bool parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
    515                                 Optional<unsigned> *InRangeOp = nullptr);
    516     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
    517     bool parseMetadataAsValue(Value *&V, PerFunctionState &PFS);
    518     bool parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
    519                               PerFunctionState *PFS);
    520     bool parseMetadata(Metadata *&MD, PerFunctionState *PFS);
    521     bool parseMDTuple(MDNode *&MD, bool IsDistinct = false);
    522     bool parseMDNode(MDNode *&N);
    523     bool parseMDNodeTail(MDNode *&N);
    524     bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
    525     bool parseMetadataAttachment(unsigned &Kind, MDNode *&MD);
    526     bool parseInstructionMetadata(Instruction &Inst);
    527     bool parseGlobalObjectMetadataAttachment(GlobalObject &GO);
    528     bool parseOptionalFunctionMetadata(Function &F);
    529 
    530     template <class FieldTy>
    531     bool parseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
    532     template <class FieldTy> bool parseMDField(StringRef Name, FieldTy &Result);
    533     template <class ParserTy> bool parseMDFieldsImplBody(ParserTy ParseField);
    534     template <class ParserTy>
    535     bool parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc);
    536     bool parseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
    537 
    538 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
    539   bool parse##CLASS(MDNode *&Result, bool IsDistinct);
    540 #include "llvm/IR/Metadata.def"
    541     bool parseDIArgList(MDNode *&Result, bool IsDistinct,
    542                         PerFunctionState *PFS);
    543 
    544     // Function Parsing.
    545     struct ArgInfo {
    546       LocTy Loc;
    547       Type *Ty;
    548       AttributeSet Attrs;
    549       std::string Name;
    550       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
    551           : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
    552     };
    553     bool parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &IsVarArg);
    554     bool parseFunctionHeader(Function *&Fn, bool IsDefine);
    555     bool parseFunctionBody(Function &Fn);
    556     bool parseBasicBlock(PerFunctionState &PFS);
    557 
    558     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
    559 
    560     // Instruction Parsing.  Each instruction parsing routine can return with a
    561     // normal result, an error result, or return having eaten an extra comma.
    562     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
    563     int parseInstruction(Instruction *&Inst, BasicBlock *BB,
    564                          PerFunctionState &PFS);
    565     bool parseCmpPredicate(unsigned &P, unsigned Opc);
    566 
    567     bool parseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
    568     bool parseBr(Instruction *&Inst, PerFunctionState &PFS);
    569     bool parseSwitch(Instruction *&Inst, PerFunctionState &PFS);
    570     bool parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
    571     bool parseInvoke(Instruction *&Inst, PerFunctionState &PFS);
    572     bool parseResume(Instruction *&Inst, PerFunctionState &PFS);
    573     bool parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
    574     bool parseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
    575     bool parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
    576     bool parseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
    577     bool parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
    578     bool parseCallBr(Instruction *&Inst, PerFunctionState &PFS);
    579 
    580     bool parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
    581                       bool IsFP);
    582     bool parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
    583                          unsigned Opc, bool IsFP);
    584     bool parseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
    585     bool parseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
    586     bool parseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
    587     bool parseSelect(Instruction *&Inst, PerFunctionState &PFS);
    588     bool parseVAArg(Instruction *&Inst, PerFunctionState &PFS);
    589     bool parseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
    590     bool parseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
    591     bool parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
    592     int parsePHI(Instruction *&Inst, PerFunctionState &PFS);
    593     bool parseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
    594     bool parseCall(Instruction *&Inst, PerFunctionState &PFS,
    595                    CallInst::TailCallKind TCK);
    596     int parseAlloc(Instruction *&Inst, PerFunctionState &PFS);
    597     int parseLoad(Instruction *&Inst, PerFunctionState &PFS);
    598     int parseStore(Instruction *&Inst, PerFunctionState &PFS);
    599     int parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
    600     int parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
    601     int parseFence(Instruction *&Inst, PerFunctionState &PFS);
    602     int parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
    603     int parseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
    604     int parseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
    605     bool parseFreeze(Instruction *&I, PerFunctionState &PFS);
    606 
    607     // Use-list order directives.
    608     bool parseUseListOrder(PerFunctionState *PFS = nullptr);
    609     bool parseUseListOrderBB();
    610     bool parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
    611     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
    612   };
    613 } // End llvm namespace
    614 
    615 #endif
    616