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/Parser.h"
19 #include "llvm/IR/Attributes.h"
20 #include "llvm/IR/FMF.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/ModuleSummaryIndex.h"
23 #include <map>
24 
25 namespace llvm {
26   class Module;
27   class ConstantRange;
28   class FunctionType;
29   class GlobalObject;
30   class SMDiagnostic;
31   class SMLoc;
32   class SourceMgr;
33   class Type;
34   struct MaybeAlign;
35   template <typename T> class Optional;
36   class Function;
37   class Value;
38   class BasicBlock;
39   class Instruction;
40   class Constant;
41   class GlobalValue;
42   class Comdat;
43   class MDString;
44   class MDNode;
45   struct SlotMapping;
46 
47   /// ValID - Represents a reference of a definition of some sort with no type.
48   /// There are several cases where we have to parse the value but where the
49   /// type can depend on later context.  This may either be a numeric reference
50   /// or a symbolic (%var) reference.  This is just a discriminated union.
51   struct ValID {
52     enum {
53       t_LocalID, t_GlobalID,           // ID in UIntVal.
54       t_LocalName, t_GlobalName,       // Name in StrVal.
55       t_APSInt, t_APFloat,             // Value in APSIntVal/APFloatVal.
56       t_Null, t_Undef, t_Zero, t_None, t_Poison, // No value.
57       t_EmptyArray,                    // No value:  []
58       t_Constant,                      // Value in ConstantVal.
59       t_InlineAsm,                     // Value in FTy/StrVal/StrVal2/UIntVal.
60       t_ConstantStruct,                // Value in ConstantStructElts.
61       t_PackedConstantStruct           // Value in ConstantStructElts.
62     } Kind = t_LocalID;
63 
64     LLLexer::LocTy Loc;
65     unsigned UIntVal;
66     FunctionType *FTy = nullptr;
67     std::string StrVal, StrVal2;
68     APSInt APSIntVal;
69     APFloat APFloatVal{0.0};
70     Constant *ConstantVal;
71     std::unique_ptr<Constant *[]> ConstantStructElts;
72     bool NoCFI = false;
73 
74     ValID() = default;
75     ValID(const ValID &RHS)
76         : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
77           StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
78           APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal),
79           NoCFI(RHS.NoCFI) {
80       assert(!RHS.ConstantStructElts);
81     }
82 
83     bool operator<(const ValID &RHS) const {
84       if (Kind == t_LocalID || Kind == t_GlobalID)
85         return UIntVal < RHS.UIntVal;
86       assert((Kind == t_LocalName || Kind == t_GlobalName ||
87               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
88              "Ordering not defined for this ValID kind yet");
89       return StrVal < RHS.StrVal;
90     }
91   };
92 
93   class LLParser {
94   public:
95     typedef LLLexer::LocTy LocTy;
96   private:
97     LLVMContext &Context;
98     // Lexer to determine whether to use opaque pointers or not.
99     LLLexer OPLex;
100     LLLexer Lex;
101     // Module being parsed, null if we are only parsing summary index.
102     Module *M;
103     // Summary index being parsed, null if we are only parsing Module.
104     ModuleSummaryIndex *Index;
105     SlotMapping *Slots;
106 
107     SmallVector<Instruction*, 64> InstsWithTBAATag;
108 
109     // Type resolution handling data structures.  The location is set when we
110     // have processed a use of the type but not a definition yet.
111     StringMap<std::pair<Type*, LocTy> > NamedTypes;
112     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
113 
114     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
115     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
116 
117     // Global Value reference information.
118     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
119     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
120     std::vector<GlobalValue*> NumberedVals;
121 
122     // Comdat forward reference information.
123     std::map<std::string, LocTy> ForwardRefComdats;
124 
125     // References to blockaddress.  The key is the function ValID, the value is
126     // a list of references to blocks in that function.
127     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
128     class PerFunctionState;
129     /// Reference to per-function state to allow basic blocks to be
130     /// forward-referenced by blockaddress instructions within the same
131     /// function.
132     PerFunctionState *BlockAddressPFS;
133 
134     // Attribute builder reference information.
135     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
136     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
137 
138     // Summary global value reference information.
139     std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
140         ForwardRefValueInfos;
141     std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
142         ForwardRefAliasees;
143     std::vector<ValueInfo> NumberedValueInfos;
144 
145     // Summary type id reference information.
146     std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
147         ForwardRefTypeIds;
148 
149     // Map of module ID to path.
150     std::map<unsigned, StringRef> ModuleIdMap;
151 
152     /// Only the llvm-as tool may set this to false to bypass
153     /// UpgradeDebuginfo so it can generate broken bitcode.
154     bool UpgradeDebugInfo;
155 
156     std::string SourceFileName;
157 
158   public:
159     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
160              ModuleSummaryIndex *Index, LLVMContext &Context,
161              SlotMapping *Slots = nullptr)
162         : Context(Context), OPLex(F, SM, Err, Context),
163           Lex(F, SM, Err, Context), M(M), Index(Index), Slots(Slots),
164           BlockAddressPFS(nullptr) {}
165     bool Run(
166         bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback =
167                                    [](StringRef) { return None; });
168 
169     bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
170 
171     bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
172                               const SlotMapping *Slots);
173 
174     LLVMContext &getContext() { return Context; }
175 
176   private:
177     bool error(LocTy L, const Twine &Msg) const { return Lex.Error(L, Msg); }
178     bool tokError(const Twine &Msg) const { return error(Lex.getLoc(), Msg); }
179 
180     /// Restore the internal name and slot mappings using the mappings that
181     /// were created at an earlier parsing stage.
182     void restoreParsingState(const SlotMapping *Slots);
183 
184     /// getGlobalVal - Get a value with the specified name or ID, creating a
185     /// forward reference record if needed.  This can return null if the value
186     /// exists but does not have the right type.
187     GlobalValue *getGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
188     GlobalValue *getGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
189 
190     /// Get a Comdat with the specified name, creating a forward reference
191     /// record if needed.
192     Comdat *getComdat(const std::string &Name, LocTy Loc);
193 
194     // Helper Routines.
195     bool parseToken(lltok::Kind T, const char *ErrMsg);
196     bool EatIfPresent(lltok::Kind T) {
197       if (Lex.getKind() != T) return false;
198       Lex.Lex();
199       return true;
200     }
201 
202     FastMathFlags EatFastMathFlagsIfPresent() {
203       FastMathFlags FMF;
204       while (true)
205         switch (Lex.getKind()) {
206         case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
207         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
208         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
209         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
210         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
211         case lltok::kw_contract:
212           FMF.setAllowContract(true);
213           Lex.Lex();
214           continue;
215         case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
216         case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
217         default: return FMF;
218         }
219       return FMF;
220     }
221 
222     bool parseOptionalToken(lltok::Kind T, bool &Present,
223                             LocTy *Loc = nullptr) {
224       if (Lex.getKind() != T) {
225         Present = false;
226       } else {
227         if (Loc)
228           *Loc = Lex.getLoc();
229         Lex.Lex();
230         Present = true;
231       }
232       return false;
233     }
234     bool parseStringConstant(std::string &Result);
235     bool parseUInt32(unsigned &Val);
236     bool parseUInt32(unsigned &Val, LocTy &Loc) {
237       Loc = Lex.getLoc();
238       return parseUInt32(Val);
239     }
240     bool parseUInt64(uint64_t &Val);
241     bool parseUInt64(uint64_t &Val, LocTy &Loc) {
242       Loc = Lex.getLoc();
243       return parseUInt64(Val);
244     }
245     bool parseFlag(unsigned &Val);
246 
247     bool parseStringAttribute(AttrBuilder &B);
248 
249     bool parseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
250     bool parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
251     bool parseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
252     bool parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
253     bool parseOptionalProgramAddrSpace(unsigned &AddrSpace) {
254       return parseOptionalAddrSpace(
255           AddrSpace, M->getDataLayout().getProgramAddressSpace());
256     };
257     bool parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
258                             bool InAttrGroup);
259     bool parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam);
260     bool parseOptionalParamAttrs(AttrBuilder &B) {
261       return parseOptionalParamOrReturnAttrs(B, true);
262     }
263     bool parseOptionalReturnAttrs(AttrBuilder &B) {
264       return parseOptionalParamOrReturnAttrs(B, false);
265     }
266     bool parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
267                               unsigned &Visibility, unsigned &DLLStorageClass,
268                               bool &DSOLocal);
269     void parseOptionalDSOLocal(bool &DSOLocal);
270     void parseOptionalVisibility(unsigned &Res);
271     void parseOptionalDLLStorageClass(unsigned &Res);
272     bool parseOptionalCallingConv(unsigned &CC);
273     bool parseOptionalAlignment(MaybeAlign &Alignment,
274                                 bool AllowParens = false);
275     bool parseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
276     bool parseOptionalUWTableKind(UWTableKind &Kind);
277     bool parseAllocKind(AllocFnKind &Kind);
278     bool parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
279                                AtomicOrdering &Ordering);
280     bool parseScope(SyncScope::ID &SSID);
281     bool parseOrdering(AtomicOrdering &Ordering);
282     bool parseOptionalStackAlignment(unsigned &Alignment);
283     bool parseOptionalCommaAlign(MaybeAlign &Alignment, bool &AteExtraComma);
284     bool parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
285                                      bool &AteExtraComma);
286     bool parseAllocSizeArguments(unsigned &BaseSizeArg,
287                                  Optional<unsigned> &HowManyArg);
288     bool parseVScaleRangeArguments(unsigned &MinValue, unsigned &MaxValue);
289     bool parseIndexList(SmallVectorImpl<unsigned> &Indices,
290                         bool &AteExtraComma);
291     bool parseIndexList(SmallVectorImpl<unsigned> &Indices) {
292       bool AteExtraComma;
293       if (parseIndexList(Indices, AteExtraComma))
294         return true;
295       if (AteExtraComma)
296         return tokError("expected index");
297       return false;
298     }
299 
300     // Top-Level Entities
301     bool parseTopLevelEntities();
302     bool validateEndOfModule(bool UpgradeDebugInfo);
303     bool validateEndOfIndex();
304     bool parseTargetDefinitions();
305     bool parseTargetDefinition();
306     bool parseModuleAsm();
307     bool parseSourceFileName();
308     bool parseUnnamedType();
309     bool parseNamedType();
310     bool parseDeclare();
311     bool parseDefine();
312 
313     bool parseGlobalType(bool &IsConstant);
314     bool parseUnnamedGlobal();
315     bool parseNamedGlobal();
316     bool parseGlobal(const std::string &Name, LocTy NameLoc, unsigned Linkage,
317                      bool HasLinkage, unsigned Visibility,
318                      unsigned DLLStorageClass, bool DSOLocal,
319                      GlobalVariable::ThreadLocalMode TLM,
320                      GlobalVariable::UnnamedAddr UnnamedAddr);
321     bool parseAliasOrIFunc(const std::string &Name, LocTy NameLoc, unsigned L,
322                            unsigned Visibility, unsigned DLLStorageClass,
323                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
324                            GlobalVariable::UnnamedAddr UnnamedAddr);
325     bool parseComdat();
326     bool parseStandaloneMetadata();
327     bool parseNamedMetadata();
328     bool parseMDString(MDString *&Result);
329     bool parseMDNodeID(MDNode *&Result);
330     bool parseUnnamedAttrGrp();
331     bool parseFnAttributeValuePairs(AttrBuilder &B,
332                                     std::vector<unsigned> &FwdRefAttrGrps,
333                                     bool inAttrGrp, LocTy &BuiltinLoc);
334     bool parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
335                                Attribute::AttrKind AttrKind);
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);
439       Value *getVal(unsigned ID, Type *Ty, LocTy Loc);
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);
462 
463     Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
464                                   Value *Val);
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,
512                     Type *ExpectedTy = nullptr);
513     bool parseGlobalValue(Type *Ty, Constant *&C);
514     bool parseGlobalTypeAndValue(Constant *&V);
515     bool parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
516                                 Optional<unsigned> *InRangeOp = nullptr);
517     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
518     bool parseSanitizer(GlobalVariable *GV);
519     bool parseMetadataAsValue(Value *&V, PerFunctionState &PFS);
520     bool parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
521                               PerFunctionState *PFS);
522     bool parseMetadata(Metadata *&MD, PerFunctionState *PFS);
523     bool parseMDTuple(MDNode *&MD, bool IsDistinct = false);
524     bool parseMDNode(MDNode *&N);
525     bool parseMDNodeTail(MDNode *&N);
526     bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
527     bool parseMetadataAttachment(unsigned &Kind, MDNode *&MD);
528     bool parseInstructionMetadata(Instruction &Inst);
529     bool parseGlobalObjectMetadataAttachment(GlobalObject &GO);
530     bool parseOptionalFunctionMetadata(Function &F);
531 
532     template <class FieldTy>
533     bool parseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
534     template <class FieldTy> bool parseMDField(StringRef Name, FieldTy &Result);
535     template <class ParserTy> bool parseMDFieldsImplBody(ParserTy ParseField);
536     template <class ParserTy>
537     bool parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc);
538     bool parseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
539 
540 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
541   bool parse##CLASS(MDNode *&Result, bool IsDistinct);
542 #include "llvm/IR/Metadata.def"
543     bool parseDIArgList(MDNode *&Result, bool IsDistinct,
544                         PerFunctionState *PFS);
545 
546     // Function Parsing.
547     struct ArgInfo {
548       LocTy Loc;
549       Type *Ty;
550       AttributeSet Attrs;
551       std::string Name;
552       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
553           : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
554     };
555     bool parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &IsVarArg);
556     bool parseFunctionHeader(Function *&Fn, bool IsDefine);
557     bool parseFunctionBody(Function &Fn);
558     bool parseBasicBlock(PerFunctionState &PFS);
559 
560     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
561 
562     // Instruction Parsing.  Each instruction parsing routine can return with a
563     // normal result, an error result, or return having eaten an extra comma.
564     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
565     int parseInstruction(Instruction *&Inst, BasicBlock *BB,
566                          PerFunctionState &PFS);
567     bool parseCmpPredicate(unsigned &P, unsigned Opc);
568 
569     bool parseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
570     bool parseBr(Instruction *&Inst, PerFunctionState &PFS);
571     bool parseSwitch(Instruction *&Inst, PerFunctionState &PFS);
572     bool parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
573     bool parseInvoke(Instruction *&Inst, PerFunctionState &PFS);
574     bool parseResume(Instruction *&Inst, PerFunctionState &PFS);
575     bool parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
576     bool parseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
577     bool parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
578     bool parseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
579     bool parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
580     bool parseCallBr(Instruction *&Inst, PerFunctionState &PFS);
581 
582     bool parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
583                       bool IsFP);
584     bool parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
585                          unsigned Opc, bool IsFP);
586     bool parseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
587     bool parseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
588     bool parseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
589     bool parseSelect(Instruction *&Inst, PerFunctionState &PFS);
590     bool parseVAArg(Instruction *&Inst, PerFunctionState &PFS);
591     bool parseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
592     bool parseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
593     bool parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
594     int parsePHI(Instruction *&Inst, PerFunctionState &PFS);
595     bool parseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
596     bool parseCall(Instruction *&Inst, PerFunctionState &PFS,
597                    CallInst::TailCallKind TCK);
598     int parseAlloc(Instruction *&Inst, PerFunctionState &PFS);
599     int parseLoad(Instruction *&Inst, PerFunctionState &PFS);
600     int parseStore(Instruction *&Inst, PerFunctionState &PFS);
601     int parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
602     int parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
603     int parseFence(Instruction *&Inst, PerFunctionState &PFS);
604     int parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
605     int parseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
606     int parseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
607     bool parseFreeze(Instruction *&I, PerFunctionState &PFS);
608 
609     // Use-list order directives.
610     bool parseUseListOrder(PerFunctionState *PFS = nullptr);
611     bool parseUseListOrderBB();
612     bool parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
613     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
614   };
615 } // End llvm namespace
616 
617 #endif
618