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