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
27namespace 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, // No value.
50      t_EmptyArray,                    // No value:  []
51      t_Constant,                      // Value in ConstantVal.
52      t_InlineAsm,                     // Value in FTy/StrVal/StrVal2/UIntVal.
53      t_ConstantStruct,                // Value in ConstantStructElts.
54      t_PackedConstantStruct           // Value in ConstantStructElts.
55    } Kind = t_LocalID;
56
57    LLLexer::LocTy Loc;
58    unsigned UIntVal;
59    FunctionType *FTy = nullptr;
60    std::string StrVal, StrVal2;
61    APSInt APSIntVal;
62    APFloat APFloatVal{0.0};
63    Constant *ConstantVal;
64    std::unique_ptr<Constant *[]> ConstantStructElts;
65
66    ValID() = default;
67    ValID(const ValID &RHS)
68        : Kind(RHS.Kind), Loc(RHS.Loc), UIntVal(RHS.UIntVal), FTy(RHS.FTy),
69          StrVal(RHS.StrVal), StrVal2(RHS.StrVal2), APSIntVal(RHS.APSIntVal),
70          APFloatVal(RHS.APFloatVal), ConstantVal(RHS.ConstantVal) {
71      assert(!RHS.ConstantStructElts);
72    }
73
74    bool operator<(const ValID &RHS) const {
75      if (Kind == t_LocalID || Kind == t_GlobalID)
76        return UIntVal < RHS.UIntVal;
77      assert((Kind == t_LocalName || Kind == t_GlobalName ||
78              Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
79             "Ordering not defined for this ValID kind yet");
80      return StrVal < RHS.StrVal;
81    }
82  };
83
84  class LLParser {
85  public:
86    typedef LLLexer::LocTy LocTy;
87  private:
88    LLVMContext &Context;
89    LLLexer Lex;
90    // Module being parsed, null if we are only parsing summary index.
91    Module *M;
92    // Summary index being parsed, null if we are only parsing Module.
93    ModuleSummaryIndex *Index;
94    SlotMapping *Slots;
95
96    // Instruction metadata resolution.  Each instruction can have a list of
97    // MDRef info associated with them.
98    //
99    // The simpler approach of just creating temporary MDNodes and then calling
100    // RAUW on them when the definition is processed doesn't work because some
101    // instruction metadata kinds, such as dbg, get stored in the IR in an
102    // "optimized" format which doesn't participate in the normal value use
103    // lists. This means that RAUW doesn't work, even on temporary MDNodes
104    // which otherwise support RAUW. Instead, we defer resolving MDNode
105    // references until the definitions have been processed.
106    struct MDRef {
107      SMLoc Loc;
108      unsigned MDKind, MDSlot;
109    };
110
111    SmallVector<Instruction*, 64> InstsWithTBAATag;
112
113    // Type resolution handling data structures.  The location is set when we
114    // have processed a use of the type but not a definition yet.
115    StringMap<std::pair<Type*, LocTy> > NamedTypes;
116    std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
117
118    std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
119    std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
120
121    // Global Value reference information.
122    std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
123    std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
124    std::vector<GlobalValue*> NumberedVals;
125
126    // Comdat forward reference information.
127    std::map<std::string, LocTy> ForwardRefComdats;
128
129    // References to blockaddress.  The key is the function ValID, the value is
130    // a list of references to blocks in that function.
131    std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
132    class PerFunctionState;
133    /// Reference to per-function state to allow basic blocks to be
134    /// forward-referenced by blockaddress instructions within the same
135    /// function.
136    PerFunctionState *BlockAddressPFS;
137
138    // Attribute builder reference information.
139    std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
140    std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
141
142    // Summary global value reference information.
143    std::map<unsigned, std::vector<std::pair<ValueInfo *, LocTy>>>
144        ForwardRefValueInfos;
145    std::map<unsigned, std::vector<std::pair<AliasSummary *, LocTy>>>
146        ForwardRefAliasees;
147    std::vector<ValueInfo> NumberedValueInfos;
148
149    // Summary type id reference information.
150    std::map<unsigned, std::vector<std::pair<GlobalValue::GUID *, LocTy>>>
151        ForwardRefTypeIds;
152
153    // Map of module ID to path.
154    std::map<unsigned, StringRef> ModuleIdMap;
155
156    /// Only the llvm-as tool may set this to false to bypass
157    /// UpgradeDebuginfo so it can generate broken bitcode.
158    bool UpgradeDebugInfo;
159
160    std::string SourceFileName;
161
162  public:
163    LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *M,
164             ModuleSummaryIndex *Index, LLVMContext &Context,
165             SlotMapping *Slots = nullptr)
166        : Context(Context), Lex(F, SM, Err, Context), M(M), Index(Index),
167          Slots(Slots), BlockAddressPFS(nullptr) {}
168    bool Run(
169        bool UpgradeDebugInfo,
170        DataLayoutCallbackTy DataLayoutCallback = [](Module *) {});
171
172    bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots);
173
174    bool parseTypeAtBeginning(Type *&Ty, unsigned &Read,
175                              const SlotMapping *Slots);
176
177    LLVMContext &getContext() { return Context; }
178
179  private:
180
181    bool Error(LocTy L, const Twine &Msg) const {
182      return Lex.Error(L, Msg);
183    }
184    bool TokError(const Twine &Msg) const {
185      return Error(Lex.getLoc(), Msg);
186    }
187
188    /// Restore the internal name and slot mappings using the mappings that
189    /// were created at an earlier parsing stage.
190    void restoreParsingState(const SlotMapping *Slots);
191
192    /// GetGlobalVal - Get a value with the specified name or ID, creating a
193    /// forward reference record if needed.  This can return null if the value
194    /// exists but does not have the right type.
195    GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc,
196                              bool IsCall);
197    GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
198
199    /// Get a Comdat with the specified name, creating a forward reference
200    /// record if needed.
201    Comdat *getComdat(const std::string &Name, LocTy Loc);
202
203    // Helper Routines.
204    bool ParseToken(lltok::Kind T, const char *ErrMsg);
205    bool EatIfPresent(lltok::Kind T) {
206      if (Lex.getKind() != T) return false;
207      Lex.Lex();
208      return true;
209    }
210
211    FastMathFlags EatFastMathFlagsIfPresent() {
212      FastMathFlags FMF;
213      while (true)
214        switch (Lex.getKind()) {
215        case lltok::kw_fast: FMF.setFast();            Lex.Lex(); continue;
216        case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
217        case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
218        case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
219        case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
220        case lltok::kw_contract:
221          FMF.setAllowContract(true);
222          Lex.Lex();
223          continue;
224        case lltok::kw_reassoc: FMF.setAllowReassoc(); Lex.Lex(); continue;
225        case lltok::kw_afn:     FMF.setApproxFunc();   Lex.Lex(); continue;
226        default: return FMF;
227        }
228      return FMF;
229    }
230
231    bool ParseOptionalToken(lltok::Kind T, bool &Present,
232                            LocTy *Loc = nullptr) {
233      if (Lex.getKind() != T) {
234        Present = false;
235      } else {
236        if (Loc)
237          *Loc = Lex.getLoc();
238        Lex.Lex();
239        Present = true;
240      }
241      return false;
242    }
243    bool ParseStringConstant(std::string &Result);
244    bool ParseUInt32(unsigned &Val);
245    bool ParseUInt32(unsigned &Val, LocTy &Loc) {
246      Loc = Lex.getLoc();
247      return ParseUInt32(Val);
248    }
249    bool ParseUInt64(uint64_t &Val);
250    bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
251      Loc = Lex.getLoc();
252      return ParseUInt64(Val);
253    }
254    bool ParseFlag(unsigned &Val);
255
256    bool ParseStringAttribute(AttrBuilder &B);
257
258    bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
259    bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
260    bool ParseOptionalUnnamedAddr(GlobalVariable::UnnamedAddr &UnnamedAddr);
261    bool ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS = 0);
262    bool ParseOptionalProgramAddrSpace(unsigned &AddrSpace) {
263      return ParseOptionalAddrSpace(
264          AddrSpace, M->getDataLayout().getProgramAddressSpace());
265    };
266    bool ParseOptionalParamAttrs(AttrBuilder &B);
267    bool ParseOptionalReturnAttrs(AttrBuilder &B);
268    bool ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
269                              unsigned &Visibility, unsigned &DLLStorageClass,
270                              bool &DSOLocal);
271    void ParseOptionalDSOLocal(bool &DSOLocal);
272    void ParseOptionalVisibility(unsigned &Res);
273    void ParseOptionalDLLStorageClass(unsigned &Res);
274    bool ParseOptionalCallingConv(unsigned &CC);
275    bool ParseOptionalAlignment(MaybeAlign &Alignment,
276                                bool AllowParens = false);
277    bool ParseOptionalDerefAttrBytes(lltok::Kind AttrKind, uint64_t &Bytes);
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 ParseOptionalCommaInAlloca(bool &IsInAlloca);
287    bool parseAllocSizeArguments(unsigned &BaseSizeArg,
288                                 Optional<unsigned> &HowManyArg);
289    bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,
290                        bool &AteExtraComma);
291    bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
292      bool AteExtraComma;
293      if (ParseIndexList(Indices, AteExtraComma)) return true;
294      if (AteExtraComma)
295        return TokError("expected index");
296      return false;
297    }
298
299    // Top-Level Entities
300    bool ParseTopLevelEntities();
301    bool ValidateEndOfModule(bool UpgradeDebugInfo);
302    bool ValidateEndOfIndex();
303    bool ParseTargetDefinitions();
304    bool ParseTargetDefinition();
305    bool ParseModuleAsm();
306    bool ParseSourceFileName();
307    bool ParseDepLibs();        // FIXME: Remove in 4.0.
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 parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
322                             unsigned L, unsigned Visibility,
323                             unsigned DLLStorageClass, bool DSOLocal,
324                             GlobalVariable::ThreadLocalMode TLM,
325                             GlobalVariable::UnnamedAddr UnnamedAddr);
326    bool parseComdat();
327    bool ParseStandaloneMetadata();
328    bool ParseNamedMetadata();
329    bool ParseMDString(MDString *&Result);
330    bool ParseMDNodeID(MDNode *&Result);
331    bool ParseUnnamedAttrGrp();
332    bool ParseFnAttributeValuePairs(AttrBuilder &B,
333                                    std::vector<unsigned> &FwdRefAttrGrps,
334                                    bool inAttrGrp, LocTy &BuiltinLoc);
335    bool ParseByValWithOptionalType(Type *&Result);
336    bool ParsePreallocated(Type *&Result);
337
338    // Module Summary Index Parsing.
339    bool SkipModuleSummaryEntry();
340    bool ParseSummaryEntry();
341    bool ParseModuleEntry(unsigned ID);
342    bool ParseModuleReference(StringRef &ModulePath);
343    bool ParseGVReference(ValueInfo &VI, unsigned &GVId);
344    bool ParseSummaryIndexFlags();
345    bool ParseBlockCount();
346    bool ParseGVEntry(unsigned ID);
347    bool ParseFunctionSummary(std::string Name, GlobalValue::GUID, unsigned ID);
348    bool ParseVariableSummary(std::string Name, GlobalValue::GUID, unsigned ID);
349    bool ParseAliasSummary(std::string Name, GlobalValue::GUID, unsigned ID);
350    bool ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags);
351    bool ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags);
352    bool ParseOptionalFFlags(FunctionSummary::FFlags &FFlags);
353    bool ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls);
354    bool ParseHotness(CalleeInfo::HotnessType &Hotness);
355    bool ParseOptionalTypeIdInfo(FunctionSummary::TypeIdInfo &TypeIdInfo);
356    bool ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests);
357    bool ParseVFuncIdList(lltok::Kind Kind,
358                          std::vector<FunctionSummary::VFuncId> &VFuncIdList);
359    bool ParseConstVCallList(
360        lltok::Kind Kind,
361        std::vector<FunctionSummary::ConstVCall> &ConstVCallList);
362    using IdToIndexMapType =
363        std::map<unsigned, std::vector<std::pair<unsigned, LocTy>>>;
364    bool ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
365                         IdToIndexMapType &IdToIndexMap, unsigned Index);
366    bool ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
367                      IdToIndexMapType &IdToIndexMap, unsigned Index);
368    bool ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs);
369    bool ParseOptionalParamAccesses(
370        std::vector<FunctionSummary::ParamAccess> &Params);
371    bool ParseParamNo(uint64_t &ParamNo);
372    bool ParseParamAccess(FunctionSummary::ParamAccess &Param);
373    bool ParseParamAccessCall(FunctionSummary::ParamAccess::Call &Call);
374    bool ParseParamAccessOffset(ConstantRange &range);
375    bool ParseOptionalRefs(std::vector<ValueInfo> &Refs);
376    bool ParseTypeIdEntry(unsigned ID);
377    bool ParseTypeIdSummary(TypeIdSummary &TIS);
378    bool ParseTypeIdCompatibleVtableEntry(unsigned ID);
379    bool ParseTypeTestResolution(TypeTestResolution &TTRes);
380    bool ParseOptionalWpdResolutions(
381        std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap);
382    bool ParseWpdRes(WholeProgramDevirtResolution &WPDRes);
383    bool ParseOptionalResByArg(
384        std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
385            &ResByArg);
386    bool ParseArgs(std::vector<uint64_t> &Args);
387    void AddGlobalValueToIndex(std::string Name, GlobalValue::GUID,
388                               GlobalValue::LinkageTypes Linkage, unsigned ID,
389                               std::unique_ptr<GlobalValueSummary> Summary);
390
391    // Type Parsing.
392    bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
393    bool ParseType(Type *&Result, bool AllowVoid = false) {
394      return ParseType(Result, "expected type", AllowVoid);
395    }
396    bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
397                   bool AllowVoid = false) {
398      Loc = Lex.getLoc();
399      return ParseType(Result, Msg, AllowVoid);
400    }
401    bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
402      Loc = Lex.getLoc();
403      return ParseType(Result, AllowVoid);
404    }
405    bool ParseAnonStructType(Type *&Result, bool Packed);
406    bool ParseStructBody(SmallVectorImpl<Type*> &Body);
407    bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
408                               std::pair<Type*, LocTy> &Entry,
409                               Type *&ResultTy);
410
411    bool ParseArrayVectorType(Type *&Result, bool isVector);
412    bool ParseFunctionType(Type *&Result);
413
414    // Function Semantic Analysis.
415    class PerFunctionState {
416      LLParser &P;
417      Function &F;
418      std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
419      std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
420      std::vector<Value*> NumberedVals;
421
422      /// FunctionNumber - If this is an unnamed function, this is the slot
423      /// number of it, otherwise it is -1.
424      int FunctionNumber;
425    public:
426      PerFunctionState(LLParser &p, Function &f, int functionNumber);
427      ~PerFunctionState();
428
429      Function &getFunction() const { return F; }
430
431      bool FinishFunction();
432
433      /// GetVal - Get a value with the specified name or ID, creating a
434      /// forward reference record if needed.  This can return null if the value
435      /// exists but does not have the right type.
436      Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc, bool IsCall);
437      Value *GetVal(unsigned ID, Type *Ty, LocTy Loc, bool IsCall);
438
439      /// SetInstName - After an instruction is parsed and inserted into its
440      /// basic block, this installs its name.
441      bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
442                       Instruction *Inst);
443
444      /// GetBB - Get a basic block with the specified name or ID, creating a
445      /// forward reference record if needed.  This can return null if the value
446      /// is not a BasicBlock.
447      BasicBlock *GetBB(const std::string &Name, LocTy Loc);
448      BasicBlock *GetBB(unsigned ID, LocTy Loc);
449
450      /// DefineBB - Define the specified basic block, which is either named or
451      /// unnamed.  If there is an error, this returns null otherwise it returns
452      /// the block being defined.
453      BasicBlock *DefineBB(const std::string &Name, int NameID, LocTy Loc);
454
455      bool resolveForwardRefBlockAddresses();
456    };
457
458    bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
459                             PerFunctionState *PFS, bool IsCall);
460
461    Value *checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
462                                  Value *Val, bool IsCall);
463
464    bool parseConstantValue(Type *Ty, Constant *&C);
465    bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
466    bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
467      return ParseValue(Ty, V, &PFS);
468    }
469
470    bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
471                    PerFunctionState &PFS) {
472      Loc = Lex.getLoc();
473      return ParseValue(Ty, V, &PFS);
474    }
475
476    bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
477    bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
478      return ParseTypeAndValue(V, &PFS);
479    }
480    bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
481      Loc = Lex.getLoc();
482      return ParseTypeAndValue(V, PFS);
483    }
484    bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
485                                PerFunctionState &PFS);
486    bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
487      LocTy Loc;
488      return ParseTypeAndBasicBlock(BB, Loc, PFS);
489    }
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,
501                            bool IsMustTailCall = false,
502                            bool InVarArgsFunc = false);
503
504    bool
505    ParseOptionalOperandBundles(SmallVectorImpl<OperandBundleDef> &BundleList,
506                                PerFunctionState &PFS);
507
508    bool ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
509                            PerFunctionState &PFS);
510
511    // Constant Parsing.
512    bool ParseValID(ValID &ID, PerFunctionState *PFS = 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 ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
519    bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
520                              PerFunctionState *PFS);
521    bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
522    bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
523    bool ParseMDNode(MDNode *&N);
524    bool ParseMDNodeTail(MDNode *&N);
525    bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
526    bool ParseMetadataAttachment(unsigned &Kind, MDNode *&MD);
527    bool ParseInstructionMetadata(Instruction &Inst);
528    bool ParseGlobalObjectMetadataAttachment(GlobalObject &GO);
529    bool ParseOptionalFunctionMetadata(Function &F);
530
531    template <class FieldTy>
532    bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
533    template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
534    template <class ParserTy>
535    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
544    // Function Parsing.
545    struct ArgInfo {
546      LocTy Loc;
547      Type *Ty;
548      AttributeSet Attrs;
549      std::string Name;
550      ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
551          : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
552    };
553    bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
554    bool ParseFunctionHeader(Function *&Fn, bool isDefine);
555    bool ParseFunctionBody(Function &Fn);
556    bool ParseBasicBlock(PerFunctionState &PFS);
557
558    enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
559
560    // Instruction Parsing.  Each instruction parsing routine can return with a
561    // normal result, an error result, or return having eaten an extra comma.
562    enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
563    int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
564                         PerFunctionState &PFS);
565    bool ParseCmpPredicate(unsigned &P, unsigned Opc);
566
567    bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
568    bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
569    bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
570    bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
571    bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
572    bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
573    bool ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS);
574    bool ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS);
575    bool ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS);
576    bool ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS);
577    bool ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS);
578    bool ParseCallBr(Instruction *&Inst, PerFunctionState &PFS);
579
580    bool ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
581                      bool IsFP);
582    bool ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc,
583                         bool IsFP);
584    bool ParseLogical(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
585    bool ParseCompare(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
586    bool ParseCast(Instruction *&Inst, PerFunctionState &PFS, unsigned Opc);
587    bool ParseSelect(Instruction *&Inst, PerFunctionState &PFS);
588    bool ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS);
589    bool ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS);
590    bool ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS);
591    bool ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS);
592    int ParsePHI(Instruction *&Inst, PerFunctionState &PFS);
593    bool ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS);
594    bool ParseCall(Instruction *&Inst, PerFunctionState &PFS,
595                   CallInst::TailCallKind TCK);
596    int ParseAlloc(Instruction *&Inst, PerFunctionState &PFS);
597    int ParseLoad(Instruction *&Inst, PerFunctionState &PFS);
598    int ParseStore(Instruction *&Inst, PerFunctionState &PFS);
599    int ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS);
600    int ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS);
601    int ParseFence(Instruction *&Inst, PerFunctionState &PFS);
602    int ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS);
603    int ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS);
604    int ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS);
605    bool ParseFreeze(Instruction *&I, PerFunctionState &PFS);
606
607    // Use-list order directives.
608    bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
609    bool ParseUseListOrderBB();
610    bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
611    bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
612  };
613} // End llvm namespace
614
615#endif
616