1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===// 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 implements the DIBuilder. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/DIBuilder.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DebugInfo.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/Dwarf.h" 22 #include "LLVMContextImpl.h" 23 24 using namespace llvm; 25 using namespace llvm::dwarf; 26 27 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes) 28 : M(m), VMContext(M.getContext()), CUNode(nullptr), 29 DeclareFn(nullptr), ValueFn(nullptr), 30 AllowUnresolvedNodes(AllowUnresolvedNodes) {} 31 32 void DIBuilder::trackIfUnresolved(MDNode *N) { 33 if (!N) 34 return; 35 if (N->isResolved()) 36 return; 37 38 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes"); 39 UnresolvedNodes.emplace_back(N); 40 } 41 42 void DIBuilder::finalize() { 43 if (!CUNode) { 44 assert(!AllowUnresolvedNodes && 45 "creating type nodes without a CU is not supported"); 46 return; 47 } 48 49 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes)); 50 51 SmallVector<Metadata *, 16> RetainValues; 52 // Declarations and definitions of the same type may be retained. Some 53 // clients RAUW these pairs, leaving duplicates in the retained types 54 // list. Use a set to remove the duplicates while we transform the 55 // TrackingVHs back into Values. 56 SmallPtrSet<Metadata *, 16> RetainSet; 57 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) 58 if (RetainSet.insert(AllRetainTypes[I]).second) 59 RetainValues.push_back(AllRetainTypes[I]); 60 61 if (!RetainValues.empty()) 62 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues)); 63 64 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms); 65 auto resolveVariables = [&](DISubprogram *SP) { 66 MDTuple *Temp = SP->getVariables().get(); 67 if (!Temp) 68 return; 69 70 SmallVector<Metadata *, 4> Variables; 71 72 auto PV = PreservedVariables.find(SP); 73 if (PV != PreservedVariables.end()) 74 Variables.append(PV->second.begin(), PV->second.end()); 75 76 DINodeArray AV = getOrCreateArray(Variables); 77 TempMDTuple(Temp)->replaceAllUsesWith(AV.get()); 78 }; 79 for (auto *SP : SPs) 80 resolveVariables(SP); 81 for (auto *N : RetainValues) 82 if (auto *SP = dyn_cast<DISubprogram>(N)) 83 resolveVariables(SP); 84 85 if (!AllGVs.empty()) 86 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs)); 87 88 if (!AllImportedModules.empty()) 89 CUNode->replaceImportedEntities(MDTuple::get( 90 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(), 91 AllImportedModules.end()))); 92 93 // Now that all temp nodes have been replaced or deleted, resolve remaining 94 // cycles. 95 for (const auto &N : UnresolvedNodes) 96 if (N && !N->isResolved()) 97 N->resolveCycles(); 98 UnresolvedNodes.clear(); 99 100 // Can't handle unresolved nodes anymore. 101 AllowUnresolvedNodes = false; 102 } 103 104 /// If N is compile unit return NULL otherwise return N. 105 static DIScope *getNonCompileUnitScope(DIScope *N) { 106 if (!N || isa<DICompileUnit>(N)) 107 return nullptr; 108 return cast<DIScope>(N); 109 } 110 111 DICompileUnit *DIBuilder::createCompileUnit( 112 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, 113 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, 114 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId, 115 bool SplitDebugInlining) { 116 117 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || 118 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && 119 "Invalid Language tag"); 120 assert(!Filename.empty() && 121 "Unable to create compile unit without filename"); 122 123 assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); 124 CUNode = DICompileUnit::getDistinct( 125 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer, 126 isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr, 127 nullptr, nullptr, nullptr, DWOId, SplitDebugInlining); 128 129 // Create a named metadata so that it is easier to find cu in a module. 130 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); 131 NMD->addOperand(CUNode); 132 trackIfUnresolved(CUNode); 133 return CUNode; 134 } 135 136 static DIImportedEntity * 137 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, 138 Metadata *NS, unsigned Line, StringRef Name, 139 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) { 140 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size(); 141 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name); 142 if (EntitiesCount < C.pImpl->DIImportedEntitys.size()) 143 // A new Imported Entity was just added to the context. 144 // Add it to the Imported Modules list. 145 AllImportedModules.emplace_back(M); 146 return M; 147 } 148 149 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 150 DINamespace *NS, 151 unsigned Line) { 152 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 153 Context, NS, Line, StringRef(), AllImportedModules); 154 } 155 156 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, 157 DIImportedEntity *NS, 158 unsigned Line) { 159 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 160 Context, NS, Line, StringRef(), AllImportedModules); 161 } 162 163 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, 164 unsigned Line) { 165 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, 166 Context, M, Line, StringRef(), AllImportedModules); 167 } 168 169 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context, 170 DINode *Decl, 171 unsigned Line, 172 StringRef Name) { 173 // Make sure to use the unique identifier based metadata reference for 174 // types that have one. 175 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, 176 Context, Decl, Line, Name, AllImportedModules); 177 } 178 179 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) { 180 return DIFile::get(VMContext, Filename, Directory); 181 } 182 183 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) { 184 assert(!Name.empty() && "Unable to create enumerator without name"); 185 return DIEnumerator::get(VMContext, Val, Name); 186 } 187 188 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { 189 assert(!Name.empty() && "Unable to create type without name"); 190 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); 191 } 192 193 DIBasicType *DIBuilder::createNullPtrType() { 194 return createUnspecifiedType("decltype(nullptr)"); 195 } 196 197 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, 198 uint64_t AlignInBits, 199 unsigned Encoding) { 200 assert(!Name.empty() && "Unable to create type without name"); 201 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 202 AlignInBits, Encoding); 203 } 204 205 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { 206 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0, 207 0, 0, DINode::FlagZero); 208 } 209 210 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy, 211 uint64_t SizeInBits, 212 uint64_t AlignInBits, 213 StringRef Name) { 214 // FIXME: Why is there a name here? 215 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, 216 nullptr, 0, nullptr, PointeeTy, SizeInBits, 217 AlignInBits, 0, DINode::FlagZero); 218 } 219 220 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, 221 DIType *Base, 222 uint64_t SizeInBits, 223 uint64_t AlignInBits, 224 DINode::DIFlags Flags) { 225 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", 226 nullptr, 0, nullptr, PointeeTy, SizeInBits, 227 AlignInBits, 0, Flags, Base); 228 } 229 230 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, 231 uint64_t SizeInBits, 232 uint64_t AlignInBits) { 233 assert(RTy && "Unable to create reference type"); 234 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy, 235 SizeInBits, AlignInBits, 0, DINode::FlagZero); 236 } 237 238 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, 239 DIFile *File, unsigned LineNo, 240 DIScope *Context) { 241 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, 242 LineNo, getNonCompileUnitScope(Context), Ty, 0, 0, 243 0, DINode::FlagZero); 244 } 245 246 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { 247 assert(Ty && "Invalid type!"); 248 assert(FriendTy && "Invalid friend type!"); 249 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty, 250 FriendTy, 0, 0, 0, DINode::FlagZero); 251 } 252 253 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, 254 uint64_t BaseOffset, 255 DINode::DIFlags Flags) { 256 assert(Ty && "Unable to create inheritance"); 257 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 258 0, Ty, BaseTy, 0, 0, BaseOffset, Flags); 259 } 260 261 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, 262 DIFile *File, unsigned LineNumber, 263 uint64_t SizeInBits, 264 uint64_t AlignInBits, 265 uint64_t OffsetInBits, 266 DINode::DIFlags Flags, DIType *Ty) { 267 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 268 LineNumber, getNonCompileUnitScope(Scope), Ty, 269 SizeInBits, AlignInBits, OffsetInBits, Flags); 270 } 271 272 static ConstantAsMetadata *getConstantOrNull(Constant *C) { 273 if (C) 274 return ConstantAsMetadata::get(C); 275 return nullptr; 276 } 277 278 DIDerivedType *DIBuilder::createBitFieldMemberType( 279 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 280 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits, 281 uint64_t StorageOffsetInBits, DINode::DIFlags Flags, DIType *Ty) { 282 Flags |= DINode::FlagBitField; 283 return DIDerivedType::get( 284 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, 285 getNonCompileUnitScope(Scope), Ty, SizeInBits, AlignInBits, OffsetInBits, 286 Flags, ConstantAsMetadata::get(ConstantInt::get( 287 IntegerType::get(VMContext, 64), StorageOffsetInBits))); 288 } 289 290 DIDerivedType * 291 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File, 292 unsigned LineNumber, DIType *Ty, 293 DINode::DIFlags Flags, llvm::Constant *Val) { 294 Flags |= DINode::FlagStaticMember; 295 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 296 LineNumber, getNonCompileUnitScope(Scope), Ty, 0, 0, 297 0, Flags, getConstantOrNull(Val)); 298 } 299 300 DIDerivedType * 301 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber, 302 uint64_t SizeInBits, uint64_t AlignInBits, 303 uint64_t OffsetInBits, DINode::DIFlags Flags, 304 DIType *Ty, MDNode *PropertyNode) { 305 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, 306 LineNumber, getNonCompileUnitScope(File), Ty, 307 SizeInBits, AlignInBits, OffsetInBits, Flags, 308 PropertyNode); 309 } 310 311 DIObjCProperty * 312 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, 313 StringRef GetterName, StringRef SetterName, 314 unsigned PropertyAttributes, DIType *Ty) { 315 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, 316 SetterName, PropertyAttributes, Ty); 317 } 318 319 DITemplateTypeParameter * 320 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, 321 DIType *Ty) { 322 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 323 return DITemplateTypeParameter::get(VMContext, Name, Ty); 324 } 325 326 static DITemplateValueParameter * 327 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, 328 DIScope *Context, StringRef Name, DIType *Ty, 329 Metadata *MD) { 330 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); 331 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD); 332 } 333 334 DITemplateValueParameter * 335 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, 336 DIType *Ty, Constant *Val) { 337 return createTemplateValueParameterHelper( 338 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, 339 getConstantOrNull(Val)); 340 } 341 342 DITemplateValueParameter * 343 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, 344 DIType *Ty, StringRef Val) { 345 return createTemplateValueParameterHelper( 346 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, 347 MDString::get(VMContext, Val)); 348 } 349 350 DITemplateValueParameter * 351 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, 352 DIType *Ty, DINodeArray Val) { 353 return createTemplateValueParameterHelper( 354 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, 355 Val.get()); 356 } 357 358 DICompositeType *DIBuilder::createClassType( 359 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 360 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits, 361 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, 362 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { 363 assert((!Context || isa<DIScope>(Context)) && 364 "createClassType should be called with a valid Context"); 365 366 auto *R = DICompositeType::get( 367 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 368 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 369 OffsetInBits, Flags, Elements, 0, VTableHolder, 370 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); 371 trackIfUnresolved(R); 372 return R; 373 } 374 375 DICompositeType *DIBuilder::createStructType( 376 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, 377 uint64_t SizeInBits, uint64_t AlignInBits, DINode::DIFlags Flags, 378 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, 379 DIType *VTableHolder, StringRef UniqueIdentifier) { 380 auto *R = DICompositeType::get( 381 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, 382 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0, 383 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier); 384 trackIfUnresolved(R); 385 return R; 386 } 387 388 DICompositeType *DIBuilder::createUnionType( 389 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 390 uint64_t SizeInBits, uint64_t AlignInBits, DINode::DIFlags Flags, 391 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { 392 auto *R = DICompositeType::get( 393 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, 394 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, 395 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier); 396 trackIfUnresolved(R); 397 return R; 398 } 399 400 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, 401 DINode::DIFlags Flags, 402 unsigned CC) { 403 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes); 404 } 405 406 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File, 407 StringRef UniqueIdentifier) { 408 assert(!UniqueIdentifier.empty() && "external type ref without uid"); 409 return DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 410 0, 0, 0, DINode::FlagExternalTypeRef, nullptr, 0, 411 nullptr, nullptr, UniqueIdentifier); 412 } 413 414 DICompositeType *DIBuilder::createEnumerationType( 415 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, 416 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements, 417 DIType *UnderlyingType, StringRef UniqueIdentifier) { 418 auto *CTy = DICompositeType::get( 419 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, 420 getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0, 421 DINode::FlagZero, Elements, 0, nullptr, nullptr, UniqueIdentifier); 422 AllEnumTypes.push_back(CTy); 423 trackIfUnresolved(CTy); 424 return CTy; 425 } 426 427 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits, 428 DIType *Ty, 429 DINodeArray Subscripts) { 430 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 431 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, 432 DINode::FlagZero, Subscripts, 0, nullptr); 433 trackIfUnresolved(R); 434 return R; 435 } 436 437 DICompositeType *DIBuilder::createVectorType(uint64_t Size, 438 uint64_t AlignInBits, DIType *Ty, 439 DINodeArray Subscripts) { 440 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", 441 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, 442 DINode::FlagVector, Subscripts, 0, nullptr); 443 trackIfUnresolved(R); 444 return R; 445 } 446 447 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty, 448 DINode::DIFlags FlagsToSet) { 449 auto NewTy = Ty->clone(); 450 NewTy->setFlags(NewTy->getFlags() | FlagsToSet); 451 return MDNode::replaceWithUniqued(std::move(NewTy)); 452 } 453 454 DIType *DIBuilder::createArtificialType(DIType *Ty) { 455 // FIXME: Restrict this to the nodes where it's valid. 456 if (Ty->isArtificial()) 457 return Ty; 458 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial); 459 } 460 461 DIType *DIBuilder::createObjectPointerType(DIType *Ty) { 462 // FIXME: Restrict this to the nodes where it's valid. 463 if (Ty->isObjectPointer()) 464 return Ty; 465 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; 466 return createTypeWithFlags(VMContext, Ty, Flags); 467 } 468 469 void DIBuilder::retainType(DIScope *T) { 470 assert(T && "Expected non-null type"); 471 assert((isa<DIType>(T) || (isa<DISubprogram>(T) && 472 cast<DISubprogram>(T)->isDefinition() == false)) && 473 "Expected type or subprogram declaration"); 474 AllRetainTypes.emplace_back(T); 475 } 476 477 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } 478 479 DICompositeType * 480 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, 481 DIFile *F, unsigned Line, unsigned RuntimeLang, 482 uint64_t SizeInBits, uint64_t AlignInBits, 483 StringRef UniqueIdentifier) { 484 // FIXME: Define in terms of createReplaceableForwardDecl() by calling 485 // replaceWithUniqued(). 486 auto *RetTy = DICompositeType::get( 487 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 488 SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, 489 nullptr, nullptr, UniqueIdentifier); 490 trackIfUnresolved(RetTy); 491 return RetTy; 492 } 493 494 DICompositeType *DIBuilder::createReplaceableCompositeType( 495 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, 496 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits, 497 DINode::DIFlags Flags, StringRef UniqueIdentifier) { 498 auto *RetTy = 499 DICompositeType::getTemporary( 500 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, 501 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr, 502 nullptr, UniqueIdentifier) 503 .release(); 504 trackIfUnresolved(RetTy); 505 return RetTy; 506 } 507 508 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { 509 return MDTuple::get(VMContext, Elements); 510 } 511 512 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { 513 SmallVector<llvm::Metadata *, 16> Elts; 514 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 515 if (Elements[i] && isa<MDNode>(Elements[i])) 516 Elts.push_back(cast<DIType>(Elements[i])); 517 else 518 Elts.push_back(Elements[i]); 519 } 520 return DITypeRefArray(MDNode::get(VMContext, Elts)); 521 } 522 523 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { 524 return DISubrange::get(VMContext, Count, Lo); 525 } 526 527 static void checkGlobalVariableScope(DIScope *Context) { 528 #ifndef NDEBUG 529 if (auto *CT = 530 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) 531 assert(CT->getIdentifier().empty() && 532 "Context of a global variable should not be a type with identifier"); 533 #endif 534 } 535 536 DIGlobalVariable *DIBuilder::createGlobalVariable( 537 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 538 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr, 539 MDNode *Decl) { 540 checkGlobalVariableScope(Context); 541 542 auto *N = DIGlobalVariable::getDistinct( 543 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 544 LineNumber, Ty, isLocalToUnit, true, Expr, 545 cast_or_null<DIDerivedType>(Decl)); 546 AllGVs.push_back(N); 547 return N; 548 } 549 550 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( 551 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, 552 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr, 553 MDNode *Decl) { 554 checkGlobalVariableScope(Context); 555 556 return DIGlobalVariable::getTemporary( 557 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, 558 LineNumber, Ty, isLocalToUnit, false, Expr, 559 cast_or_null<DIDerivedType>(Decl)) 560 .release(); 561 } 562 563 static DILocalVariable *createLocalVariable( 564 LLVMContext &VMContext, 565 DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables, 566 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 567 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) { 568 // FIXME: Why getNonCompileUnitScope()? 569 // FIXME: Why is "!Context" okay here? 570 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT 571 // the only valid scopes)? 572 DIScope *Context = getNonCompileUnitScope(Scope); 573 574 auto *Node = 575 DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name, 576 File, LineNo, Ty, ArgNo, Flags); 577 if (AlwaysPreserve) { 578 // The optimizer may remove local variables. If there is an interest 579 // to preserve variable info in such situation then stash it in a 580 // named mdnode. 581 DISubprogram *Fn = getDISubprogram(Scope); 582 assert(Fn && "Missing subprogram for local variable"); 583 PreservedVariables[Fn].emplace_back(Node); 584 } 585 return Node; 586 } 587 588 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name, 589 DIFile *File, unsigned LineNo, 590 DIType *Ty, bool AlwaysPreserve, 591 DINode::DIFlags Flags) { 592 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, 593 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, 594 Flags); 595 } 596 597 DILocalVariable *DIBuilder::createParameterVariable( 598 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, 599 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) { 600 assert(ArgNo && "Expected non-zero argument number for parameter"); 601 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo, 602 File, LineNo, Ty, AlwaysPreserve, Flags); 603 } 604 605 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { 606 return DIExpression::get(VMContext, Addr); 607 } 608 609 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) { 610 // TODO: Remove the callers of this signed version and delete. 611 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end()); 612 return createExpression(Addr); 613 } 614 615 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes, 616 unsigned SizeInBytes) { 617 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes}; 618 return DIExpression::get(VMContext, Addr); 619 } 620 621 template <class... Ts> 622 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) { 623 if (IsDistinct) 624 return DISubprogram::getDistinct(std::forward<Ts>(Args)...); 625 return DISubprogram::get(std::forward<Ts>(Args)...); 626 } 627 628 DISubprogram *DIBuilder::createFunction( 629 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 630 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 631 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, 632 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) { 633 auto *Node = getSubprogram( 634 /* IsDistinct = */ isDefinition, VMContext, 635 getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty, 636 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags, 637 isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, 638 MDTuple::getTemporary(VMContext, None).release()); 639 640 if (isDefinition) 641 AllSubprograms.push_back(Node); 642 trackIfUnresolved(Node); 643 return Node; 644 } 645 646 DISubprogram *DIBuilder::createTempFunctionFwdDecl( 647 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, 648 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, 649 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, 650 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) { 651 return DISubprogram::getTemporary( 652 VMContext, getNonCompileUnitScope(Context), Name, LinkageName, 653 File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 654 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, 655 TParams, Decl, nullptr) 656 .release(); 657 } 658 659 DISubprogram *DIBuilder::createMethod(DIScope *Context, StringRef Name, 660 StringRef LinkageName, DIFile *F, 661 unsigned LineNo, DISubroutineType *Ty, 662 bool isLocalToUnit, bool isDefinition, 663 unsigned VK, unsigned VIndex, 664 int ThisAdjustment, DIType *VTableHolder, 665 DINode::DIFlags Flags, bool isOptimized, 666 DITemplateParameterArray TParams) { 667 assert(getNonCompileUnitScope(Context) && 668 "Methods should have both a Context and a context that isn't " 669 "the compile unit."); 670 // FIXME: Do we want to use different scope/lines? 671 auto *SP = getSubprogram( 672 /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name, 673 LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo, 674 VTableHolder, VK, VIndex, ThisAdjustment, Flags, isOptimized, 675 isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr); 676 677 if (isDefinition) 678 AllSubprograms.push_back(SP); 679 trackIfUnresolved(SP); 680 return SP; 681 } 682 683 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, 684 DIFile *File, unsigned LineNo) { 685 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name, 686 LineNo); 687 } 688 689 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, 690 StringRef ConfigurationMacros, 691 StringRef IncludePath, 692 StringRef ISysRoot) { 693 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, 694 ConfigurationMacros, IncludePath, ISysRoot); 695 } 696 697 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, 698 DIFile *File, 699 unsigned Discriminator) { 700 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); 701 } 702 703 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, 704 unsigned Line, unsigned Col) { 705 // Make these distinct, to avoid merging two lexical blocks on the same 706 // file/line/column. 707 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), 708 File, Line, Col); 709 } 710 711 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { 712 assert(V && "no value passed to dbg intrinsic"); 713 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); 714 } 715 716 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) { 717 I->setDebugLoc(const_cast<DILocation *>(DL)); 718 return I; 719 } 720 721 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 722 DIExpression *Expr, const DILocation *DL, 723 Instruction *InsertBefore) { 724 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 725 assert(DL && "Expected debug loc"); 726 assert(DL->getScope()->getSubprogram() == 727 VarInfo->getScope()->getSubprogram() && 728 "Expected matching subprograms"); 729 if (!DeclareFn) 730 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 731 732 trackIfUnresolved(VarInfo); 733 trackIfUnresolved(Expr); 734 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 735 MetadataAsValue::get(VMContext, VarInfo), 736 MetadataAsValue::get(VMContext, Expr)}; 737 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL); 738 } 739 740 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, 741 DIExpression *Expr, const DILocation *DL, 742 BasicBlock *InsertAtEnd) { 743 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); 744 assert(DL && "Expected debug loc"); 745 assert(DL->getScope()->getSubprogram() == 746 VarInfo->getScope()->getSubprogram() && 747 "Expected matching subprograms"); 748 if (!DeclareFn) 749 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); 750 751 trackIfUnresolved(VarInfo); 752 trackIfUnresolved(Expr); 753 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), 754 MetadataAsValue::get(VMContext, VarInfo), 755 MetadataAsValue::get(VMContext, Expr)}; 756 757 // If this block already has a terminator then insert this intrinsic 758 // before the terminator. 759 if (TerminatorInst *T = InsertAtEnd->getTerminator()) 760 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL); 761 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL); 762 } 763 764 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 765 DILocalVariable *VarInfo, 766 DIExpression *Expr, 767 const DILocation *DL, 768 Instruction *InsertBefore) { 769 assert(V && "no value passed to dbg.value"); 770 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 771 assert(DL && "Expected debug loc"); 772 assert(DL->getScope()->getSubprogram() == 773 VarInfo->getScope()->getSubprogram() && 774 "Expected matching subprograms"); 775 if (!ValueFn) 776 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 777 778 trackIfUnresolved(VarInfo); 779 trackIfUnresolved(Expr); 780 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 781 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 782 MetadataAsValue::get(VMContext, VarInfo), 783 MetadataAsValue::get(VMContext, Expr)}; 784 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL); 785 } 786 787 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, 788 DILocalVariable *VarInfo, 789 DIExpression *Expr, 790 const DILocation *DL, 791 BasicBlock *InsertAtEnd) { 792 assert(V && "no value passed to dbg.value"); 793 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); 794 assert(DL && "Expected debug loc"); 795 assert(DL->getScope()->getSubprogram() == 796 VarInfo->getScope()->getSubprogram() && 797 "Expected matching subprograms"); 798 if (!ValueFn) 799 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); 800 801 trackIfUnresolved(VarInfo); 802 trackIfUnresolved(Expr); 803 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), 804 ConstantInt::get(Type::getInt64Ty(VMContext), Offset), 805 MetadataAsValue::get(VMContext, VarInfo), 806 MetadataAsValue::get(VMContext, Expr)}; 807 808 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL); 809 } 810 811 void DIBuilder::replaceVTableHolder(DICompositeType *&T, 812 DICompositeType *VTableHolder) { 813 { 814 TypedTrackingMDRef<DICompositeType> N(T); 815 N->replaceVTableHolder(VTableHolder); 816 T = N.get(); 817 } 818 819 // If this didn't create a self-reference, just return. 820 if (T != VTableHolder) 821 return; 822 823 // Look for unresolved operands. T will drop RAUW support, orphaning any 824 // cycles underneath it. 825 if (T->isResolved()) 826 for (const MDOperand &O : T->operands()) 827 if (auto *N = dyn_cast_or_null<MDNode>(O)) 828 trackIfUnresolved(N); 829 } 830 831 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, 832 DINodeArray TParams) { 833 { 834 TypedTrackingMDRef<DICompositeType> N(T); 835 if (Elements) 836 N->replaceElements(Elements); 837 if (TParams) 838 N->replaceTemplateParams(DITemplateParameterArray(TParams)); 839 T = N.get(); 840 } 841 842 // If T isn't resolved, there's no problem. 843 if (!T->isResolved()) 844 return; 845 846 // If T is resolved, it may be due to a self-reference cycle. Track the 847 // arrays explicitly if they're unresolved, or else the cycles will be 848 // orphaned. 849 if (Elements) 850 trackIfUnresolved(Elements.get()); 851 if (TParams) 852 trackIfUnresolved(TParams.get()); 853 } 854