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