[mips] Specify the correct value type when combining a CMovFP node.
[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     std::unique_ptr<Constant*[]> ConstantStructElts;
66
67     ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
68     // Workaround for MSVC not synthesizing implicit move members.
69     ValID(ValID &&RHS)
70         : Kind(std::move(RHS.Kind)), Loc(std::move(RHS.Loc)),
71           UIntVal(std::move(RHS.UIntVal)), StrVal(std::move(RHS.StrVal)),
72           StrVal2(std::move(RHS.StrVal2)), APSIntVal(std::move(RHS.APSIntVal)),
73           APFloatVal(std::move(RHS.APFloatVal)),
74           ConstantVal(std::move(RHS.ConstantVal)),
75           ConstantStructElts(std::move(RHS.ConstantStructElts)) {}
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
110     SmallVector<Instruction*, 64> InstsWithTBAATag;
111
112     // Type resolution handling data structures.  The location is set when we
113     // have processed a use of the type but not a definition yet.
114     StringMap<std::pair<Type*, LocTy> > NamedTypes;
115     std::map<unsigned, std::pair<Type*, LocTy> > NumberedTypes;
116
117     std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
118     std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
119
120     // Global Value reference information.
121     std::map<std::string, std::pair<GlobalValue*, LocTy> > ForwardRefVals;
122     std::map<unsigned, std::pair<GlobalValue*, LocTy> > ForwardRefValIDs;
123     std::vector<GlobalValue*> NumberedVals;
124
125     // Comdat forward reference information.
126     std::map<std::string, LocTy> ForwardRefComdats;
127
128     // References to blockaddress.  The key is the function ValID, the value is
129     // a list of references to blocks in that function.
130     std::map<ValID, std::map<ValID, GlobalValue *>> ForwardRefBlockAddresses;
131     class PerFunctionState;
132     /// Reference to per-function state to allow basic blocks to be
133     /// forward-referenced by blockaddress instructions within the same
134     /// function.
135     PerFunctionState *BlockAddressPFS;
136
137     // Attribute builder reference information.
138     std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
139     std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
140
141   public:
142     LLParser(StringRef F, SourceMgr &SM, SMDiagnostic &Err, Module *m)
143         : Context(m->getContext()), Lex(F, SM, Err, m->getContext()), M(m),
144           BlockAddressPFS(nullptr) {}
145     bool Run();
146
147     LLVMContext &getContext() { return Context; }
148
149   private:
150
151     bool Error(LocTy L, const Twine &Msg) const {
152       return Lex.Error(L, Msg);
153     }
154     bool TokError(const Twine &Msg) const {
155       return Error(Lex.getLoc(), Msg);
156     }
157
158     /// GetGlobalVal - Get a value with the specified name or ID, creating a
159     /// forward reference record if needed.  This can return null if the value
160     /// exists but does not have the right type.
161     GlobalValue *GetGlobalVal(const std::string &N, Type *Ty, LocTy Loc);
162     GlobalValue *GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc);
163
164     /// Get a Comdat with the specified name, creating a forward reference
165     /// record if needed.
166     Comdat *getComdat(const std::string &N, LocTy Loc);
167
168     // Helper Routines.
169     bool ParseToken(lltok::Kind T, const char *ErrMsg);
170     bool EatIfPresent(lltok::Kind T) {
171       if (Lex.getKind() != T) return false;
172       Lex.Lex();
173       return true;
174     }
175
176     FastMathFlags EatFastMathFlagsIfPresent() {
177       FastMathFlags FMF;
178       while (true)
179         switch (Lex.getKind()) {
180         case lltok::kw_fast: FMF.setUnsafeAlgebra();   Lex.Lex(); continue;
181         case lltok::kw_nnan: FMF.setNoNaNs();          Lex.Lex(); continue;
182         case lltok::kw_ninf: FMF.setNoInfs();          Lex.Lex(); continue;
183         case lltok::kw_nsz:  FMF.setNoSignedZeros();   Lex.Lex(); continue;
184         case lltok::kw_arcp: FMF.setAllowReciprocal(); Lex.Lex(); continue;
185         default: return FMF;
186         }
187       return FMF;
188     }
189
190     bool ParseOptionalToken(lltok::Kind T, bool &Present,
191                             LocTy *Loc = nullptr) {
192       if (Lex.getKind() != T) {
193         Present = false;
194       } else {
195         if (Loc)
196           *Loc = Lex.getLoc();
197         Lex.Lex();
198         Present = true;
199       }
200       return false;
201     }
202     bool ParseStringConstant(std::string &Result);
203     bool ParseUInt32(unsigned &Val);
204     bool ParseUInt32(unsigned &Val, LocTy &Loc) {
205       Loc = Lex.getLoc();
206       return ParseUInt32(Val);
207     }
208     bool ParseUInt64(uint64_t &Val);
209     bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
210       Loc = Lex.getLoc();
211       return ParseUInt64(Val);
212     }
213
214     bool ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM);
215     bool ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM);
216     bool parseOptionalUnnamedAddr(bool &UnnamedAddr) {
217       return ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr);
218     }
219     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
220     bool ParseOptionalParamAttrs(AttrBuilder &B);
221     bool ParseOptionalReturnAttrs(AttrBuilder &B);
222     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
223     bool ParseOptionalLinkage(unsigned &Linkage) {
224       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
225     }
226     bool ParseOptionalVisibility(unsigned &Visibility);
227     bool ParseOptionalDLLStorageClass(unsigned &DLLStorageClass);
228     bool ParseOptionalCallingConv(unsigned &CC);
229     bool ParseOptionalAlignment(unsigned &Alignment);
230     bool ParseOptionalDereferenceableBytes(uint64_t &Bytes);
231     bool ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
232                                AtomicOrdering &Ordering);
233     bool ParseOrdering(AtomicOrdering &Ordering);
234     bool ParseOptionalStackAlignment(unsigned &Alignment);
235     bool ParseOptionalCommaAlign(unsigned &Alignment, bool &AteExtraComma);
236     bool ParseOptionalCommaInAlloca(bool &IsInAlloca);
237     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices,bool &AteExtraComma);
238     bool ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
239       bool AteExtraComma;
240       if (ParseIndexList(Indices, AteExtraComma)) return true;
241       if (AteExtraComma)
242         return TokError("expected index");
243       return false;
244     }
245
246     // Top-Level Entities
247     bool ParseTopLevelEntities();
248     bool ValidateEndOfModule();
249     bool ParseTargetDefinition();
250     bool ParseModuleAsm();
251     bool ParseDepLibs();        // FIXME: Remove in 4.0.
252     bool ParseUnnamedType();
253     bool ParseNamedType();
254     bool ParseDeclare();
255     bool ParseDefine();
256
257     bool ParseGlobalType(bool &IsConstant);
258     bool ParseUnnamedGlobal();
259     bool ParseNamedGlobal();
260     bool ParseGlobal(const std::string &Name, LocTy Loc, unsigned Linkage,
261                      bool HasLinkage, unsigned Visibility,
262                      unsigned DLLStorageClass,
263                      GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
264     bool ParseAlias(const std::string &Name, LocTy Loc, unsigned Linkage,
265                     unsigned Visibility, unsigned DLLStorageClass,
266                     GlobalVariable::ThreadLocalMode TLM, bool UnnamedAddr);
267     bool parseComdat();
268     bool ParseStandaloneMetadata();
269     bool ParseNamedMetadata();
270     bool ParseMDString(MDString *&Result);
271     bool ParseMDNodeID(MDNode *&Result);
272     bool ParseUnnamedAttrGrp();
273     bool ParseFnAttributeValuePairs(AttrBuilder &B,
274                                     std::vector<unsigned> &FwdRefAttrGrps,
275                                     bool inAttrGrp, LocTy &BuiltinLoc);
276
277     // Type Parsing.
278     bool ParseType(Type *&Result, const Twine &Msg, bool AllowVoid = false);
279     bool ParseType(Type *&Result, bool AllowVoid = false) {
280       return ParseType(Result, "expected type", AllowVoid);
281     }
282     bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
283                    bool AllowVoid = false) {
284       Loc = Lex.getLoc();
285       return ParseType(Result, Msg, AllowVoid);
286     }
287     bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
288       Loc = Lex.getLoc();
289       return ParseType(Result, AllowVoid);
290     }
291     bool ParseAnonStructType(Type *&Result, bool Packed);
292     bool ParseStructBody(SmallVectorImpl<Type*> &Body);
293     bool ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
294                                std::pair<Type*, LocTy> &Entry,
295                                Type *&ResultTy);
296
297     bool ParseArrayVectorType(Type *&Result, bool isVector);
298     bool ParseFunctionType(Type *&Result);
299
300     // Function Semantic Analysis.
301     class PerFunctionState {
302       LLParser &P;
303       Function &F;
304       std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
305       std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
306       std::vector<Value*> NumberedVals;
307
308       /// FunctionNumber - If this is an unnamed function, this is the slot
309       /// number of it, otherwise it is -1.
310       int FunctionNumber;
311     public:
312       PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
313       ~PerFunctionState();
314
315       Function &getFunction() const { return F; }
316
317       bool FinishFunction();
318
319       /// GetVal - Get a value with the specified name or ID, creating a
320       /// forward reference record if needed.  This can return null if the value
321       /// exists but does not have the right type.
322       Value *GetVal(const std::string &Name, Type *Ty, LocTy Loc);
323       Value *GetVal(unsigned ID, Type *Ty, LocTy Loc);
324
325       /// SetInstName - After an instruction is parsed and inserted into its
326       /// basic block, this installs its name.
327       bool SetInstName(int NameID, const std::string &NameStr, LocTy NameLoc,
328                        Instruction *Inst);
329
330       /// GetBB - Get a basic block with the specified name or ID, creating a
331       /// forward reference record if needed.  This can return null if the value
332       /// is not a BasicBlock.
333       BasicBlock *GetBB(const std::string &Name, LocTy Loc);
334       BasicBlock *GetBB(unsigned ID, LocTy Loc);
335
336       /// DefineBB - Define the specified basic block, which is either named or
337       /// unnamed.  If there is an error, this returns null otherwise it returns
338       /// the block being defined.
339       BasicBlock *DefineBB(const std::string &Name, LocTy Loc);
340
341       bool resolveForwardRefBlockAddresses();
342     };
343
344     bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
345                              PerFunctionState *PFS);
346
347     bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
348     bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
349       return ParseValue(Ty, V, &PFS);
350     }
351     bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
352                     PerFunctionState &PFS) {
353       Loc = Lex.getLoc();
354       return ParseValue(Ty, V, &PFS);
355     }
356
357     bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
358     bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
359       return ParseTypeAndValue(V, &PFS);
360     }
361     bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
362       Loc = Lex.getLoc();
363       return ParseTypeAndValue(V, PFS);
364     }
365     bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
366                                 PerFunctionState &PFS);
367     bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
368       LocTy Loc;
369       return ParseTypeAndBasicBlock(BB, Loc, PFS);
370     }
371
372
373     struct ParamInfo {
374       LocTy Loc;
375       Value *V;
376       AttributeSet Attrs;
377       ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
378         : Loc(loc), V(v), Attrs(attrs) {}
379     };
380     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
381                             PerFunctionState &PFS,
382                             bool IsMustTailCall = false,
383                             bool InVarArgsFunc = false);
384
385     // Constant Parsing.
386     bool ParseValID(ValID &ID, PerFunctionState *PFS = nullptr);
387     bool ParseGlobalValue(Type *Ty, Constant *&V);
388     bool ParseGlobalTypeAndValue(Constant *&V);
389     bool ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts);
390     bool parseOptionalComdat(StringRef GlobalName, Comdat *&C);
391     bool ParseMetadataAsValue(Value *&V, PerFunctionState &PFS);
392     bool ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
393                               PerFunctionState *PFS);
394     bool ParseMetadata(Metadata *&MD, PerFunctionState *PFS);
395     bool ParseMDTuple(MDNode *&MD, bool IsDistinct = false);
396     bool ParseMDNode(MDNode *&MD);
397     bool ParseMDNodeTail(MDNode *&MD);
398     bool ParseMDNodeVector(SmallVectorImpl<Metadata *> &MDs);
399     bool ParseInstructionMetadata(Instruction *Inst, PerFunctionState *PFS);
400
401     template <class FieldTy>
402     bool ParseMDField(LocTy Loc, StringRef Name, FieldTy &Result);
403     template <class FieldTy> bool ParseMDField(StringRef Name, FieldTy &Result);
404     template <class ParserTy>
405     bool ParseMDFieldsImplBody(ParserTy parseField);
406     template <class ParserTy>
407     bool ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc);
408     bool ParseSpecializedMDNode(MDNode *&N, bool IsDistinct = false);
409
410 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
411   bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
412 #include "llvm/IR/Metadata.def"
413
414     // Function Parsing.
415     struct ArgInfo {
416       LocTy Loc;
417       Type *Ty;
418       AttributeSet Attrs;
419       std::string Name;
420       ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
421         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
422     };
423     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarArg);
424     bool ParseFunctionHeader(Function *&Fn, bool isDefine);
425     bool ParseFunctionBody(Function &Fn);
426     bool ParseBasicBlock(PerFunctionState &PFS);
427
428     enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
429
430     // Instruction Parsing.  Each instruction parsing routine can return with a
431     // normal result, an error result, or return having eaten an extra comma.
432     enum InstResult { InstNormal = 0, InstError = 1, InstExtraComma = 2 };
433     int ParseInstruction(Instruction *&Inst, BasicBlock *BB,
434                          PerFunctionState &PFS);
435     bool ParseCmpPredicate(unsigned &Pred, unsigned Opc);
436
437     bool ParseRet(Instruction *&Inst, BasicBlock *BB, PerFunctionState &PFS);
438     bool ParseBr(Instruction *&Inst, PerFunctionState &PFS);
439     bool ParseSwitch(Instruction *&Inst, PerFunctionState &PFS);
440     bool ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS);
441     bool ParseInvoke(Instruction *&Inst, PerFunctionState &PFS);
442     bool ParseResume(Instruction *&Inst, PerFunctionState &PFS);
443
444     bool ParseArithmetic(Instruction *&I, PerFunctionState &PFS, unsigned Opc,
445                          unsigned OperandType);
446     bool ParseLogical(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
447     bool ParseCompare(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
448     bool ParseCast(Instruction *&I, PerFunctionState &PFS, unsigned Opc);
449     bool ParseSelect(Instruction *&I, PerFunctionState &PFS);
450     bool ParseVA_Arg(Instruction *&I, PerFunctionState &PFS);
451     bool ParseExtractElement(Instruction *&I, PerFunctionState &PFS);
452     bool ParseInsertElement(Instruction *&I, PerFunctionState &PFS);
453     bool ParseShuffleVector(Instruction *&I, PerFunctionState &PFS);
454     int ParsePHI(Instruction *&I, PerFunctionState &PFS);
455     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
456     bool ParseCall(Instruction *&I, PerFunctionState &PFS,
457                    CallInst::TailCallKind IsTail);
458     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
459     int ParseLoad(Instruction *&I, PerFunctionState &PFS);
460     int ParseStore(Instruction *&I, PerFunctionState &PFS);
461     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
462     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
463     int ParseFence(Instruction *&I, PerFunctionState &PFS);
464     int ParseGetElementPtr(Instruction *&I, PerFunctionState &PFS);
465     int ParseExtractValue(Instruction *&I, PerFunctionState &PFS);
466     int ParseInsertValue(Instruction *&I, PerFunctionState &PFS);
467
468     // Use-list order directives.
469     bool ParseUseListOrder(PerFunctionState *PFS = nullptr);
470     bool ParseUseListOrderBB();
471     bool ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes);
472     bool sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes, SMLoc Loc);
473   };
474 } // End llvm namespace
475
476 #endif