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