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