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 std::unique_ptr<Constant*[]> ConstantStructElts;
67 ValID() : Kind(t_LocalID), APFloatVal(0.0) {}
68 // Workaround for MSVC not synthesizing implicit move members.
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)) {}
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;
89 typedef LLLexer::LocTy LocTy;
95 // Instruction metadata resolution. Each instruction can have a list of
96 // MDRef info associated with them.
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.
107 unsigned MDKind, MDSlot;
110 SmallVector<Instruction*, 64> InstsWithTBAATag;
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;
117 std::map<unsigned, TrackingMDNodeRef> NumberedMetadata;
118 std::map<unsigned, std::pair<TempMDTuple, LocTy>> ForwardRefMDNodes;
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;
125 // Comdat forward reference information.
126 std::map<std::string, LocTy> ForwardRefComdats;
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
135 PerFunctionState *BlockAddressPFS;
137 // Attribute builder reference information.
138 std::map<Value*, std::vector<unsigned> > ForwardRefAttrGroups;
139 std::map<unsigned, AttrBuilder> NumberedAttrBuilders;
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) {}
147 LLVMContext &getContext() { return Context; }
151 bool Error(LocTy L, const Twine &Msg) const {
152 return Lex.Error(L, Msg);
154 bool TokError(const Twine &Msg) const {
155 return Error(Lex.getLoc(), Msg);
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);
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);
169 bool ParseToken(lltok::Kind T, const char *ErrMsg);
170 bool EatIfPresent(lltok::Kind T) {
171 if (Lex.getKind() != T) return false;
176 FastMathFlags EatFastMathFlagsIfPresent() {
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;
190 bool ParseOptionalToken(lltok::Kind T, bool &Present,
191 LocTy *Loc = nullptr) {
192 if (Lex.getKind() != T) {
202 bool ParseStringConstant(std::string &Result);
203 bool ParseUInt32(unsigned &Val);
204 bool ParseUInt32(unsigned &Val, LocTy &Loc) {
206 return ParseUInt32(Val);
208 bool ParseUInt64(uint64_t &Val);
209 bool ParseUInt64(uint64_t &Val, LocTy &Loc) {
211 return ParseUInt64(Val);
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);
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);
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) {
240 if (ParseIndexList(Indices, AteExtraComma)) return true;
242 return TokError("expected index");
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();
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);
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);
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);
282 bool ParseType(Type *&Result, const Twine &Msg, LocTy &Loc,
283 bool AllowVoid = false) {
285 return ParseType(Result, Msg, AllowVoid);
287 bool ParseType(Type *&Result, LocTy &Loc, bool AllowVoid = false) {
289 return ParseType(Result, AllowVoid);
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,
297 bool ParseArrayVectorType(Type *&Result, bool isVector);
298 bool ParseFunctionType(Type *&Result);
300 // Function Semantic Analysis.
301 class PerFunctionState {
304 std::map<std::string, std::pair<Value*, LocTy> > ForwardRefVals;
305 std::map<unsigned, std::pair<Value*, LocTy> > ForwardRefValIDs;
306 std::vector<Value*> NumberedVals;
308 /// FunctionNumber - If this is an unnamed function, this is the slot
309 /// number of it, otherwise it is -1.
312 PerFunctionState(LLParser &p, Function &f, int FunctionNumber);
315 Function &getFunction() const { return F; }
317 bool FinishFunction();
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);
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,
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);
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);
341 bool resolveForwardRefBlockAddresses();
344 bool ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
345 PerFunctionState *PFS);
347 bool ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS);
348 bool ParseValue(Type *Ty, Value *&V, PerFunctionState &PFS) {
349 return ParseValue(Ty, V, &PFS);
351 bool ParseValue(Type *Ty, Value *&V, LocTy &Loc,
352 PerFunctionState &PFS) {
354 return ParseValue(Ty, V, &PFS);
357 bool ParseTypeAndValue(Value *&V, PerFunctionState *PFS);
358 bool ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
359 return ParseTypeAndValue(V, &PFS);
361 bool ParseTypeAndValue(Value *&V, LocTy &Loc, PerFunctionState &PFS) {
363 return ParseTypeAndValue(V, PFS);
365 bool ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
366 PerFunctionState &PFS);
367 bool ParseTypeAndBasicBlock(BasicBlock *&BB, PerFunctionState &PFS) {
369 return ParseTypeAndBasicBlock(BB, Loc, PFS);
377 ParamInfo(LocTy loc, Value *v, AttributeSet attrs)
378 : Loc(loc), V(v), Attrs(attrs) {}
380 bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
381 PerFunctionState &PFS,
382 bool IsMustTailCall = false,
383 bool InVarArgsFunc = false);
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);
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);
410 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
411 bool Parse##CLASS(MDNode *&Result, bool IsDistinct);
412 #include "llvm/IR/Metadata.def"
420 ArgInfo(LocTy L, Type *ty, AttributeSet Attr, const std::string &N)
421 : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
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);
428 enum TailCallType { TCT_None, TCT_Tail, TCT_MustTail };
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);
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);
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);
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);
474 } // End llvm namespace