rewrite handling of forward ref'd instruction metadata
[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/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Support/ValueHandle.h"
21 #include <map>
22
23 namespace llvm {
24   class Module;
25   class OpaqueType;
26   class Function;
27   class Value;
28   class BasicBlock;
29   class Instruction;
30   class Constant;
31   class GlobalValue;
32   class MDString;
33   class MDNode;
34   class UnionType;
35
36   /// ValID - Represents a reference of a definition of some sort with no type.
37   /// There are several cases where we have to parse the value but where the
38   /// type can depend on later context.  This may either be a numeric reference
39   /// or a symbolic (%var) reference.  This is just a discriminated union.
40   struct ValID {
41     enum {
42       t_LocalID, t_GlobalID,      // ID in UIntVal.
43       t_LocalName, t_GlobalName,  // Name in StrVal.
44       t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
45       t_Null, t_Undef, t_Zero,    // No value.
46       t_EmptyArray,               // No value:  []
47       t_Constant,                 // Value in ConstantVal.
48       t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
49       t_MDNode,                   // Value in MDNodeVal.
50       t_MDString                  // Value in MDStringVal.
51     } Kind;
52     
53     LLLexer::LocTy Loc;
54     unsigned UIntVal;
55     std::string StrVal, StrVal2;
56     APSInt APSIntVal;
57     APFloat APFloatVal;
58     Constant *ConstantVal;
59     MDNode *MDNodeVal;
60     MDString *MDStringVal;
61     ValID() : APFloatVal(0.0) {}
62     
63     bool operator<(const ValID &RHS) const {
64       if (Kind == t_LocalID || Kind == t_GlobalID)
65         return UIntVal < RHS.UIntVal;
66       assert((Kind == t_LocalName || Kind == t_GlobalName) && 
67              "Ordering not defined for this ValID kind yet");
68       return StrVal < RHS.StrVal;
69     }
70   };
71   
72   class LLParser {
73   public:
74     typedef LLLexer::LocTy LocTy;
75   private:
76     LLVMContext& Context;
77     LLLexer Lex;
78     Module *M;
79     
80     // Instruction metadata resolution.  Each instruction can have a list of
81     // MDRef info associated with them.
82     struct MDRef {
83       SMLoc Loc;
84       unsigned MDKind, MDSlot;
85     };
86     DenseMap<Instruction*, std::vector<MDRef> > ForwardRefInstMetadata;
87
88     // Type resolution handling data structures.
89     std::map<std::string, std::pair<PATypeHolder, LocTy> > ForwardRefTypes;
90     std::map<unsigned, std::pair<PATypeHolder, LocTy> > ForwardRefTypeIDs;
91     std::vector<PATypeHolder> NumberedTypes;
92     std::vector<TrackingVH<MDNode> > NumberedMetadata;
93     std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> > ForwardRefMDNodes;
94     struct UpRefRecord {
95       /// Loc - This is the location of the upref.
96       LocTy Loc;
97
98       /// NestingLevel - The number of nesting levels that need to be popped
99       /// before this type is resolved.
100       unsigned NestingLevel;
101
102       /// LastContainedTy - This is the type at the current binding level for
103       /// the type.  Every time we reduce the nesting level, this gets updated.
104       const Type *LastContainedTy;
105
106       /// UpRefTy - This is the actual opaque type that the upreference is
107       /// represented with.
108       OpaqueType *UpRefTy;
109
110       UpRefRecord(LocTy L, unsigned NL, OpaqueType *URTy)
111         : Loc(L), NestingLevel(NL), LastContainedTy((Type*)URTy),
112           UpRefTy(URTy) {}
113     };
114     std::vector<UpRefRecord> UpRefs;
115
116     // Global Value reference information.
117     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
118     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
119     std::vector<GlobalValue*> NumberedVals;
120     
121     // References to blockaddress.  The key is the function ValID, the value is
122     // a list of references to blocks in that function.
123     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >
124       ForwardRefBlockAddresses;
125     
126     Function *MallocF;
127   public:
128     LLParser(MemoryBuffer *F, SourceMgr &SM, SMDiagnostic &Err, Module *m) : 
129       Context(m->getContext()), Lex(F, SM, Err, m->getContext()),
130       M(m), MallocF(NULL) {}
131     bool Run();
132
133     LLVMContext& getContext() { return Context; }
134
135   private:
136
137     bool Error(LocTy L, const std::string &Msg) const {
138       return Lex.Error(L, Msg);
139     }
140     bool TokError(const std::string &Msg) const {
141       return Error(Lex.getLoc(), Msg);
142     }
143
144     /// GetGlobalVal - Get a value with the specified name or ID, creating a
145     /// forward reference record if needed.  This can return null if the value
146     /// exists but does not have the right type.
147     GlobalValue *GetGlobalVal(const std::string &N, const Type *Ty, LocTy Loc);
148     GlobalValue *GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc);
149
150     // Helper Routines.
151     bool ParseToken(lltok::Kind T, const char *ErrMsg);
152     bool EatIfPresent(lltok::Kind T) {
153       if (Lex.getKind() != T) return false;
154       Lex.Lex();
155       return true;
156     }
157     bool ParseOptionalToken(lltok::Kind T, bool &Present) {
158       if (Lex.getKind() != T) {
159         Present = false;
160       } else {
161         Lex.Lex();
162         Present = true;
163       }
164       return false;
165     }
166     bool ParseStringConstant(std::string &Result);
167     bool ParseUInt32(unsigned &Val);
168     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
169       Loc = Lex.getLoc();
170       return ParseUInt32(Val);
171     }
172     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
173     bool ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind);
174     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
175     bool ParseOptionalLinkage(unsigned &Linkage) {
176       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
177     }
178     bool ParseOptionalVisibility(unsigned &Visibility);
179     bool ParseOptionalCallingConv(CallingConv::ID &CC);
180     bool ParseOptionalAlignment(unsigned &Alignment);
181     bool ParseOptionalStackAlignment(unsigned &Alignment);
182     bool ParseInstructionMetadata(Instruction *Inst);
183     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
184     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
185     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
186       bool AteExtraComma;
187       if (ParseIndexList(Indices, AteExtraComma)) return true;
188       if (AteExtraComma)
189         return TokError("expected index");
190       return false;
191     }
192
193     // Top-Level Entities
194     bool ParseTopLevelEntities();
195     bool ValidateEndOfModule();
196     bool ParseTargetDefinition();
197     bool ParseDepLibs();
198     bool ParseModuleAsm();
199     bool ParseUnnamedType();
200     bool ParseNamedType();
201     bool ParseDeclare();
202     bool ParseDefine();
203
204     bool ParseGlobalType(bool &IsConstant);
205     bool ParseUnnamedGlobal();
206     bool ParseNamedGlobal();
207     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
208                      bool HasLinkage, unsigned Visibility);
209     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Visibility);
210     bool ParseStandaloneMetadata();
211     bool ParseNamedMetadata();
212     bool ParseMDString(MDString *&Result);
213     bool ParseMDNodeID(MDNode *&Result);
214     bool ParseMDNodeID(MDNode *&Result, unsigned &SlotNo);
215
216     // Type Parsing.
217     bool ParseType(PATypeHolder &Result, bool AllowVoid = false);
218     bool ParseType(PATypeHolder &Result, LocTy &Loc, bool AllowVoid = false) {
219       Loc = Lex.getLoc();
220       return ParseType(Result, AllowVoid);
221     }
222     bool ParseTypeRec(PATypeHolder &H);
223     bool ParseStructType(PATypeHolder &H, bool Packed);
224     bool ParseUnionType(PATypeHolder &H);
225     bool ParseArrayVectorType(PATypeHolder &H, bool isVector);
226     bool ParseFunctionType(PATypeHolder &Result);
227     PATypeHolder HandleUpRefs(const Type *Ty);
228
229     // Function Semantic Analysis.
230     class PerFunctionState {
231       LLParser &P;
232       Function &F;
233       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
234       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
235       std::vector<Value*> NumberedVals;
236       
237       /// FunctionNumber - If this is an unnamed function, this is the slot
238       /// number of it, otherwise it is -1.
239       int FunctionNumber;
240     public:
241       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
242       ~PerFunctionState();
243
244       Function &getFunction() const { return F; }
245
246       bool FinishFunction();
247
248       /// GetVal - Get a value with the specified name or ID, creating a
249       /// forward reference record if needed.  This can return null if the value
250       /// exists but does not have the right type.
251       Value *GetVal(const std::string &Name, const Type *Ty, LocTy Loc);
252       Value *GetVal(unsigned ID, const Type *Ty, LocTy Loc);
253
254       /// SetInstName - After an instruction is parsed and inserted into its
255       /// basic block, this installs its name.
256       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
257                        Instruction *Inst);
258
259       /// GetBB - Get a basic block with the specified name or ID, creating a
260       /// forward reference record if needed.  This can return null if the value
261       /// is not a BasicBlock.
262       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
263       BasicBlock *GetBB(unsigned ID, LocTy Loc);
264
265       /// DefineBB - Define the specified basic block, which is either named or
266       /// unnamed.  If there is an error, this returns null otherwise it returns
267       /// the block being defined.
268       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
269     };
270
271     bool ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
272                              PerFunctionState *PFS);
273
274     bool ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS);
275     bool ParseValue(const Type *Ty, Value *&V, LocTy &Loc,
276                     PerFunctionState &PFS) {
277       Loc = Lex.getLoc();
278       return ParseValue(Ty, V, PFS);
279     }
280
281     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS);
282     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
283       Loc = Lex.getLoc();
284       return ParseTypeAndValue(V, PFS);
285     }
286     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
287                                 PerFunctionState &PFS);
288     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
289       LocTy Loc;
290       return ParseTypeAndBasicBlock(BB, Loc, PFS);
291     }
292
293     bool ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V);
294
295     struct ParamInfo {
296       LocTy Loc;
297       Value *V;
298       unsigned Attrs;
299       ParamInfo(LocTy loc, Value *v, unsigned attrs)
300         : Loc(loc), V(v), Attrs(attrs) {}
301     };
302     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
303                             PerFunctionState &PFS);
304
305     // Constant Parsing.
306     bool ParseValID(ValID &ID, PerFunctionState *PFS = NULL);
307     bool ParseGlobalValue(const Type *Ty, Constant *&V);
308     bool ParseGlobalTypeAndValue(Constant *&V);
309     bool ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts);
310     bool ParseMDNodeVector(SmallVectorImpl<Value*> &, PerFunctionState *PFS);
311
312     // Function Parsing.
313     struct ArgInfo {
314       LocTy Loc;
315       PATypeHolder Type;
316       unsigned Attrs;
317       std::string Name;
318       ArgInfo(LocTy L, PATypeHolder Ty, unsigned Attr, const std::string &N)
319         : Loc(L), Type(Ty), Attrs(Attr), Name(N) {}
320     };
321     bool ParseArgumentList(std::vector<ArgInfo> &ArgList,
322                            bool &isVarArg, bool inType);
323     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
324     bool ParseFunctionBody(Function &Fn);
325     bool ParseBasicBlock(PerFunctionState &PFS);
326
327     // Instruction Parsing.  Each instruction parsing routine can return with a
328     // normal result, an error result, or return having eaten an extra comma.
329     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
330     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
331                          PerFunctionState &PFS);
332     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
333
334     int ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
335     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
336     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
337     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
338     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
339
340     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
341                          unsigned OperandType);
342     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
343     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
344     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
345     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
346     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
347     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
348     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
349     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
350     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
351     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
352     int ParseAlloc(Instruction *&I, PerFunctionState &PFS,
353                     BasicBlock *BB = 0, bool isAlloca = true);
354     bool ParseFree(Instruction *&I, PerFunctionState &PFS, BasicBlock *BB);
355     int ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile);
356     int ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile);
357     bool ParseGetResult(Instruction *&I, PerFunctionState &PFS);
358     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
359     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
360     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
361     
362     bool ResolveForwardRefBlockAddresses(Function *TheFn, 
363                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
364                                          PerFunctionState *PFS);
365   };
366 } // End llvm namespace
367
368 #endif