Use ParseFnAttributeValuePairs instead of ParseOptionalFuncAttrs
[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_ASMPARSER_LLPARSER_H
15 #define LLVM_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/Support/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 MDString;
38   class MDNode;
39   class StructType;
40
41   /// ValID - Represents a reference of a definition of some sort with no type.
42   /// There are several cases where we have to parse the value but where the
43   /// type can depend on later context.  This may either be a numeric reference
44   /// or a symbolic (%var) reference.  This is just a discriminated union.
45   struct ValID {
46     enum {
47       t_LocalID, t_GlobalID,      // ID in UIntVal.
48       t_LocalName, t_GlobalName,  // Name in StrVal.
49       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
50       t_Null, t_Undef, t_Zero,    // No value.
51       t_EmptyArray,               // No value:  []
52       t_Constant,                 // Value in ConstantVal.
53       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
54       t_MDNode,                   // Value in MDNodeVal.
55       t_MDString,                 // Value in MDStringVal.
56       t_ConstantStruct,           // Value in ConstantStructElts.
57       t_PackedConstantStruct      // Value in ConstantStructElts.
58     } Kind;
59
60     LLLexer::LocTy Loc;
61     unsigned UIntVal;
62     std::string StrVal, StrVal2;
63     APSInt APSIntVal;
64     APFloat APFloatVal;
65     Constant *ConstantVal;
66     MDNode *MDNodeVal;
67     MDString *MDStringVal;
68     Constant **ConstantStructElts;
69
70     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
71     ~ValID() {
72       if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
73         delete [] ConstantStructElts;
74     }
75
76     bool operator<(const ValID &RHS) const {
77       if (Kind == t_LocalID || Kind == t_GlobalID)
78         return UIntVal < RHS.UIntVal;
79       assert((Kind == t_LocalName || Kind == t_GlobalName ||
80               Kind == t_ConstantStruct || Kind == t_PackedConstantStruct) &&
81              "Ordering not defined for this ValID kind yet");
82       return StrVal < RHS.StrVal;
83     }
84   };
85
86   class LLParser {
87   public:
88     typedef LLLexer::LocTy LocTy;
89   private:
90     LLVMContext &Context;
91     LLLexer Lex;
92     Module *M;
93
94     // Instruction metadata resolution.  Each instruction can have a list of
95     // MDRef info associated with them.
96     //
97     // The simpler approach of just creating temporary MDNodes and then calling
98     // RAUW on them when the definition is processed doesn't work because some
99     // instruction metadata kinds, such as dbg, get stored in the IR in an
100     // "optimized" format which doesn't participate in the normal value use
101     // lists. This means that RAUW doesn't work, even on temporary MDNodes
102     // which otherwise support RAUW. Instead, we defer resolving MDNode
103     // references until the definitions have been processed.
104     struct MDRef {
105       SMLoc Loc;
106       unsigned MDKind, MDSlot;
107     };
108     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
109
110     // Type resolution handling data structures.  The location is set when we
111     // have processed a use of the type but not a definition yet.
112     StringMap<std::pair<Type*, LocTy> > NamedTypes;
113     std::vector<std::pair<Type*, LocTy> > NumberedTypes;
114
115     std::vector<TrackingVH<MDNode> > NumberedMetadata;
116     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
117
118     // Global Value reference information.
119     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
120     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
121     std::vector<GlobalValue*> NumberedVals;
122
123     // References to blockaddress.  The key is the function ValID, the value is
124     // a list of references to blocks in that function.
125     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
126       ForwardRefBlockAddresses;
127
128     // Attribute builder reference information.
129     std::map<unsigned, AttrBuilder> ForwardRefAttrBuilder;
130
131   public:
132     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) :
133       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
134       M(m) {}
135     bool Run();
136
137     LLVMContext &getContext() { return Context; }
138
139   private:
140
141     bool Error(LocTy L, const Twine &Msg) const {
142       return Lex.Error(L, Msg);
143     }
144     bool TokError(const Twine &Msg) const {
145       return Error(Lex.getLoc(), Msg);
146     }
147
148     /// GetGlobalVal - Get a value with the specified name or ID, creating a
149     /// forward reference record if needed.  This can return null if the value
150     /// exists but does not have the right type.
151     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
152     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
153
154     // Helper Routines.
155     bool ParseToken(lltok::Kind T, const char *ErrMsg);
156     bool EatIfPresent(lltok::Kind T) {
157       if (Lex.getKind() != T) return false;
158       Lex.Lex();
159       return true;
160     }
161
162     FastMathFlags EatFastMathFlagsIfPresent() {
163       FastMathFlags FMF;
164       while (true)
165         switch (Lex.getKind()) {
166         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
167         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
168         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
169         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
170         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
171         default: return FMF;
172         }
173       return FMF;
174     }
175
176     bool ParseOptionalToken(lltok::Kind T, bool &Present, LocTy *Loc = 0) {
177       if (Lex.getKind() != T) {
178         Present = false;
179       } else {
180         if (Loc)
181           *Loc = Lex.getLoc();
182         Lex.Lex();
183         Present = true;
184       }
185       return false;
186     }
187     bool ParseStringConstant(std::string &Result);
188     bool ParseUInt32(unsigned &Val);
189     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
190       Loc = Lex.getLoc();
191       return ParseUInt32(Val);
192     }
193
194     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
195     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
196     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
197     bool ParseOptionalParamAttrs(AttrBuilder &B);
198     bool ParseOptionalReturnAttrs(AttrBuilder &B);
199     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
200     bool ParseOptionalLinkage(unsigned &Linkage) {
201       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
202     }
203     bool ParseOptionalVisibility(unsigned &Visibility);
204     bool ParseOptionalCallingConv(CallingConv::ID &CC);
205     bool ParseOptionalAlignment(unsigned &Alignment);
206     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
207                                AtomicOrdering &Ordering);
208     bool ParseOptionalStackAlignment(unsigned &Alignment);
209     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
210     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
211     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
212       bool AteExtraComma;
213       if (ParseIndexList(Indices, AteExtraComma)) return true;
214       if (AteExtraComma)
215         return TokError("expected index");
216       return false;
217     }
218
219     // Top-Level Entities
220     bool ParseTopLevelEntities();
221     bool ValidateEndOfModule();
222     bool ParseTargetDefinition();
223     bool ParseModuleAsm();
224     bool ParseDepLibs();        // FIXME: Remove in 4.0.
225     bool ParseUnnamedType();
226     bool ParseNamedType();
227     bool ParseDeclare();
228     bool ParseDefine();
229
230     bool ParseGlobalType(bool &IsConstant);
231     bool ParseUnnamedGlobal();
232     bool ParseNamedGlobal();
233     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
234                      bool HasLinkage, unsigned Visibility);
235     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility);
236     bool ParseStandaloneMetadata();
237     bool ParseNamedMetadata();
238     bool ParseMDString(MDString *&Result);
239     bool ParseMDNodeID(MDNode *&Result);
240     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
241     bool ParseUnnamedAttrGrp();
242     bool ParseFnAttributeValuePairs(AttrBuilder &B, bool inAttrGrp);
243
244     // Type Parsing.
245     bool ParseType(Type *&Result, bool AllowVoid = false);
246     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
247       Loc = Lex.getLoc();
248       return ParseType(Result, AllowVoid);
249     }
250     bool ParseAnonStructType(Type *&Result, bool Packed);
251     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
252     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
253                                std::pair<Type*, LocTy> &Entry,
254                                Type *&ResultTy);
255
256     bool ParseArrayVectorType(Type *&Result, bool isVector);
257     bool ParseFunctionType(Type *&Result);
258
259     // Function Semantic Analysis.
260     class PerFunctionState {
261       LLParser &P;
262       Function &F;
263       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
264       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
265       std::vector<Value*> NumberedVals;
266
267       /// FunctionNumber - If this is an unnamed function, this is the slot
268       /// number of it, otherwise it is -1.
269       int FunctionNumber;
270     public:
271       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
272       ~PerFunctionState();
273
274       Function &getFunction() const { return F; }
275
276       bool FinishFunction();
277
278       /// GetVal - Get a value with the specified name or ID, creating a
279       /// forward reference record if needed.  This can return null if the value
280       /// exists but does not have the right type.
281       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
282       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
283
284       /// SetInstName - After an instruction is parsed and inserted into its
285       /// basic block, this installs its name.
286       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
287                        Instruction *Inst);
288
289       /// GetBB - Get a basic block with the specified name or ID, creating a
290       /// forward reference record if needed.  This can return null if the value
291       /// is not a BasicBlock.
292       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
293       BasicBlock *GetBB(unsigned ID, LocTy Loc);
294
295       /// DefineBB - Define the specified basic block, which is either named or
296       /// unnamed.  If there is an error, this returns null otherwise it returns
297       /// the block being defined.
298       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
299     };
300
301     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
302                              PerFunctionState *PFS);
303
304     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
305     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
306       return ParseValue(Ty, V, &PFS);
307     }
308     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
309                     PerFunctionState &PFS) {
310       Loc = Lex.getLoc();
311       return ParseValue(Ty, V, &PFS);
312     }
313
314     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
315     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
316       return ParseTypeAndValue(V, &PFS);
317     }
318     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
319       Loc = Lex.getLoc();
320       return ParseTypeAndValue(V, PFS);
321     }
322     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
323                                 PerFunctionState &PFS);
324     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
325       LocTy Loc;
326       return ParseTypeAndBasicBlock(BB, Loc, PFS);
327     }
328
329
330     struct ParamInfo {
331       LocTy Loc;
332       Value *V;
333       AttributeSet Attrs;
334       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
335         : Loc(loc), V(v), Attrs(attrs) {}
336     };
337     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
338                             PerFunctionState &PFS);
339
340     // Constant Parsing.
341     bool ParseValID(ValID &ID, PerFunctionState *PFS = NULL);
342     bool ParseGlobalValue(Type *Ty, Constant *&V);
343     bool ParseGlobalTypeAndValue(Constant *&V);
344     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
345     bool ParseMetadataListValue(ValID &ID, PerFunctionState *PFS);
346     bool ParseMetadataValue(ValID &ID, PerFunctionState *PFS);
347     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
348     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
349
350     // Function Parsing.
351     struct ArgInfo {
352       LocTy Loc;
353       Type *Ty;
354       AttributeSet Attrs;
355       std::string Name;
356       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
357         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
358     };
359     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
360     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
361     bool ParseFunctionBody(Function &Fn);
362     bool ParseBasicBlock(PerFunctionState &PFS);
363
364     // Instruction Parsing.  Each instruction parsing routine can return with a
365     // normal result, an error result, or return having eaten an extra comma.
366     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
367     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
368                          PerFunctionState &PFS);
369     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
370
371     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
372     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
373     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
374     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
375     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
376     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
377
378     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
379                          unsigned OperandType);
380     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
381     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
382     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
383     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
384     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
385     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
386     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
387     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
388     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
389     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
390     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
391     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
392     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
393     int ParseStore(Instruction *&I, PerFunctionState &PFS);
394     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
395     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
396     int ParseFence(Instruction *&I, PerFunctionState &PFS);
397     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
398     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
399     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
400
401     bool ResolveForwardRefBlockAddresses(Function *TheFn,
402                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
403                                          PerFunctionState *PFS);
404   };
405 } // End llvm namespace
406
407 #endif