1 //===-- LLParser.h - Parser Class -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_LIB_ASMPARSER_LLPARSER_H
15 #define LLVM_LIB_ASMPARSER_LLPARSER_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"
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.
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.
61 std::string StrVal, StrVal2;
64 Constant *ConstantVal;
65 Constant **ConstantStructElts;
67 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
69 if (Kind == t_ConstantStruct || Kind == t_PackedConstantStruct)
70 delete [] ConstantStructElts;
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;
83 /// Structure to represent an optional metadata field.
84 template <class FieldTy> struct MDFieldImpl {
85 typedef MDFieldImpl ImplTy;
89 void assign(FieldTy Val) {
91 this->Val = std::move(Val);
94 explicit MDFieldImpl(FieldTy Default)
95 : Val(std::move(Default)), Seen(false) {}
97 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
100 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
101 : ImplTy(Default), Max(Max) {}
103 struct DwarfTagField : public MDUnsignedField {
104 DwarfTagField() : MDUnsignedField(0, ~0u >> 16) {}
106 struct MDField : public MDFieldImpl<Metadata *> {
107 MDField() : ImplTy(nullptr) {}
109 struct MDStringField : public MDFieldImpl<std::string> {
110 MDStringField() : ImplTy(std::string()) {}
112 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
113 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
118 typedef LLLexer::LocTy LocTy;
120 LLVMContext &Context;
124 // Instruction metadata resolution. Each instruction can have a list of
125 // MDRef info associated with them.
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.
136 unsigned MDKind, MDSlot;
139 SmallVector<Instruction*, 64> InstsWithTBAATag;
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;
146 std::vector<TrackingMDNodeRef> NumberedMetadata;
147 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
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;
154 // Comdat forward reference information.
155 std::map<std::string, LocTy> ForwardRefComdats;
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
164 PerFunctionState *BlockAddressPFS;
166 // Attribute builder reference information.
167 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
168 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
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) {}
176 LLVMContext &getContext() { return Context; }
180 bool Error(LocTy L, const Twine &Msg) const {
181 return Lex.Error(L, Msg);
183 bool TokError(const Twine &Msg) const {
184 return Error(Lex.getLoc(), Msg);
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);
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);
198 bool ParseToken(lltok::Kind T, const char *ErrMsg);
199 bool EatIfPresent(lltok::Kind T) {
200 if (Lex.getKind() != T) return false;
205 FastMathFlags EatFastMathFlagsIfPresent() {
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;
219 bool ParseOptionalToken(lltok::Kind T, bool &Present,
220 LocTy *Loc = nullptr) {
221 if (Lex.getKind() != T) {
231 bool ParseStringConstant(std::string &Result);
232 bool ParseUInt32(unsigned &Val);
233 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
235 return ParseUInt32(Val);
237 bool ParseUInt64(uint64_t &Val);
238 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
240 return ParseUInt64(Val);
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);
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);
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) {
269 if (ParseIndexList(Indices, AteExtraComma)) return true;
271 return TokError("expected index");
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();
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);
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);
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);
311 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
312 bool AllowVoid = false) {
314 return ParseType(Result, Msg, AllowVoid);
316 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
318 return ParseType(Result, AllowVoid);
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,
326 bool ParseArrayVectorType(Type *&Result, bool isVector);
327 bool ParseFunctionType(Type *&Result);
329 // Function Semantic Analysis.
330 class PerFunctionState {
333 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
334 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
335 std::vector<Value*> NumberedVals;
337 /// FunctionNumber - If this is an unnamed function, this is the slot
338 /// number of it, otherwise it is -1.
341 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
344 Function &getFunction() const { return F; }
346 bool FinishFunction();
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);
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,
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);
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);
370 bool resolveForwardRefBlockAddresses();
373 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
374 PerFunctionState *PFS);
376 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
377 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
378 return ParseValue(Ty, V, &PFS);
380 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
381 PerFunctionState &PFS) {
383 return ParseValue(Ty, V, &PFS);
386 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
387 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
388 return ParseTypeAndValue(V, &PFS);
390 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
392 return ParseTypeAndValue(V, PFS);
394 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
395 PerFunctionState &PFS);
396 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
398 return ParseTypeAndBasicBlock(BB, Loc, PFS);
406 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
407 : Loc(loc), V(v), Attrs(attrs) {}
409 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
410 PerFunctionState &PFS,
411 bool IsMustTailCall = false,
412 bool InVarArgsFunc = false);
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);
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);
449 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
450 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
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);
457 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
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);
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);
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);
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);
503 } // End llvm namespace