c9aafd997404ac10093e69430b95b43730d13b01
[oota-llvm.git] / lib / AsmParser / LLParser.h
1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
15 #define LLVM_LIB_ASMPARSER_LLPARSER_H
16
17 #include "LLLexer.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/Type.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include <map>
27
28 namespace llvm {
29   class Module;
30   class OpaqueType;
31   class Function;
32   class Value;
33   class BasicBlock;
34   class Instruction;
35   class Constant;
36   class GlobalValue;
37   class Comdat;
38   class MDString;
39   class MDNode;
40   class StructType;
41
42   /// ValID - Represents a reference of a definition of some sort with no type.
43   /// There are several cases where we have to parse the value but where the
44   /// type can depend on later context.  This may either be a numeric reference
45   /// or a symbolic (%var) reference.  This is just a discriminated union.
46   struct ValID {
47     enum {
48       t_LocalID, t_GlobalID,      // ID in UIntVal.
49       t_LocalName, t_GlobalName,  // Name in StrVal.
50       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
51       t_Null, t_Undef, t_Zero,    // No value.
52       t_EmptyArray,               // No value:  []
53       t_Constant,                 // Value in ConstantVal.
54       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
55       t_ConstantStruct,           // Value in ConstantStructElts.
56       t_PackedConstantStruct      // Value in ConstantStructElts.
57     } Kind;
58
59     LLLexer::LocTy Loc;
60     unsigned UIntVal;
61     std::string StrVal, StrVal2;
62     APSInt APSIntVal;
63     APFloat APFloatVal;
64     Constant *ConstantVal;
65     Constant **ConstantStructElts;
66
67     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
68     ~ValID() {
69       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
70         delete [] ConstantStructElts;
71     }
72
73     bool operator<(const ValID &RHS) const {
74       if (Kind == t_LocalID || Kind == t_GlobalID)
75         return UIntVal < RHS.UIntVal;
76       assert((Kind == t_LocalName || Kind == t_GlobalName ||
77               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
78              "Ordering not defined for this ValID kind yet");
79       return StrVal < RHS.StrVal;
80     }
81   };
82
83   /// Structure to represent an optional metadata field.
84   template <class FieldTy> struct MDFieldImpl {
85     typedef MDFieldImpl ImplTy;
86     FieldTy Val;
87     bool Seen;
88
89     void assign(FieldTy Val) {
90       Seen = true;
91       this->Val = std::move(Val);
92     }
93
94     explicit MDFieldImpl(FieldTy Default)
95         : Val(std::move(Default)), Seen(false) {}
96   };
97   struct MDUnsignedField : public MDFieldImpl<uint64_t> {
98     uint64_t Max;
99
100     MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
101         : ImplTy(Default), Max(Max) {}
102   };
103   struct DwarfTagField : public MDUnsignedField {
104     DwarfTagField() : MDUnsignedField(0, ~0u >> 16) {}
105   };
106   struct MDField : public MDFieldImpl<Metadata *> {
107     MDField() : ImplTy(nullptr) {}
108   };
109   struct MDStringField : public MDFieldImpl<std::string> {
110     MDStringField() : ImplTy(std::string()) {}
111   };
112   struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
113     MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
114   };
115
116   class LLParser {
117   public:
118     typedef LLLexer::LocTy LocTy;
119   private:
120     LLVMContext &Context;
121     LLLexer Lex;
122     Module *M;
123
124     // Instruction metadata resolution.  Each instruction can have a list of
125     // MDRef info associated with them.
126     //
127     // The simpler approach of just creating temporary MDNodes and then calling
128     // RAUW on them when the definition is processed doesn't work because some
129     // instruction metadata kinds, such as dbg, get stored in the IR in an
130     // "optimized" format which doesn't participate in the normal value use
131     // lists. This means that RAUW doesn't work, even on temporary MDNodes
132     // which otherwise support RAUW. Instead, we defer resolving MDNode
133     // references until the definitions have been processed.
134     struct MDRef {
135       SMLoc Loc;
136       unsigned MDKind, MDSlot;
137     };
138
139     SmallVector<Instruction*, 64> InstsWithTBAATag;
140
141     // Type resolution handling data structures.  The location is set when we
142     // have processed a use of the type but not a definition yet.
143     StringMap<std::pair<Type*, LocTy> > NamedTypes;
144     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
145
146     std::vector<TrackingMDNodeRef> NumberedMetadata;
147     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
148
149     // Global Value reference information.
150     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
151     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
152     std::vector<GlobalValue*> NumberedVals;
153
154     // Comdat forward reference information.
155     std::map<std::string, LocTy> ForwardRefComdats;
156
157     // References to blockaddress.  The key is the function ValID, the value is
158     // a list of references to blocks in that function.
159     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
160     class PerFunctionState;
161     /// Reference to per-function state to allow basic blocks to be
162     /// forward-referenced by blockaddress instructions within the same
163     /// function.
164     PerFunctionState *BlockAddressPFS;
165
166     // Attribute builder reference information.
167     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
168     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
169
170   public:
171     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
172         : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
173           BlockAddressPFS(nullptr) {}
174     bool Run();
175
176     LLVMContext &getContext() { return Context; }
177
178   private:
179
180     bool Error(LocTy L, const Twine &Msg) const {
181       return Lex.Error(L, Msg);
182     }
183     bool TokError(const Twine &Msg) const {
184       return Error(Lex.getLoc(), Msg);
185     }
186
187     /// GetGlobalVal - Get a value with the specified name or ID, creating a
188     /// forward reference record if needed.  This can return null if the value
189     /// exists but does not have the right type.
190     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
191     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
192
193     /// Get a Comdat with the specified name, creating a forward reference
194     /// record if needed.
195     Comdat *getComdat(const std::string &N, LocTy Loc);
196
197     // Helper Routines.
198     bool ParseToken(lltok::Kind T, const char *ErrMsg);
199     bool EatIfPresent(lltok::Kind T) {
200       if (Lex.getKind() != T) return false;
201       Lex.Lex();
202       return true;
203     }
204
205     FastMathFlags EatFastMathFlagsIfPresent() {
206       FastMathFlags FMF;
207       while (true)
208         switch (Lex.getKind()) {
209         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
210         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
211         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
212         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
213         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
214         default: return FMF;
215         }
216       return FMF;
217     }
218
219     bool ParseOptionalToken(lltok::Kind T, bool &Present,
220                             LocTy *Loc = nullptr) {
221       if (Lex.getKind() != T) {
222         Present = false;
223       } else {
224         if (Loc)
225           *Loc = Lex.getLoc();
226         Lex.Lex();
227         Present = true;
228       }
229       return false;
230     }
231     bool ParseStringConstant(std::string &Result);
232     bool ParseUInt32(unsigned &Val);
233     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
234       Loc = Lex.getLoc();
235       return ParseUInt32(Val);
236     }
237     bool ParseUInt64(uint64_t &Val);
238     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
239       Loc = Lex.getLoc();
240       return ParseUInt64(Val);
241     }
242
243     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
244     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
245     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
246       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
247     }
248     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
249     bool ParseOptionalParamAttrs(AttrBuilder &B);
250     bool ParseOptionalReturnAttrs(AttrBuilder &B);
251     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
252     bool ParseOptionalLinkage(unsigned &Linkage) {
253       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
254     }
255     bool ParseOptionalVisibility(unsigned &Visibility);
256     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
257     bool ParseOptionalCallingConv(unsigned &CC);
258     bool ParseOptionalAlignment(unsigned &Alignment);
259     bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
260     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
261                                AtomicOrdering &Ordering);
262     bool ParseOrdering(AtomicOrdering &Ordering);
263     bool ParseOptionalStackAlignment(unsigned &Alignment);
264     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
265     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
266     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
267     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
268       bool AteExtraComma;
269       if (ParseIndexList(Indices, AteExtraComma)) return true;
270       if (AteExtraComma)
271         return TokError("expected index");
272       return false;
273     }
274
275     // Top-Level Entities
276     bool ParseTopLevelEntities();
277     bool ValidateEndOfModule();
278     bool ParseTargetDefinition();
279     bool ParseModuleAsm();
280     bool ParseDepLibs();        // FIXME: Remove in 4.0.
281     bool ParseUnnamedType();
282     bool ParseNamedType();
283     bool ParseDeclare();
284     bool ParseDefine();
285
286     bool ParseGlobalType(bool &IsConstant);
287     bool ParseUnnamedGlobal();
288     bool ParseNamedGlobal();
289     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
290                      bool HasLinkage, unsigned Visibility,
291                      unsigned DLLStorageClass,
292                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
293     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
294                     unsigned Visibility, unsigned DLLStorageClass,
295                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
296     bool parseComdat();
297     bool ParseStandaloneMetadata();
298     bool ParseNamedMetadata();
299     bool ParseMDString(MDString *&Result);
300     bool ParseMDNodeID(MDNode *&Result);
301     bool ParseUnnamedAttrGrp();
302     bool ParseFnAttributeValuePairs(AttrBuilder &B,
303                                     std::vector<unsigned> &FwdRefAttrGrps,
304                                     bool inAttrGrp, LocTy &BuiltinLoc);
305
306     // Type Parsing.
307     bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
308     bool ParseType(Type *&Result, bool AllowVoid = false) {
309       return ParseType(Result, "expected type", AllowVoid);
310     }
311     bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
312                    bool AllowVoid = false) {
313       Loc = Lex.getLoc();
314       return ParseType(Result, Msg, AllowVoid);
315     }
316     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
317       Loc = Lex.getLoc();
318       return ParseType(Result, AllowVoid);
319     }
320     bool ParseAnonStructType(Type *&Result, bool Packed);
321     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
322     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
323                                std::pair<Type*, LocTy> &Entry,
324                                Type *&ResultTy);
325
326     bool ParseArrayVectorType(Type *&Result, bool isVector);
327     bool ParseFunctionType(Type *&Result);
328
329     // Function Semantic Analysis.
330     class PerFunctionState {
331       LLParser &P;
332       Function &F;
333       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
334       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
335       std::vector<Value*> NumberedVals;
336
337       /// FunctionNumber - If this is an unnamed function, this is the slot
338       /// number of it, otherwise it is -1.
339       int FunctionNumber;
340     public:
341       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
342       ~PerFunctionState();
343
344       Function &getFunction() const { return F; }
345
346       bool FinishFunction();
347
348       /// GetVal - Get a value with the specified name or ID, creating a
349       /// forward reference record if needed.  This can return null if the value
350       /// exists but does not have the right type.
351       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
352       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
353
354       /// SetInstName - After an instruction is parsed and inserted into its
355       /// basic block, this installs its name.
356       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
357                        Instruction *Inst);
358
359       /// GetBB - Get a basic block with the specified name or ID, creating a
360       /// forward reference record if needed.  This can return null if the value
361       /// is not a BasicBlock.
362       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
363       BasicBlock *GetBB(unsigned ID, LocTy Loc);
364
365       /// DefineBB - Define the specified basic block, which is either named or
366       /// unnamed.  If there is an error, this returns null otherwise it returns
367       /// the block being defined.
368       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
369
370       bool resolveForwardRefBlockAddresses();
371     };
372
373     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
374                              PerFunctionState *PFS);
375
376     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
377     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
378       return ParseValue(Ty, V, &PFS);
379     }
380     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
381                     PerFunctionState &PFS) {
382       Loc = Lex.getLoc();
383       return ParseValue(Ty, V, &PFS);
384     }
385
386     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
387     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
388       return ParseTypeAndValue(V, &PFS);
389     }
390     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
391       Loc = Lex.getLoc();
392       return ParseTypeAndValue(V, PFS);
393     }
394     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
395                                 PerFunctionState &PFS);
396     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
397       LocTy Loc;
398       return ParseTypeAndBasicBlock(BB, Loc, PFS);
399     }
400
401
402     struct ParamInfo {
403       LocTy Loc;
404       Value *V;
405       AttributeSet Attrs;
406       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
407         : Loc(loc), V(v), Attrs(attrs) {}
408     };
409     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
410                             PerFunctionState &PFS,
411                             bool IsMustTailCall = false,
412                             bool InVarArgsFunc = false);
413
414     // Constant Parsing.
415     bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
416     bool ParseGlobalValue(Type *Ty, Constant *&V);
417     bool ParseGlobalTypeAndValue(Constant *&V);
418     bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
419     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
420     bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
421     bool ParseValueAsMetadata(Metadata *&MD, PerFunctionState *PFS);
422     bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
423     bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
424     bool ParseMDNode(MDNode *&MD);
425     bool ParseMDNodeTail(MDNode *&MD);
426     bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
427     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
428
429     bool ParseMDField(LocTy Loc, StringRef Name, MDUnsignedField &Result);
430     bool ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result);
431     bool ParseMDField(LocTy Loc, StringRef Name, MDField &Result);
432     bool ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result);
433     bool ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result);
434     template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
435     template <class ParserTy>
436     bool ParseMDFieldsImplBody(ParserTy parseField);
437     template <class ParserTy>
438     bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
439     bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
440     bool ParseMDLocation(MDNode *&Result, bool IsDistinct);
441     bool ParseGenericDebugNode(MDNode *&Result, bool IsDistinct);
442
443     // Function Parsing.
444     struct ArgInfo {
445       LocTy Loc;
446       Type *Ty;
447       AttributeSet Attrs;
448       std::string Name;
449       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
450         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
451     };
452     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
453     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
454     bool ParseFunctionBody(Function &Fn);
455     bool ParseBasicBlock(PerFunctionState &PFS);
456
457     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
458
459     // Instruction Parsing.  Each instruction parsing routine can return with a
460     // normal result, an error result, or return having eaten an extra comma.
461     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
462     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
463                          PerFunctionState &PFS);
464     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
465
466     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
467     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
468     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
469     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
470     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
471     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
472
473     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
474                          unsigned OperandType);
475     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
476     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
477     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
478     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
479     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
480     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
481     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
482     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
483     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
484     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
485     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
486                    CallInst::TailCallKind IsTail);
487     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
488     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
489     int ParseStore(Instruction *&I, PerFunctionState &PFS);
490     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
491     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
492     int ParseFence(Instruction *&I, PerFunctionState &PFS);
493     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
494     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
495     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
496
497     // Use-list order directives.
498     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
499     bool ParseUseListOrderBB();
500     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
501     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
502   };
503 } // End llvm namespace
504
505 #endif