IR: Implement uselistorder assembly directives
[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_MDNode,                   // Value in MDNodeVal.
56       t_MDString,                 // Value in MDStringVal.
57       t_ConstantStruct,           // Value in ConstantStructElts.
58       t_PackedConstantStruct      // Value in ConstantStructElts.
59     } Kind;
60
61     LLLexer::LocTy Loc;
62     unsigned UIntVal;
63     std::string StrVal, StrVal2;
64     APSInt APSIntVal;
65     APFloat APFloatVal;
66     Constant *ConstantVal;
67     MDNode *MDNodeVal;
68     MDString *MDStringVal;
69     Constant **ConstantStructElts;
70
71     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
72     ~ValID() {
73       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
74         delete [] ConstantStructElts;
75     }
76
77     bool operator<(const ValID &RHS) const {
78       if (Kind == t_LocalID || Kind == t_GlobalID)
79         return UIntVal < RHS.UIntVal;
80       assert((Kind == t_LocalName || Kind == t_GlobalName ||
81               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
82              "Ordering not defined for this ValID kind yet");
83       return StrVal < RHS.StrVal;
84     }
85   };
86
87   class LLParser {
88   public:
89     typedef LLLexer::LocTy LocTy;
90   private:
91     LLVMContext &Context;
92     LLLexer Lex;
93     Module *M;
94
95     // Instruction metadata resolution.  Each instruction can have a list of
96     // MDRef info associated with them.
97     //
98     // The simpler approach of just creating temporary MDNodes and then calling
99     // RAUW on them when the definition is processed doesn't work because some
100     // instruction metadata kinds, such as dbg, get stored in the IR in an
101     // "optimized" format which doesn't participate in the normal value use
102     // lists. This means that RAUW doesn't work, even on temporary MDNodes
103     // which otherwise support RAUW. Instead, we defer resolving MDNode
104     // references until the definitions have been processed.
105     struct MDRef {
106       SMLoc Loc;
107       unsigned MDKind, MDSlot;
108     };
109     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
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::vector<std::pair<Type*, LocTy> > NumberedTypes;
117
118     std::vector<TrackingVH<MDNode> > NumberedMetadata;
119     std::map<unsigned, std::pair<TrackingVH<MDNode>, 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   public:
143     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
144         : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
145           BlockAddressPFS(nullptr) {}
146     bool Run();
147
148     LLVMContext &getContext() { return Context; }
149
150   private:
151
152     bool Error(LocTy L, const Twine &Msg) const {
153       return Lex.Error(L, Msg);
154     }
155     bool TokError(const Twine &Msg) const {
156       return Error(Lex.getLoc(), Msg);
157     }
158
159     /// GetGlobalVal - Get a value with the specified name or ID, creating a
160     /// forward reference record if needed.  This can return null if the value
161     /// exists but does not have the right type.
162     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
163     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
164
165     /// Get a Comdat with the specified name, creating a forward reference
166     /// record if needed.
167     Comdat *getComdat(const std::string &N, LocTy Loc);
168
169     // Helper Routines.
170     bool ParseToken(lltok::Kind T, const char *ErrMsg);
171     bool EatIfPresent(lltok::Kind T) {
172       if (Lex.getKind() != T) return false;
173       Lex.Lex();
174       return true;
175     }
176
177     FastMathFlags EatFastMathFlagsIfPresent() {
178       FastMathFlags FMF;
179       while (true)
180         switch (Lex.getKind()) {
181         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
182         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
183         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
184         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
185         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
186         default: return FMF;
187         }
188       return FMF;
189     }
190
191     bool ParseOptionalToken(lltok::Kind T, bool &Present,
192                             LocTy *Loc = nullptr) {
193       if (Lex.getKind() != T) {
194         Present = false;
195       } else {
196         if (Loc)
197           *Loc = Lex.getLoc();
198         Lex.Lex();
199         Present = true;
200       }
201       return false;
202     }
203     bool ParseStringConstant(std::string &Result);
204     bool ParseUInt32(unsigned &Val);
205     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
206       Loc = Lex.getLoc();
207       return ParseUInt32(Val);
208     }
209     bool ParseUInt64(uint64_t &Val);
210     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
211       Loc = Lex.getLoc();
212       return ParseUInt64(Val);
213     }
214
215     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
216     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
217     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
218       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
219     }
220     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
221     bool ParseOptionalParamAttrs(AttrBuilder &B);
222     bool ParseOptionalReturnAttrs(AttrBuilder &B);
223     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
224     bool ParseOptionalLinkage(unsigned &Linkage) {
225       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
226     }
227     bool ParseOptionalVisibility(unsigned &Visibility);
228     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
229     bool ParseOptionalCallingConv(CallingConv::ID &CC);
230     bool ParseOptionalAlignment(unsigned &Alignment);
231     bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
232     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
233                                AtomicOrdering &Ordering);
234     bool ParseOrdering(AtomicOrdering &Ordering);
235     bool ParseOptionalStackAlignment(unsigned &Alignment);
236     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
237     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
238     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
239     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
240       bool AteExtraComma;
241       if (ParseIndexList(Indices, AteExtraComma)) return true;
242       if (AteExtraComma)
243         return TokError("expected index");
244       return false;
245     }
246
247     // Top-Level Entities
248     bool ParseTopLevelEntities();
249     bool ValidateEndOfModule();
250     bool ParseTargetDefinition();
251     bool ParseModuleAsm();
252     bool ParseDepLibs();        // FIXME: Remove in 4.0.
253     bool ParseUnnamedType();
254     bool ParseNamedType();
255     bool ParseDeclare();
256     bool ParseDefine();
257
258     bool ParseGlobalType(bool &IsConstant);
259     bool ParseUnnamedGlobal();
260     bool ParseNamedGlobal();
261     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
262                      bool HasLinkage, unsigned Visibility,
263                      unsigned DLLStorageClass,
264                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
265     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
266                     unsigned Visibility, unsigned DLLStorageClass,
267                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
268     bool parseComdat();
269     bool ParseStandaloneMetadata();
270     bool ParseNamedMetadata();
271     bool ParseMDString(MDString *&Result);
272     bool ParseMDNodeID(MDNode *&Result);
273     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
274     bool ParseUnnamedAttrGrp();
275     bool ParseFnAttributeValuePairs(AttrBuilder &B,
276                                     std::vector<unsigned> &FwdRefAttrGrps,
277                                     bool inAttrGrp, LocTy &BuiltinLoc);
278
279     // Type Parsing.
280     bool ParseType(Type *&Result, bool AllowVoid = false);
281     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
282       Loc = Lex.getLoc();
283       return ParseType(Result, AllowVoid);
284     }
285     bool ParseAnonStructType(Type *&Result, bool Packed);
286     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
287     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
288                                std::pair<Type*, LocTy> &Entry,
289                                Type *&ResultTy);
290
291     bool ParseArrayVectorType(Type *&Result, bool isVector);
292     bool ParseFunctionType(Type *&Result);
293
294     // Function Semantic Analysis.
295     class PerFunctionState {
296       LLParser &P;
297       Function &F;
298       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
299       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
300       std::vector<Value*> NumberedVals;
301
302       /// FunctionNumber - If this is an unnamed function, this is the slot
303       /// number of it, otherwise it is -1.
304       int FunctionNumber;
305     public:
306       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
307       ~PerFunctionState();
308
309       Function &getFunction() const { return F; }
310
311       bool FinishFunction();
312
313       /// GetVal - Get a value with the specified name or ID, creating a
314       /// forward reference record if needed.  This can return null if the value
315       /// exists but does not have the right type.
316       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
317       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
318
319       /// SetInstName - After an instruction is parsed and inserted into its
320       /// basic block, this installs its name.
321       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
322                        Instruction *Inst);
323
324       /// GetBB - Get a basic block with the specified name or ID, creating a
325       /// forward reference record if needed.  This can return null if the value
326       /// is not a BasicBlock.
327       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
328       BasicBlock *GetBB(unsigned ID, LocTy Loc);
329
330       /// DefineBB - Define the specified basic block, which is either named or
331       /// unnamed.  If there is an error, this returns null otherwise it returns
332       /// the block being defined.
333       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
334
335       bool resolveForwardRefBlockAddresses();
336     };
337
338     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
339                              PerFunctionState *PFS);
340
341     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
342     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
343       return ParseValue(Ty, V, &PFS);
344     }
345     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
346                     PerFunctionState &PFS) {
347       Loc = Lex.getLoc();
348       return ParseValue(Ty, V, &PFS);
349     }
350
351     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
352     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
353       return ParseTypeAndValue(V, &PFS);
354     }
355     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
356       Loc = Lex.getLoc();
357       return ParseTypeAndValue(V, PFS);
358     }
359     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
360                                 PerFunctionState &PFS);
361     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
362       LocTy Loc;
363       return ParseTypeAndBasicBlock(BB, Loc, PFS);
364     }
365
366
367     struct ParamInfo {
368       LocTy Loc;
369       Value *V;
370       AttributeSet Attrs;
371       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
372         : Loc(loc), V(v), Attrs(attrs) {}
373     };
374     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
375                             PerFunctionState &PFS);
376
377     // Constant Parsing.
378     bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
379     bool ParseGlobalValue(Type *Ty, Constant *&V);
380     bool ParseGlobalTypeAndValue(Constant *&V);
381     bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
382     bool parseOptionalComdat(Comdat *&C);
383     bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
384     bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
385     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
386     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
387
388     // Function Parsing.
389     struct ArgInfo {
390       LocTy Loc;
391       Type *Ty;
392       AttributeSet Attrs;
393       std::string Name;
394       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
395         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
396     };
397     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
398     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
399     bool ParseFunctionBody(Function &Fn);
400     bool ParseBasicBlock(PerFunctionState &PFS);
401
402     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
403
404     // Instruction Parsing.  Each instruction parsing routine can return with a
405     // normal result, an error result, or return having eaten an extra comma.
406     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
407     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
408                          PerFunctionState &PFS);
409     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
410
411     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
412     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
413     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
414     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
415     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
416     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
417
418     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
419                          unsigned OperandType);
420     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
421     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
422     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
423     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
424     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
425     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
426     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
427     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
428     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
429     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
430     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
431                    CallInst::TailCallKind IsTail);
432     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
433     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
434     int ParseStore(Instruction *&I, PerFunctionState &PFS);
435     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
436     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
437     int ParseFence(Instruction *&I, PerFunctionState &PFS);
438     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
439     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
440     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
441
442     // Use-list order directives.
443     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
444     bool ParseUseListOrderBB();
445     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
446     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
447   };
448 } // End llvm namespace
449
450 #endif