1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the helper classes used to build and interpret debug 10 // information in LLVM IR form. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm-c/DebugInfo.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/DIBuilder.h" 25 #include "llvm/IR/DebugInfo.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/DebugProgramInstruction.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/GVMaterializer.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/IntrinsicInst.h" 33 #include "llvm/IR/LLVMContext.h" 34 #include "llvm/IR/Metadata.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/PassManager.h" 37 #include "llvm/Support/Casting.h" 38 #include <algorithm> 39 #include <cassert> 40 #include <optional> 41 #include <utility> 42 43 using namespace llvm; 44 using namespace llvm::at; 45 using namespace llvm::dwarf; 46 47 template <typename IntrinsicT, 48 DPValue::LocationType Type = DPValue::LocationType::Any> 49 static void findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V, 50 SmallVectorImpl<DPValue *> *DPValues) { 51 // This function is hot. Check whether the value has any metadata to avoid a 52 // DenseMap lookup. 53 if (!V->isUsedByMetadata()) 54 return; 55 56 LLVMContext &Ctx = V->getContext(); 57 // TODO: If this value appears multiple times in a DIArgList, we should still 58 // only add the owning DbgValueInst once; use this set to track ArgListUsers. 59 // This behaviour can be removed when we can automatically remove duplicates. 60 // V will also appear twice in a dbg.assign if its used in the both the value 61 // and address components. 62 SmallPtrSet<IntrinsicT *, 4> EncounteredIntrinsics; 63 SmallPtrSet<DPValue *, 4> EncounteredDPValues; 64 65 /// Append IntrinsicT users of MetadataAsValue(MD). 66 auto AppendUsers = [&Ctx, &EncounteredIntrinsics, &Result, 67 DPValues](Metadata *MD) { 68 if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) { 69 for (User *U : MDV->users()) 70 if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U)) 71 if (EncounteredIntrinsics.insert(DVI).second) 72 Result.push_back(DVI); 73 } 74 if (!DPValues) 75 return; 76 // Get DPValues that use this as a single value. 77 if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) { 78 for (DPValue *DPV : L->getAllDPValueUsers()) { 79 if (Type == DPValue::LocationType::Any || DPV->getType() == Type) 80 DPValues->push_back(DPV); 81 } 82 } 83 }; 84 85 if (auto *L = LocalAsMetadata::getIfExists(V)) { 86 AppendUsers(L); 87 for (Metadata *AL : L->getAllArgListUsers()) { 88 AppendUsers(AL); 89 if (!DPValues) 90 continue; 91 DIArgList *DI = cast<DIArgList>(AL); 92 for (DPValue *DPV : DI->getAllDPValueUsers()) 93 if (Type == DPValue::LocationType::Any || DPV->getType() == Type) 94 if (EncounteredDPValues.insert(DPV).second) 95 DPValues->push_back(DPV); 96 } 97 } 98 } 99 100 void llvm::findDbgDeclares(SmallVectorImpl<DbgDeclareInst *> &DbgUsers, 101 Value *V, SmallVectorImpl<DPValue *> *DPValues) { 102 findDbgIntrinsics<DbgDeclareInst, DPValue::LocationType::Declare>(DbgUsers, V, 103 DPValues); 104 } 105 106 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, 107 Value *V, SmallVectorImpl<DPValue *> *DPValues) { 108 findDbgIntrinsics<DbgValueInst, DPValue::LocationType::Value>(DbgValues, V, 109 DPValues); 110 } 111 112 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers, 113 Value *V, SmallVectorImpl<DPValue *> *DPValues) { 114 findDbgIntrinsics<DbgVariableIntrinsic, DPValue::LocationType::Any>( 115 DbgUsers, V, DPValues); 116 } 117 118 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) { 119 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope)) 120 return LocalScope->getSubprogram(); 121 return nullptr; 122 } 123 124 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) { 125 // Original dbg.declare must have a location. 126 const DebugLoc &DeclareLoc = DII->getDebugLoc(); 127 MDNode *Scope = DeclareLoc.getScope(); 128 DILocation *InlinedAt = DeclareLoc.getInlinedAt(); 129 // Because no machine insts can come from debug intrinsics, only the scope 130 // and inlinedAt is significant. Zero line numbers are used in case this 131 // DebugLoc leaks into any adjacent instructions. Produce an unknown location 132 // with the correct scope / inlinedAt fields. 133 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt); 134 } 135 136 //===----------------------------------------------------------------------===// 137 // DebugInfoFinder implementations. 138 //===----------------------------------------------------------------------===// 139 140 void DebugInfoFinder::reset() { 141 CUs.clear(); 142 SPs.clear(); 143 GVs.clear(); 144 TYs.clear(); 145 Scopes.clear(); 146 NodesSeen.clear(); 147 } 148 149 void DebugInfoFinder::processModule(const Module &M) { 150 for (auto *CU : M.debug_compile_units()) 151 processCompileUnit(CU); 152 for (auto &F : M.functions()) { 153 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram())) 154 processSubprogram(SP); 155 // There could be subprograms from inlined functions referenced from 156 // instructions only. Walk the function to find them. 157 for (const BasicBlock &BB : F) 158 for (const Instruction &I : BB) 159 processInstruction(M, I); 160 } 161 } 162 163 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) { 164 if (!addCompileUnit(CU)) 165 return; 166 for (auto *DIG : CU->getGlobalVariables()) { 167 if (!addGlobalVariable(DIG)) 168 continue; 169 auto *GV = DIG->getVariable(); 170 processScope(GV->getScope()); 171 processType(GV->getType()); 172 } 173 for (auto *ET : CU->getEnumTypes()) 174 processType(ET); 175 for (auto *RT : CU->getRetainedTypes()) 176 if (auto *T = dyn_cast<DIType>(RT)) 177 processType(T); 178 else 179 processSubprogram(cast<DISubprogram>(RT)); 180 for (auto *Import : CU->getImportedEntities()) { 181 auto *Entity = Import->getEntity(); 182 if (auto *T = dyn_cast<DIType>(Entity)) 183 processType(T); 184 else if (auto *SP = dyn_cast<DISubprogram>(Entity)) 185 processSubprogram(SP); 186 else if (auto *NS = dyn_cast<DINamespace>(Entity)) 187 processScope(NS->getScope()); 188 else if (auto *M = dyn_cast<DIModule>(Entity)) 189 processScope(M->getScope()); 190 } 191 } 192 193 void DebugInfoFinder::processInstruction(const Module &M, 194 const Instruction &I) { 195 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) 196 processVariable(M, DVI->getVariable()); 197 198 if (auto DbgLoc = I.getDebugLoc()) 199 processLocation(M, DbgLoc.get()); 200 201 for (const DPValue &DPV : I.getDbgValueRange()) 202 processDPValue(M, DPV); 203 } 204 205 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) { 206 if (!Loc) 207 return; 208 processScope(Loc->getScope()); 209 processLocation(M, Loc->getInlinedAt()); 210 } 211 212 void DebugInfoFinder::processDPValue(const Module &M, const DPValue &DPV) { 213 processVariable(M, DPV.getVariable()); 214 processLocation(M, DPV.getDebugLoc().get()); 215 } 216 217 void DebugInfoFinder::processType(DIType *DT) { 218 if (!addType(DT)) 219 return; 220 processScope(DT->getScope()); 221 if (auto *ST = dyn_cast<DISubroutineType>(DT)) { 222 for (DIType *Ref : ST->getTypeArray()) 223 processType(Ref); 224 return; 225 } 226 if (auto *DCT = dyn_cast<DICompositeType>(DT)) { 227 processType(DCT->getBaseType()); 228 for (Metadata *D : DCT->getElements()) { 229 if (auto *T = dyn_cast<DIType>(D)) 230 processType(T); 231 else if (auto *SP = dyn_cast<DISubprogram>(D)) 232 processSubprogram(SP); 233 } 234 return; 235 } 236 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) { 237 processType(DDT->getBaseType()); 238 } 239 } 240 241 void DebugInfoFinder::processScope(DIScope *Scope) { 242 if (!Scope) 243 return; 244 if (auto *Ty = dyn_cast<DIType>(Scope)) { 245 processType(Ty); 246 return; 247 } 248 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) { 249 addCompileUnit(CU); 250 return; 251 } 252 if (auto *SP = dyn_cast<DISubprogram>(Scope)) { 253 processSubprogram(SP); 254 return; 255 } 256 if (!addScope(Scope)) 257 return; 258 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) { 259 processScope(LB->getScope()); 260 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) { 261 processScope(NS->getScope()); 262 } else if (auto *M = dyn_cast<DIModule>(Scope)) { 263 processScope(M->getScope()); 264 } 265 } 266 267 void DebugInfoFinder::processSubprogram(DISubprogram *SP) { 268 if (!addSubprogram(SP)) 269 return; 270 processScope(SP->getScope()); 271 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a 272 // ValueMap containing identity mappings for all of the DICompileUnit's, not 273 // just DISubprogram's, referenced from anywhere within the Function being 274 // cloned prior to calling MapMetadata / RemapInstruction to avoid their 275 // duplication later as DICompileUnit's are also directly referenced by 276 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well. 277 // Also, DICompileUnit's may reference DISubprogram's too and therefore need 278 // to be at least looked through. 279 processCompileUnit(SP->getUnit()); 280 processType(SP->getType()); 281 for (auto *Element : SP->getTemplateParams()) { 282 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) { 283 processType(TType->getType()); 284 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) { 285 processType(TVal->getType()); 286 } 287 } 288 } 289 290 void DebugInfoFinder::processVariable(const Module &M, 291 const DILocalVariable *DV) { 292 if (!NodesSeen.insert(DV).second) 293 return; 294 processScope(DV->getScope()); 295 processType(DV->getType()); 296 } 297 298 bool DebugInfoFinder::addType(DIType *DT) { 299 if (!DT) 300 return false; 301 302 if (!NodesSeen.insert(DT).second) 303 return false; 304 305 TYs.push_back(const_cast<DIType *>(DT)); 306 return true; 307 } 308 309 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) { 310 if (!CU) 311 return false; 312 if (!NodesSeen.insert(CU).second) 313 return false; 314 315 CUs.push_back(CU); 316 return true; 317 } 318 319 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) { 320 if (!NodesSeen.insert(DIG).second) 321 return false; 322 323 GVs.push_back(DIG); 324 return true; 325 } 326 327 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) { 328 if (!SP) 329 return false; 330 331 if (!NodesSeen.insert(SP).second) 332 return false; 333 334 SPs.push_back(SP); 335 return true; 336 } 337 338 bool DebugInfoFinder::addScope(DIScope *Scope) { 339 if (!Scope) 340 return false; 341 // FIXME: Ocaml binding generates a scope with no content, we treat it 342 // as null for now. 343 if (Scope->getNumOperands() == 0) 344 return false; 345 if (!NodesSeen.insert(Scope).second) 346 return false; 347 Scopes.push_back(Scope); 348 return true; 349 } 350 351 static MDNode *updateLoopMetadataDebugLocationsImpl( 352 MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) { 353 assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 && 354 "Loop ID needs at least one operand"); 355 assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID && 356 "Loop ID should refer to itself"); 357 358 // Save space for the self-referential LoopID. 359 SmallVector<Metadata *, 4> MDs = {nullptr}; 360 361 for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) { 362 Metadata *MD = OrigLoopID->getOperand(i); 363 if (!MD) 364 MDs.push_back(nullptr); 365 else if (Metadata *NewMD = Updater(MD)) 366 MDs.push_back(NewMD); 367 } 368 369 MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs); 370 // Insert the self-referential LoopID. 371 NewLoopID->replaceOperandWith(0, NewLoopID); 372 return NewLoopID; 373 } 374 375 void llvm::updateLoopMetadataDebugLocations( 376 Instruction &I, function_ref<Metadata *(Metadata *)> Updater) { 377 MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop); 378 if (!OrigLoopID) 379 return; 380 MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater); 381 I.setMetadata(LLVMContext::MD_loop, NewLoopID); 382 } 383 384 /// Return true if a node is a DILocation or if a DILocation is 385 /// indirectly referenced by one of the node's children. 386 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited, 387 SmallPtrSetImpl<Metadata *> &Reachable, 388 Metadata *MD) { 389 MDNode *N = dyn_cast_or_null<MDNode>(MD); 390 if (!N) 391 return false; 392 if (isa<DILocation>(N) || Reachable.count(N)) 393 return true; 394 if (!Visited.insert(N).second) 395 return false; 396 for (auto &OpIt : N->operands()) { 397 Metadata *Op = OpIt.get(); 398 if (isDILocationReachable(Visited, Reachable, Op)) { 399 // Don't return just yet as we want to visit all MD's children to 400 // initialize DILocationReachable in stripDebugLocFromLoopID 401 Reachable.insert(N); 402 } 403 } 404 return Reachable.count(N); 405 } 406 407 static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited, 408 SmallPtrSetImpl<Metadata *> &AllDILocation, 409 const SmallPtrSetImpl<Metadata *> &DIReachable, 410 Metadata *MD) { 411 MDNode *N = dyn_cast_or_null<MDNode>(MD); 412 if (!N) 413 return false; 414 if (isa<DILocation>(N) || AllDILocation.count(N)) 415 return true; 416 if (!DIReachable.count(N)) 417 return false; 418 if (!Visited.insert(N).second) 419 return false; 420 for (auto &OpIt : N->operands()) { 421 Metadata *Op = OpIt.get(); 422 if (Op == MD) 423 continue; 424 if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) { 425 return false; 426 } 427 } 428 AllDILocation.insert(N); 429 return true; 430 } 431 432 static Metadata * 433 stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation, 434 const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) { 435 if (isa<DILocation>(MD) || AllDILocation.count(MD)) 436 return nullptr; 437 438 if (!DIReachable.count(MD)) 439 return MD; 440 441 MDNode *N = dyn_cast_or_null<MDNode>(MD); 442 if (!N) 443 return MD; 444 445 SmallVector<Metadata *, 4> Args; 446 bool HasSelfRef = false; 447 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 448 Metadata *A = N->getOperand(i); 449 if (!A) { 450 Args.push_back(nullptr); 451 } else if (A == MD) { 452 assert(i == 0 && "expected i==0 for self-reference"); 453 HasSelfRef = true; 454 Args.push_back(nullptr); 455 } else if (Metadata *NewArg = 456 stripLoopMDLoc(AllDILocation, DIReachable, A)) { 457 Args.push_back(NewArg); 458 } 459 } 460 if (Args.empty() || (HasSelfRef && Args.size() == 1)) 461 return nullptr; 462 463 MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args) 464 : MDNode::get(N->getContext(), Args); 465 if (HasSelfRef) 466 NewMD->replaceOperandWith(0, NewMD); 467 return NewMD; 468 } 469 470 static MDNode *stripDebugLocFromLoopID(MDNode *N) { 471 assert(!N->operands().empty() && "Missing self reference?"); 472 SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation; 473 // If we already visited N, there is nothing to do. 474 if (!Visited.insert(N).second) 475 return N; 476 477 // If there is no debug location, we do not have to rewrite this 478 // MDNode. This loop also initializes DILocationReachable, later 479 // needed by updateLoopMetadataDebugLocationsImpl; the use of 480 // count_if avoids an early exit. 481 if (!llvm::count_if(llvm::drop_begin(N->operands()), 482 [&Visited, &DILocationReachable](const MDOperand &Op) { 483 return isDILocationReachable( 484 Visited, DILocationReachable, Op.get()); 485 })) 486 return N; 487 488 Visited.clear(); 489 // If there is only the debug location without any actual loop metadata, we 490 // can remove the metadata. 491 if (llvm::all_of(llvm::drop_begin(N->operands()), 492 [&Visited, &AllDILocation, 493 &DILocationReachable](const MDOperand &Op) { 494 return isAllDILocation(Visited, AllDILocation, 495 DILocationReachable, Op.get()); 496 })) 497 return nullptr; 498 499 return updateLoopMetadataDebugLocationsImpl( 500 N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * { 501 return stripLoopMDLoc(AllDILocation, DILocationReachable, MD); 502 }); 503 } 504 505 bool llvm::stripDebugInfo(Function &F) { 506 bool Changed = false; 507 if (F.hasMetadata(LLVMContext::MD_dbg)) { 508 Changed = true; 509 F.setSubprogram(nullptr); 510 } 511 512 DenseMap<MDNode *, MDNode *> LoopIDsMap; 513 for (BasicBlock &BB : F) { 514 for (Instruction &I : llvm::make_early_inc_range(BB)) { 515 if (isa<DbgInfoIntrinsic>(&I)) { 516 I.eraseFromParent(); 517 Changed = true; 518 continue; 519 } 520 if (I.getDebugLoc()) { 521 Changed = true; 522 I.setDebugLoc(DebugLoc()); 523 } 524 if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) { 525 auto *NewLoopID = LoopIDsMap.lookup(LoopID); 526 if (!NewLoopID) 527 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID); 528 if (NewLoopID != LoopID) 529 I.setMetadata(LLVMContext::MD_loop, NewLoopID); 530 } 531 // Strip other attachments that are or use debug info. 532 if (I.hasMetadataOtherThanDebugLoc()) { 533 // Heapallocsites point into the DIType system. 534 I.setMetadata("heapallocsite", nullptr); 535 // DIAssignID are debug info metadata primitives. 536 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr); 537 } 538 I.dropDbgValues(); 539 } 540 } 541 return Changed; 542 } 543 544 bool llvm::StripDebugInfo(Module &M) { 545 bool Changed = false; 546 547 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) { 548 // We're stripping debug info, and without them, coverage information 549 // doesn't quite make sense. 550 if (NMD.getName().starts_with("llvm.dbg.") || 551 NMD.getName() == "llvm.gcov") { 552 NMD.eraseFromParent(); 553 Changed = true; 554 } 555 } 556 557 for (Function &F : M) 558 Changed |= stripDebugInfo(F); 559 560 for (auto &GV : M.globals()) { 561 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg); 562 } 563 564 if (GVMaterializer *Materializer = M.getMaterializer()) 565 Materializer->setStripDebugInfo(); 566 567 return Changed; 568 } 569 570 namespace { 571 572 /// Helper class to downgrade -g metadata to -gline-tables-only metadata. 573 class DebugTypeInfoRemoval { 574 DenseMap<Metadata *, Metadata *> Replacements; 575 576 public: 577 /// The (void)() type. 578 MDNode *EmptySubroutineType; 579 580 private: 581 /// Remember what linkage name we originally had before stripping. If we end 582 /// up making two subprograms identical who originally had different linkage 583 /// names, then we need to make one of them distinct, to avoid them getting 584 /// uniqued. Maps the new node to the old linkage name. 585 DenseMap<DISubprogram *, StringRef> NewToLinkageName; 586 587 // TODO: Remember the distinct subprogram we created for a given linkage name, 588 // so that we can continue to unique whenever possible. Map <newly created 589 // node, old linkage name> to the first (possibly distinct) mdsubprogram 590 // created for that combination. This is not strictly needed for correctness, 591 // but can cut down on the number of MDNodes and let us diff cleanly with the 592 // output of -gline-tables-only. 593 594 public: 595 DebugTypeInfoRemoval(LLVMContext &C) 596 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0, 597 MDNode::get(C, {}))) {} 598 599 Metadata *map(Metadata *M) { 600 if (!M) 601 return nullptr; 602 auto Replacement = Replacements.find(M); 603 if (Replacement != Replacements.end()) 604 return Replacement->second; 605 606 return M; 607 } 608 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); } 609 610 /// Recursively remap N and all its referenced children. Does a DF post-order 611 /// traversal, so as to remap bottoms up. 612 void traverseAndRemap(MDNode *N) { traverse(N); } 613 614 private: 615 // Create a new DISubprogram, to replace the one given. 616 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) { 617 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile())); 618 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : ""; 619 DISubprogram *Declaration = nullptr; 620 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType())); 621 DIType *ContainingType = 622 cast_or_null<DIType>(map(MDS->getContainingType())); 623 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit())); 624 auto Variables = nullptr; 625 auto TemplateParams = nullptr; 626 627 // Make a distinct DISubprogram, for situations that warrent it. 628 auto distinctMDSubprogram = [&]() { 629 return DISubprogram::getDistinct( 630 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 631 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), 632 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(), 633 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration, 634 Variables); 635 }; 636 637 if (MDS->isDistinct()) 638 return distinctMDSubprogram(); 639 640 auto *NewMDS = DISubprogram::get( 641 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName, 642 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType, 643 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(), 644 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables); 645 646 StringRef OldLinkageName = MDS->getLinkageName(); 647 648 // See if we need to make a distinct one. 649 auto OrigLinkage = NewToLinkageName.find(NewMDS); 650 if (OrigLinkage != NewToLinkageName.end()) { 651 if (OrigLinkage->second == OldLinkageName) 652 // We're good. 653 return NewMDS; 654 655 // Otherwise, need to make a distinct one. 656 // TODO: Query the map to see if we already have one. 657 return distinctMDSubprogram(); 658 } 659 660 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()}); 661 return NewMDS; 662 } 663 664 /// Create a new compile unit, to replace the one given 665 DICompileUnit *getReplacementCU(DICompileUnit *CU) { 666 // Drop skeleton CUs. 667 if (CU->getDWOId()) 668 return nullptr; 669 670 auto *File = cast_or_null<DIFile>(map(CU->getFile())); 671 MDTuple *EnumTypes = nullptr; 672 MDTuple *RetainedTypes = nullptr; 673 MDTuple *GlobalVariables = nullptr; 674 MDTuple *ImportedEntities = nullptr; 675 return DICompileUnit::getDistinct( 676 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(), 677 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(), 678 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes, 679 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(), 680 CU->getDWOId(), CU->getSplitDebugInlining(), 681 CU->getDebugInfoForProfiling(), CU->getNameTableKind(), 682 CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK()); 683 } 684 685 DILocation *getReplacementMDLocation(DILocation *MLD) { 686 auto *Scope = map(MLD->getScope()); 687 auto *InlinedAt = map(MLD->getInlinedAt()); 688 if (MLD->isDistinct()) 689 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(), 690 MLD->getColumn(), Scope, InlinedAt); 691 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(), 692 Scope, InlinedAt); 693 } 694 695 /// Create a new generic MDNode, to replace the one given 696 MDNode *getReplacementMDNode(MDNode *N) { 697 SmallVector<Metadata *, 8> Ops; 698 Ops.reserve(N->getNumOperands()); 699 for (auto &I : N->operands()) 700 if (I) 701 Ops.push_back(map(I)); 702 auto *Ret = MDNode::get(N->getContext(), Ops); 703 return Ret; 704 } 705 706 /// Attempt to re-map N to a newly created node. 707 void remap(MDNode *N) { 708 if (Replacements.count(N)) 709 return; 710 711 auto doRemap = [&](MDNode *N) -> MDNode * { 712 if (!N) 713 return nullptr; 714 if (auto *MDSub = dyn_cast<DISubprogram>(N)) { 715 remap(MDSub->getUnit()); 716 return getReplacementSubprogram(MDSub); 717 } 718 if (isa<DISubroutineType>(N)) 719 return EmptySubroutineType; 720 if (auto *CU = dyn_cast<DICompileUnit>(N)) 721 return getReplacementCU(CU); 722 if (isa<DIFile>(N)) 723 return N; 724 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N)) 725 // Remap to our referenced scope (recursively). 726 return mapNode(MDLB->getScope()); 727 if (auto *MLD = dyn_cast<DILocation>(N)) 728 return getReplacementMDLocation(MLD); 729 730 // Otherwise, if we see these, just drop them now. Not strictly necessary, 731 // but this speeds things up a little. 732 if (isa<DINode>(N)) 733 return nullptr; 734 735 return getReplacementMDNode(N); 736 }; 737 Replacements[N] = doRemap(N); 738 } 739 740 /// Do the remapping traversal. 741 void traverse(MDNode *); 742 }; 743 744 } // end anonymous namespace 745 746 void DebugTypeInfoRemoval::traverse(MDNode *N) { 747 if (!N || Replacements.count(N)) 748 return; 749 750 // To avoid cycles, as well as for efficiency sake, we will sometimes prune 751 // parts of the graph. 752 auto prune = [](MDNode *Parent, MDNode *Child) { 753 if (auto *MDS = dyn_cast<DISubprogram>(Parent)) 754 return Child == MDS->getRetainedNodes().get(); 755 return false; 756 }; 757 758 SmallVector<MDNode *, 16> ToVisit; 759 DenseSet<MDNode *> Opened; 760 761 // Visit each node starting at N in post order, and map them. 762 ToVisit.push_back(N); 763 while (!ToVisit.empty()) { 764 auto *N = ToVisit.back(); 765 if (!Opened.insert(N).second) { 766 // Close it. 767 remap(N); 768 ToVisit.pop_back(); 769 continue; 770 } 771 for (auto &I : N->operands()) 772 if (auto *MDN = dyn_cast_or_null<MDNode>(I)) 773 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) && 774 !isa<DICompileUnit>(MDN)) 775 ToVisit.push_back(MDN); 776 } 777 } 778 779 bool llvm::stripNonLineTableDebugInfo(Module &M) { 780 bool Changed = false; 781 782 // First off, delete the debug intrinsics. 783 auto RemoveUses = [&](StringRef Name) { 784 if (auto *DbgVal = M.getFunction(Name)) { 785 while (!DbgVal->use_empty()) 786 cast<Instruction>(DbgVal->user_back())->eraseFromParent(); 787 DbgVal->eraseFromParent(); 788 Changed = true; 789 } 790 }; 791 RemoveUses("llvm.dbg.declare"); 792 RemoveUses("llvm.dbg.label"); 793 RemoveUses("llvm.dbg.value"); 794 795 // Delete non-CU debug info named metadata nodes. 796 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end(); 797 NMI != NME;) { 798 NamedMDNode *NMD = &*NMI; 799 ++NMI; 800 // Specifically keep dbg.cu around. 801 if (NMD->getName() == "llvm.dbg.cu") 802 continue; 803 } 804 805 // Drop all dbg attachments from global variables. 806 for (auto &GV : M.globals()) 807 GV.eraseMetadata(LLVMContext::MD_dbg); 808 809 DebugTypeInfoRemoval Mapper(M.getContext()); 810 auto remap = [&](MDNode *Node) -> MDNode * { 811 if (!Node) 812 return nullptr; 813 Mapper.traverseAndRemap(Node); 814 auto *NewNode = Mapper.mapNode(Node); 815 Changed |= Node != NewNode; 816 Node = NewNode; 817 return NewNode; 818 }; 819 820 // Rewrite the DebugLocs to be equivalent to what 821 // -gline-tables-only would have created. 822 for (auto &F : M) { 823 if (auto *SP = F.getSubprogram()) { 824 Mapper.traverseAndRemap(SP); 825 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP)); 826 Changed |= SP != NewSP; 827 F.setSubprogram(NewSP); 828 } 829 for (auto &BB : F) { 830 for (auto &I : BB) { 831 auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc { 832 auto *Scope = DL.getScope(); 833 MDNode *InlinedAt = DL.getInlinedAt(); 834 Scope = remap(Scope); 835 InlinedAt = remap(InlinedAt); 836 return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(), 837 Scope, InlinedAt); 838 }; 839 840 if (I.getDebugLoc() != DebugLoc()) 841 I.setDebugLoc(remapDebugLoc(I.getDebugLoc())); 842 843 // Remap DILocations in llvm.loop attachments. 844 updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * { 845 if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 846 return remapDebugLoc(Loc).get(); 847 return MD; 848 }); 849 850 // Strip heapallocsite attachments, they point into the DIType system. 851 if (I.hasMetadataOtherThanDebugLoc()) 852 I.setMetadata("heapallocsite", nullptr); 853 } 854 } 855 } 856 857 // Create a new llvm.dbg.cu, which is equivalent to the one 858 // -gline-tables-only would have created. 859 for (auto &NMD : M.named_metadata()) { 860 SmallVector<MDNode *, 8> Ops; 861 for (MDNode *Op : NMD.operands()) 862 Ops.push_back(remap(Op)); 863 864 if (!Changed) 865 continue; 866 867 NMD.clearOperands(); 868 for (auto *Op : Ops) 869 if (Op) 870 NMD.addOperand(Op); 871 } 872 return Changed; 873 } 874 875 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) { 876 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>( 877 M.getModuleFlag("Debug Info Version"))) 878 return Val->getZExtValue(); 879 return 0; 880 } 881 882 void Instruction::applyMergedLocation(DILocation *LocA, DILocation *LocB) { 883 setDebugLoc(DILocation::getMergedLocation(LocA, LocB)); 884 } 885 886 void Instruction::mergeDIAssignID( 887 ArrayRef<const Instruction *> SourceInstructions) { 888 // Replace all uses (and attachments) of all the DIAssignIDs 889 // on SourceInstructions with a single merged value. 890 assert(getFunction() && "Uninserted instruction merged"); 891 // Collect up the DIAssignID tags. 892 SmallVector<DIAssignID *, 4> IDs; 893 for (const Instruction *I : SourceInstructions) { 894 if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID)) 895 IDs.push_back(cast<DIAssignID>(MD)); 896 assert(getFunction() == I->getFunction() && 897 "Merging with instruction from another function not allowed"); 898 } 899 900 // Add this instruction's DIAssignID too, if it has one. 901 if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID)) 902 IDs.push_back(cast<DIAssignID>(MD)); 903 904 if (IDs.empty()) 905 return; // No DIAssignID tags to process. 906 907 DIAssignID *MergeID = IDs[0]; 908 for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) { 909 if (*It != MergeID) 910 at::RAUW(*It, MergeID); 911 } 912 setMetadata(LLVMContext::MD_DIAssignID, MergeID); 913 } 914 915 void Instruction::updateLocationAfterHoist() { dropLocation(); } 916 917 void Instruction::dropLocation() { 918 const DebugLoc &DL = getDebugLoc(); 919 if (!DL) 920 return; 921 922 // If this isn't a call, drop the location to allow a location from a 923 // preceding instruction to propagate. 924 bool MayLowerToCall = false; 925 if (isa<CallBase>(this)) { 926 auto *II = dyn_cast<IntrinsicInst>(this); 927 MayLowerToCall = 928 !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID()); 929 } 930 931 if (!MayLowerToCall) { 932 setDebugLoc(DebugLoc()); 933 return; 934 } 935 936 // Set a line 0 location for calls to preserve scope information in case 937 // inlining occurs. 938 DISubprogram *SP = getFunction()->getSubprogram(); 939 if (SP) 940 // If a function scope is available, set it on the line 0 location. When 941 // hoisting a call to a predecessor block, using the function scope avoids 942 // making it look like the callee was reached earlier than it should be. 943 setDebugLoc(DILocation::get(getContext(), 0, 0, SP)); 944 else 945 // The parent function has no scope. Go ahead and drop the location. If 946 // the parent function is inlined, and the callee has a subprogram, the 947 // inliner will attach a location to the call. 948 // 949 // One alternative is to set a line 0 location with the existing scope and 950 // inlinedAt info. The location might be sensitive to when inlining occurs. 951 setDebugLoc(DebugLoc()); 952 } 953 954 //===----------------------------------------------------------------------===// 955 // LLVM C API implementations. 956 //===----------------------------------------------------------------------===// 957 958 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) { 959 switch (lang) { 960 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \ 961 case LLVMDWARFSourceLanguage##NAME: \ 962 return ID; 963 #include "llvm/BinaryFormat/Dwarf.def" 964 #undef HANDLE_DW_LANG 965 } 966 llvm_unreachable("Unhandled Tag"); 967 } 968 969 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) { 970 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr); 971 } 972 973 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) { 974 return static_cast<DINode::DIFlags>(Flags); 975 } 976 977 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) { 978 return static_cast<LLVMDIFlags>(Flags); 979 } 980 981 static DISubprogram::DISPFlags 982 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) { 983 return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized); 984 } 985 986 unsigned LLVMDebugMetadataVersion() { 987 return DEBUG_METADATA_VERSION; 988 } 989 990 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) { 991 return wrap(new DIBuilder(*unwrap(M), false)); 992 } 993 994 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) { 995 return wrap(new DIBuilder(*unwrap(M))); 996 } 997 998 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) { 999 return getDebugMetadataVersionFromModule(*unwrap(M)); 1000 } 1001 1002 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) { 1003 return StripDebugInfo(*unwrap(M)); 1004 } 1005 1006 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) { 1007 delete unwrap(Builder); 1008 } 1009 1010 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) { 1011 unwrap(Builder)->finalize(); 1012 } 1013 1014 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder, 1015 LLVMMetadataRef subprogram) { 1016 unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram)); 1017 } 1018 1019 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit( 1020 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang, 1021 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen, 1022 LLVMBool isOptimized, const char *Flags, size_t FlagsLen, 1023 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen, 1024 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining, 1025 LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen, 1026 const char *SDK, size_t SDKLen) { 1027 auto File = unwrapDI<DIFile>(FileRef); 1028 1029 return wrap(unwrap(Builder)->createCompileUnit( 1030 map_from_llvmDWARFsourcelanguage(Lang), File, 1031 StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen), 1032 RuntimeVer, StringRef(SplitName, SplitNameLen), 1033 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId, 1034 SplitDebugInlining, DebugInfoForProfiling, 1035 DICompileUnit::DebugNameTableKind::Default, false, 1036 StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen))); 1037 } 1038 1039 LLVMMetadataRef 1040 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename, 1041 size_t FilenameLen, const char *Directory, 1042 size_t DirectoryLen) { 1043 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen), 1044 StringRef(Directory, DirectoryLen))); 1045 } 1046 1047 LLVMMetadataRef 1048 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope, 1049 const char *Name, size_t NameLen, 1050 const char *ConfigMacros, size_t ConfigMacrosLen, 1051 const char *IncludePath, size_t IncludePathLen, 1052 const char *APINotesFile, size_t APINotesFileLen) { 1053 return wrap(unwrap(Builder)->createModule( 1054 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), 1055 StringRef(ConfigMacros, ConfigMacrosLen), 1056 StringRef(IncludePath, IncludePathLen), 1057 StringRef(APINotesFile, APINotesFileLen))); 1058 } 1059 1060 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder, 1061 LLVMMetadataRef ParentScope, 1062 const char *Name, size_t NameLen, 1063 LLVMBool ExportSymbols) { 1064 return wrap(unwrap(Builder)->createNameSpace( 1065 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols)); 1066 } 1067 1068 LLVMMetadataRef LLVMDIBuilderCreateFunction( 1069 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1070 size_t NameLen, const char *LinkageName, size_t LinkageNameLen, 1071 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, 1072 LLVMBool IsLocalToUnit, LLVMBool IsDefinition, 1073 unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) { 1074 return wrap(unwrap(Builder)->createFunction( 1075 unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen}, 1076 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine, 1077 map_from_llvmDIFlags(Flags), 1078 pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr, 1079 nullptr, nullptr)); 1080 } 1081 1082 1083 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock( 1084 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, 1085 LLVMMetadataRef File, unsigned Line, unsigned Col) { 1086 return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope), 1087 unwrapDI<DIFile>(File), 1088 Line, Col)); 1089 } 1090 1091 LLVMMetadataRef 1092 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder, 1093 LLVMMetadataRef Scope, 1094 LLVMMetadataRef File, 1095 unsigned Discriminator) { 1096 return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope), 1097 unwrapDI<DIFile>(File), 1098 Discriminator)); 1099 } 1100 1101 LLVMMetadataRef 1102 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder, 1103 LLVMMetadataRef Scope, 1104 LLVMMetadataRef NS, 1105 LLVMMetadataRef File, 1106 unsigned Line) { 1107 return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope), 1108 unwrapDI<DINamespace>(NS), 1109 unwrapDI<DIFile>(File), 1110 Line)); 1111 } 1112 1113 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias( 1114 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, 1115 LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line, 1116 LLVMMetadataRef *Elements, unsigned NumElements) { 1117 auto Elts = 1118 (NumElements > 0) 1119 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1120 : nullptr; 1121 return wrap(unwrap(Builder)->createImportedModule( 1122 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity), 1123 unwrapDI<DIFile>(File), Line, Elts)); 1124 } 1125 1126 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule( 1127 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M, 1128 LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements, 1129 unsigned NumElements) { 1130 auto Elts = 1131 (NumElements > 0) 1132 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1133 : nullptr; 1134 return wrap(unwrap(Builder)->createImportedModule( 1135 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File), 1136 Line, Elts)); 1137 } 1138 1139 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration( 1140 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl, 1141 LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen, 1142 LLVMMetadataRef *Elements, unsigned NumElements) { 1143 auto Elts = 1144 (NumElements > 0) 1145 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements}) 1146 : nullptr; 1147 return wrap(unwrap(Builder)->createImportedDeclaration( 1148 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File), 1149 Line, {Name, NameLen}, Elts)); 1150 } 1151 1152 LLVMMetadataRef 1153 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line, 1154 unsigned Column, LLVMMetadataRef Scope, 1155 LLVMMetadataRef InlinedAt) { 1156 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope), 1157 unwrap(InlinedAt))); 1158 } 1159 1160 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) { 1161 return unwrapDI<DILocation>(Location)->getLine(); 1162 } 1163 1164 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) { 1165 return unwrapDI<DILocation>(Location)->getColumn(); 1166 } 1167 1168 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) { 1169 return wrap(unwrapDI<DILocation>(Location)->getScope()); 1170 } 1171 1172 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) { 1173 return wrap(unwrapDI<DILocation>(Location)->getInlinedAt()); 1174 } 1175 1176 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) { 1177 return wrap(unwrapDI<DIScope>(Scope)->getFile()); 1178 } 1179 1180 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) { 1181 auto Dir = unwrapDI<DIFile>(File)->getDirectory(); 1182 *Len = Dir.size(); 1183 return Dir.data(); 1184 } 1185 1186 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) { 1187 auto Name = unwrapDI<DIFile>(File)->getFilename(); 1188 *Len = Name.size(); 1189 return Name.data(); 1190 } 1191 1192 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) { 1193 if (auto Src = unwrapDI<DIFile>(File)->getSource()) { 1194 *Len = Src->size(); 1195 return Src->data(); 1196 } 1197 *Len = 0; 1198 return ""; 1199 } 1200 1201 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder, 1202 LLVMMetadataRef ParentMacroFile, 1203 unsigned Line, 1204 LLVMDWARFMacinfoRecordType RecordType, 1205 const char *Name, size_t NameLen, 1206 const char *Value, size_t ValueLen) { 1207 return wrap( 1208 unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line, 1209 static_cast<MacinfoRecordType>(RecordType), 1210 {Name, NameLen}, {Value, ValueLen})); 1211 } 1212 1213 LLVMMetadataRef 1214 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder, 1215 LLVMMetadataRef ParentMacroFile, unsigned Line, 1216 LLVMMetadataRef File) { 1217 return wrap(unwrap(Builder)->createTempMacroFile( 1218 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File))); 1219 } 1220 1221 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder, 1222 const char *Name, size_t NameLen, 1223 int64_t Value, 1224 LLVMBool IsUnsigned) { 1225 return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value, 1226 IsUnsigned != 0)); 1227 } 1228 1229 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType( 1230 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1231 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1232 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements, 1233 unsigned NumElements, LLVMMetadataRef ClassTy) { 1234 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1235 NumElements}); 1236 return wrap(unwrap(Builder)->createEnumerationType( 1237 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1238 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy))); 1239 } 1240 1241 LLVMMetadataRef LLVMDIBuilderCreateUnionType( 1242 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1243 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1244 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, 1245 LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang, 1246 const char *UniqueId, size_t UniqueIdLen) { 1247 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1248 NumElements}); 1249 return wrap(unwrap(Builder)->createUnionType( 1250 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1251 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags), 1252 Elts, RunTimeLang, {UniqueId, UniqueIdLen})); 1253 } 1254 1255 1256 LLVMMetadataRef 1257 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size, 1258 uint32_t AlignInBits, LLVMMetadataRef Ty, 1259 LLVMMetadataRef *Subscripts, 1260 unsigned NumSubscripts) { 1261 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts), 1262 NumSubscripts}); 1263 return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits, 1264 unwrapDI<DIType>(Ty), Subs)); 1265 } 1266 1267 LLVMMetadataRef 1268 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size, 1269 uint32_t AlignInBits, LLVMMetadataRef Ty, 1270 LLVMMetadataRef *Subscripts, 1271 unsigned NumSubscripts) { 1272 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts), 1273 NumSubscripts}); 1274 return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits, 1275 unwrapDI<DIType>(Ty), Subs)); 1276 } 1277 1278 LLVMMetadataRef 1279 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name, 1280 size_t NameLen, uint64_t SizeInBits, 1281 LLVMDWARFTypeEncoding Encoding, 1282 LLVMDIFlags Flags) { 1283 return wrap(unwrap(Builder)->createBasicType({Name, NameLen}, 1284 SizeInBits, Encoding, 1285 map_from_llvmDIFlags(Flags))); 1286 } 1287 1288 LLVMMetadataRef LLVMDIBuilderCreatePointerType( 1289 LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy, 1290 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, 1291 const char *Name, size_t NameLen) { 1292 return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy), 1293 SizeInBits, AlignInBits, 1294 AddressSpace, {Name, NameLen})); 1295 } 1296 1297 LLVMMetadataRef LLVMDIBuilderCreateStructType( 1298 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1299 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1300 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags, 1301 LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements, 1302 unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder, 1303 const char *UniqueId, size_t UniqueIdLen) { 1304 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1305 NumElements}); 1306 return wrap(unwrap(Builder)->createStructType( 1307 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1308 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags), 1309 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang, 1310 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen})); 1311 } 1312 1313 LLVMMetadataRef LLVMDIBuilderCreateMemberType( 1314 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1315 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, 1316 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, 1317 LLVMMetadataRef Ty) { 1318 return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope), 1319 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits, 1320 OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty))); 1321 } 1322 1323 LLVMMetadataRef 1324 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name, 1325 size_t NameLen) { 1326 return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen})); 1327 } 1328 1329 LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType( 1330 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1331 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, 1332 LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal, 1333 uint32_t AlignInBits) { 1334 return wrap(unwrap(Builder)->createStaticMemberType( 1335 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1336 LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags), 1337 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits)); 1338 } 1339 1340 LLVMMetadataRef 1341 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder, 1342 const char *Name, size_t NameLen, 1343 LLVMMetadataRef File, unsigned LineNo, 1344 uint64_t SizeInBits, uint32_t AlignInBits, 1345 uint64_t OffsetInBits, LLVMDIFlags Flags, 1346 LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) { 1347 return wrap(unwrap(Builder)->createObjCIVar( 1348 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1349 SizeInBits, AlignInBits, OffsetInBits, 1350 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty), 1351 unwrapDI<MDNode>(PropertyNode))); 1352 } 1353 1354 LLVMMetadataRef 1355 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder, 1356 const char *Name, size_t NameLen, 1357 LLVMMetadataRef File, unsigned LineNo, 1358 const char *GetterName, size_t GetterNameLen, 1359 const char *SetterName, size_t SetterNameLen, 1360 unsigned PropertyAttributes, 1361 LLVMMetadataRef Ty) { 1362 return wrap(unwrap(Builder)->createObjCProperty( 1363 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1364 {GetterName, GetterNameLen}, {SetterName, SetterNameLen}, 1365 PropertyAttributes, unwrapDI<DIType>(Ty))); 1366 } 1367 1368 LLVMMetadataRef 1369 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder, 1370 LLVMMetadataRef Type) { 1371 return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type))); 1372 } 1373 1374 LLVMMetadataRef 1375 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type, 1376 const char *Name, size_t NameLen, 1377 LLVMMetadataRef File, unsigned LineNo, 1378 LLVMMetadataRef Scope, uint32_t AlignInBits) { 1379 return wrap(unwrap(Builder)->createTypedef( 1380 unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, 1381 unwrapDI<DIScope>(Scope), AlignInBits)); 1382 } 1383 1384 LLVMMetadataRef 1385 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder, 1386 LLVMMetadataRef Ty, LLVMMetadataRef BaseTy, 1387 uint64_t BaseOffset, uint32_t VBPtrOffset, 1388 LLVMDIFlags Flags) { 1389 return wrap(unwrap(Builder)->createInheritance( 1390 unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy), 1391 BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags))); 1392 } 1393 1394 LLVMMetadataRef 1395 LLVMDIBuilderCreateForwardDecl( 1396 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, 1397 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, 1398 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 1399 const char *UniqueIdentifier, size_t UniqueIdentifierLen) { 1400 return wrap(unwrap(Builder)->createForwardDecl( 1401 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope), 1402 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits, 1403 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen})); 1404 } 1405 1406 LLVMMetadataRef 1407 LLVMDIBuilderCreateReplaceableCompositeType( 1408 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name, 1409 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line, 1410 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, 1411 LLVMDIFlags Flags, const char *UniqueIdentifier, 1412 size_t UniqueIdentifierLen) { 1413 return wrap(unwrap(Builder)->createReplaceableCompositeType( 1414 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope), 1415 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits, 1416 AlignInBits, map_from_llvmDIFlags(Flags), 1417 {UniqueIdentifier, UniqueIdentifierLen})); 1418 } 1419 1420 LLVMMetadataRef 1421 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag, 1422 LLVMMetadataRef Type) { 1423 return wrap(unwrap(Builder)->createQualifiedType(Tag, 1424 unwrapDI<DIType>(Type))); 1425 } 1426 1427 LLVMMetadataRef 1428 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag, 1429 LLVMMetadataRef Type) { 1430 return wrap(unwrap(Builder)->createReferenceType(Tag, 1431 unwrapDI<DIType>(Type))); 1432 } 1433 1434 LLVMMetadataRef 1435 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) { 1436 return wrap(unwrap(Builder)->createNullPtrType()); 1437 } 1438 1439 LLVMMetadataRef 1440 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder, 1441 LLVMMetadataRef PointeeType, 1442 LLVMMetadataRef ClassType, 1443 uint64_t SizeInBits, 1444 uint32_t AlignInBits, 1445 LLVMDIFlags Flags) { 1446 return wrap(unwrap(Builder)->createMemberPointerType( 1447 unwrapDI<DIType>(PointeeType), 1448 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits, 1449 map_from_llvmDIFlags(Flags))); 1450 } 1451 1452 LLVMMetadataRef 1453 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder, 1454 LLVMMetadataRef Scope, 1455 const char *Name, size_t NameLen, 1456 LLVMMetadataRef File, unsigned LineNumber, 1457 uint64_t SizeInBits, 1458 uint64_t OffsetInBits, 1459 uint64_t StorageOffsetInBits, 1460 LLVMDIFlags Flags, LLVMMetadataRef Type) { 1461 return wrap(unwrap(Builder)->createBitFieldMemberType( 1462 unwrapDI<DIScope>(Scope), {Name, NameLen}, 1463 unwrapDI<DIFile>(File), LineNumber, 1464 SizeInBits, OffsetInBits, StorageOffsetInBits, 1465 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type))); 1466 } 1467 1468 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder, 1469 LLVMMetadataRef Scope, const char *Name, size_t NameLen, 1470 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, 1471 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags, 1472 LLVMMetadataRef DerivedFrom, 1473 LLVMMetadataRef *Elements, unsigned NumElements, 1474 LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode, 1475 const char *UniqueIdentifier, size_t UniqueIdentifierLen) { 1476 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements), 1477 NumElements}); 1478 return wrap(unwrap(Builder)->createClassType( 1479 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File), 1480 LineNumber, SizeInBits, AlignInBits, OffsetInBits, 1481 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts, 1482 /*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder), 1483 unwrapDI<MDNode>(TemplateParamsNode), 1484 {UniqueIdentifier, UniqueIdentifierLen})); 1485 } 1486 1487 LLVMMetadataRef 1488 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder, 1489 LLVMMetadataRef Type) { 1490 return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type))); 1491 } 1492 1493 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) { 1494 return unwrapDI<DINode>(MD)->getTag(); 1495 } 1496 1497 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) { 1498 StringRef Str = unwrapDI<DIType>(DType)->getName(); 1499 *Length = Str.size(); 1500 return Str.data(); 1501 } 1502 1503 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) { 1504 return unwrapDI<DIType>(DType)->getSizeInBits(); 1505 } 1506 1507 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) { 1508 return unwrapDI<DIType>(DType)->getOffsetInBits(); 1509 } 1510 1511 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) { 1512 return unwrapDI<DIType>(DType)->getAlignInBits(); 1513 } 1514 1515 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) { 1516 return unwrapDI<DIType>(DType)->getLine(); 1517 } 1518 1519 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) { 1520 return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags()); 1521 } 1522 1523 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder, 1524 LLVMMetadataRef *Types, 1525 size_t Length) { 1526 return wrap( 1527 unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get()); 1528 } 1529 1530 LLVMMetadataRef 1531 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder, 1532 LLVMMetadataRef File, 1533 LLVMMetadataRef *ParameterTypes, 1534 unsigned NumParameterTypes, 1535 LLVMDIFlags Flags) { 1536 auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes), 1537 NumParameterTypes}); 1538 return wrap(unwrap(Builder)->createSubroutineType( 1539 Elts, map_from_llvmDIFlags(Flags))); 1540 } 1541 1542 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder, 1543 uint64_t *Addr, size_t Length) { 1544 return wrap( 1545 unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length))); 1546 } 1547 1548 LLVMMetadataRef 1549 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder, 1550 uint64_t Value) { 1551 return wrap(unwrap(Builder)->createConstantValueExpression(Value)); 1552 } 1553 1554 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression( 1555 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1556 size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File, 1557 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, 1558 LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) { 1559 return wrap(unwrap(Builder)->createGlobalVariableExpression( 1560 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen}, 1561 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit, 1562 true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl), 1563 nullptr, AlignInBits)); 1564 } 1565 1566 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) { 1567 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable()); 1568 } 1569 1570 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression( 1571 LLVMMetadataRef GVE) { 1572 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression()); 1573 } 1574 1575 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) { 1576 return wrap(unwrapDI<DIVariable>(Var)->getFile()); 1577 } 1578 1579 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) { 1580 return wrap(unwrapDI<DIVariable>(Var)->getScope()); 1581 } 1582 1583 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) { 1584 return unwrapDI<DIVariable>(Var)->getLine(); 1585 } 1586 1587 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data, 1588 size_t Count) { 1589 return wrap( 1590 MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release()); 1591 } 1592 1593 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) { 1594 MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode)); 1595 } 1596 1597 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata, 1598 LLVMMetadataRef Replacement) { 1599 auto *Node = unwrapDI<MDNode>(TargetMetadata); 1600 Node->replaceAllUsesWith(unwrap(Replacement)); 1601 MDNode::deleteTemporary(Node); 1602 } 1603 1604 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl( 1605 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1606 size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File, 1607 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit, 1608 LLVMMetadataRef Decl, uint32_t AlignInBits) { 1609 return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl( 1610 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen}, 1611 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit, 1612 unwrapDI<MDNode>(Decl), nullptr, AlignInBits)); 1613 } 1614 1615 LLVMValueRef 1616 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage, 1617 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr, 1618 LLVMMetadataRef DL, LLVMValueRef Instr) { 1619 return wrap(unwrap(Builder)->insertDeclare( 1620 unwrap(Storage), unwrap<DILocalVariable>(VarInfo), 1621 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), 1622 unwrap<Instruction>(Instr))); 1623 } 1624 1625 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd( 1626 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo, 1627 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) { 1628 return wrap(unwrap(Builder)->insertDeclare( 1629 unwrap(Storage), unwrap<DILocalVariable>(VarInfo), 1630 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), 1631 unwrap(Block))); 1632 } 1633 1634 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, 1635 LLVMValueRef Val, 1636 LLVMMetadataRef VarInfo, 1637 LLVMMetadataRef Expr, 1638 LLVMMetadataRef DebugLoc, 1639 LLVMValueRef Instr) { 1640 return wrap(unwrap(Builder)->insertDbgValueIntrinsic( 1641 unwrap(Val), unwrap<DILocalVariable>(VarInfo), 1642 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc), 1643 unwrap<Instruction>(Instr))); 1644 } 1645 1646 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder, 1647 LLVMValueRef Val, 1648 LLVMMetadataRef VarInfo, 1649 LLVMMetadataRef Expr, 1650 LLVMMetadataRef DebugLoc, 1651 LLVMBasicBlockRef Block) { 1652 return wrap(unwrap(Builder)->insertDbgValueIntrinsic( 1653 unwrap(Val), unwrap<DILocalVariable>(VarInfo), 1654 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc), 1655 unwrap(Block))); 1656 } 1657 1658 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable( 1659 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1660 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, 1661 LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) { 1662 return wrap(unwrap(Builder)->createAutoVariable( 1663 unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File), 1664 LineNo, unwrap<DIType>(Ty), AlwaysPreserve, 1665 map_from_llvmDIFlags(Flags), AlignInBits)); 1666 } 1667 1668 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable( 1669 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, 1670 size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo, 1671 LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) { 1672 return wrap(unwrap(Builder)->createParameterVariable( 1673 unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File), 1674 LineNo, unwrap<DIType>(Ty), AlwaysPreserve, 1675 map_from_llvmDIFlags(Flags))); 1676 } 1677 1678 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder, 1679 int64_t Lo, int64_t Count) { 1680 return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count)); 1681 } 1682 1683 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder, 1684 LLVMMetadataRef *Data, 1685 size_t Length) { 1686 Metadata **DataValue = unwrap(Data); 1687 return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get()); 1688 } 1689 1690 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) { 1691 return wrap(unwrap<Function>(Func)->getSubprogram()); 1692 } 1693 1694 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) { 1695 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP)); 1696 } 1697 1698 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) { 1699 return unwrapDI<DISubprogram>(Subprogram)->getLine(); 1700 } 1701 1702 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) { 1703 return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode()); 1704 } 1705 1706 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) { 1707 if (Loc) 1708 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc))); 1709 else 1710 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc()); 1711 } 1712 1713 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) { 1714 switch(unwrap(Metadata)->getMetadataID()) { 1715 #define HANDLE_METADATA_LEAF(CLASS) \ 1716 case Metadata::CLASS##Kind: \ 1717 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind; 1718 #include "llvm/IR/Metadata.def" 1719 default: 1720 return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind; 1721 } 1722 } 1723 1724 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) { 1725 assert(ID && "Expected non-null ID"); 1726 LLVMContext &Ctx = ID->getContext(); 1727 auto &Map = Ctx.pImpl->AssignmentIDToInstrs; 1728 1729 auto MapIt = Map.find(ID); 1730 if (MapIt == Map.end()) 1731 return make_range(nullptr, nullptr); 1732 1733 return make_range(MapIt->second.begin(), MapIt->second.end()); 1734 } 1735 1736 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) { 1737 assert(ID && "Expected non-null ID"); 1738 LLVMContext &Ctx = ID->getContext(); 1739 1740 auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID); 1741 1742 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that 1743 // one of those already exists first. 1744 if (!IDAsValue) 1745 return make_range(Value::user_iterator(), Value::user_iterator()); 1746 1747 return make_range(IDAsValue->user_begin(), IDAsValue->user_end()); 1748 } 1749 1750 void at::deleteAssignmentMarkers(const Instruction *Inst) { 1751 auto Range = getAssignmentMarkers(Inst); 1752 if (Range.empty()) 1753 return; 1754 SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end()); 1755 for (auto *DAI : ToDelete) 1756 DAI->eraseFromParent(); 1757 } 1758 1759 void at::RAUW(DIAssignID *Old, DIAssignID *New) { 1760 // Replace MetadataAsValue uses. 1761 if (auto *OldIDAsValue = 1762 MetadataAsValue::getIfExists(Old->getContext(), Old)) { 1763 auto *NewIDAsValue = MetadataAsValue::get(Old->getContext(), New); 1764 OldIDAsValue->replaceAllUsesWith(NewIDAsValue); 1765 } 1766 1767 // Replace attachments. 1768 AssignmentInstRange InstRange = getAssignmentInsts(Old); 1769 // Use intermediate storage for the instruction ptrs because the 1770 // getAssignmentInsts range iterators will be invalidated by adding and 1771 // removing DIAssignID attachments. 1772 SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end()); 1773 for (auto *I : InstVec) 1774 I->setMetadata(LLVMContext::MD_DIAssignID, New); 1775 } 1776 1777 void at::deleteAll(Function *F) { 1778 SmallVector<DbgAssignIntrinsic *, 12> ToDelete; 1779 for (BasicBlock &BB : *F) { 1780 for (Instruction &I : BB) { 1781 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I)) 1782 ToDelete.push_back(DAI); 1783 else 1784 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr); 1785 } 1786 } 1787 for (auto *DAI : ToDelete) 1788 DAI->eraseFromParent(); 1789 } 1790 1791 bool at::calculateFragmentIntersect( 1792 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, 1793 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DAI, 1794 std::optional<DIExpression::FragmentInfo> &Result) { 1795 // There are multiple offsets at play in this function, so let's break it 1796 // down. Starting with how variables may be stored in allocas: 1797 // 1798 // 1 Simplest case: variable is alloca sized and starts at offset 0. 1799 // 2 Variable is larger than the alloca: the alloca holds just a part of it. 1800 // 3 Variable is smaller than the alloca: the alloca may hold multiple 1801 // variables. 1802 // 1803 // Imagine we have a store to the entire alloca. In case (3) the store 1804 // affects bits outside of the bounds of each variable. In case (2), where 1805 // the alloca holds the Xth bit to the Yth bit of a variable, the 1806 // zero-offset store doesn't represent an assignment at offset zero to the 1807 // variable. It is an assignment to offset X. 1808 // 1809 // # Example 1 1810 // Obviously, not all stores are alloca-sized and have zero offset. Imagine 1811 // the lower 32 bits of this store are dead and are going to be DSEd: 1812 // 1813 // store i64 %v, ptr %dest, !DIAssignID !1 1814 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest, 1815 // !DIExpression(DW_OP_plus_uconst, 4)) 1816 // 1817 // Goal: Given our dead bits at offset:0 size:32 for the store, determine the 1818 // part of the variable, which fits in the fragment expressed by the 1819 // dbg.assign, that has been killed, if any. 1820 // 1821 // calculateFragmentIntersect(..., SliceOffsetInBits=0, 1822 // SliceSizeInBits=32, Dest=%dest, DAI=dbg.assign) 1823 // 1824 // Drawing the store (s) in memory followed by the shortened version ($), 1825 // then the dbg.assign (d), with the fragment information on a seperate scale 1826 // underneath: 1827 // 1828 // Memory 1829 // offset 1830 // from 1831 // dest 0 63 1832 // | | 1833 // s[######] - Original stores 64 bits to Dest. 1834 // $----[##] - DSE says the lower 32 bits are dead, to be removed. 1835 // d [##] - DAI's address-modifying expression adds 4 bytes to dest. 1836 // Variable | | 1837 // Fragment 128| 1838 // Offsets 159 1839 // 1840 // The answer is achieved in a few steps: 1841 // 1. Add the fragment offset to the store offset: 1842 // SliceOffsetInBits:0 + VarFrag.OffsetInBits:128 = 128 1843 // 1844 // 2. Subtract the address-modifying expression offset plus difference 1845 // between d.address and dest: 1846 // 128 - (expression_offset:32 + (d.address - dest):0) = 96 1847 // 1848 // 3. That offset along with the store size (32) represents the bits of the 1849 // variable that'd be affected by the store. Call it SliceOfVariable. 1850 // Intersect that with DAI's fragment info: 1851 // SliceOfVariable ∩ DAI_fragment = none 1852 // 1853 // In this case: none of the dead bits of the store affect DAI. 1854 // 1855 // # Example 2 1856 // Similar example with the same goal. This time the upper 16 bits 1857 // of the store are going to be DSE'd. 1858 // 1859 // store i64 %v, ptr %dest, !DIAssignID !1 1860 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest, 1861 // !DIExpression(DW_OP_plus_uconst, 4)) 1862 // 1863 // calculateFragmentIntersect(..., SliceOffsetInBits=48, 1864 // SliceSizeInBits=16, Dest=%dest, DAI=dbg.assign) 1865 // 1866 // Memory 1867 // offset 1868 // from 1869 // dest 0 63 1870 // | | 1871 // s[######] - Original stores 64 bits to Dest. 1872 // $[####]-- - DSE says the upper 16 bits are dead, to be removed. 1873 // d [##] - DAI's address-modifying expression adds 4 bytes to dest. 1874 // Variable | | 1875 // Fragment 128| 1876 // Offsets 159 1877 // 1878 // Using the same steps in the first example: 1879 // 1. SliceOffsetInBits:48 + VarFrag.OffsetInBits:128 = 176 1880 // 2. 176 - (expression_offset:32 + (d.address - dest):0) = 144 1881 // 3. SliceOfVariable offset = 144, size = 16: 1882 // SliceOfVariable ∩ DAI_fragment = (offset: 144, size: 16) 1883 // SliceOfVariable tells us the bits of the variable described by DAI that are 1884 // affected by the DSE. 1885 if (DAI->isKillAddress()) 1886 return false; 1887 1888 DIExpression::FragmentInfo VarFrag = DAI->getFragmentOrEntireVariable(); 1889 if (VarFrag.SizeInBits == 0) 1890 return false; // Variable size is unknown. 1891 1892 // Calculate the difference between Dest and the dbg.assign address + 1893 // address-modifying expression. 1894 int64_t PointerOffsetInBits; 1895 { 1896 auto DestOffsetInBytes = DAI->getAddress()->getPointerOffsetFrom(Dest, DL); 1897 if (!DestOffsetInBytes) 1898 return false; // Can't calculate difference in addresses. 1899 1900 int64_t ExprOffsetInBytes; 1901 if (!DAI->getAddressExpression()->extractIfOffset(ExprOffsetInBytes)) 1902 return false; 1903 1904 int64_t PointerOffsetInBytes = *DestOffsetInBytes + ExprOffsetInBytes; 1905 PointerOffsetInBits = PointerOffsetInBytes * 8; 1906 } 1907 1908 // Adjust the slice offset so that we go from describing the a slice 1909 // of memory to a slice of the variable. 1910 int64_t NewOffsetInBits = 1911 SliceOffsetInBits + VarFrag.OffsetInBits - PointerOffsetInBits; 1912 if (NewOffsetInBits < 0) 1913 return false; // Fragment offsets can only be positive. 1914 DIExpression::FragmentInfo SliceOfVariable(SliceSizeInBits, NewOffsetInBits); 1915 // Intersect the variable slice with DAI's fragment to trim it down to size. 1916 DIExpression::FragmentInfo TrimmedSliceOfVariable = 1917 DIExpression::FragmentInfo::intersect(SliceOfVariable, VarFrag); 1918 if (TrimmedSliceOfVariable == VarFrag) 1919 Result = std::nullopt; 1920 else 1921 Result = TrimmedSliceOfVariable; 1922 return true; 1923 } 1924 1925 /// Collect constant properies (base, size, offset) of \p StoreDest. 1926 /// Return std::nullopt if any properties are not constants or the 1927 /// offset from the base pointer is negative. 1928 static std::optional<AssignmentInfo> 1929 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest, 1930 TypeSize SizeInBits) { 1931 if (SizeInBits.isScalable()) 1932 return std::nullopt; 1933 APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0); 1934 const Value *Base = StoreDest->stripAndAccumulateConstantOffsets( 1935 DL, GEPOffset, /*AllowNonInbounds*/ true); 1936 1937 if (GEPOffset.isNegative()) 1938 return std::nullopt; 1939 1940 uint64_t OffsetInBytes = GEPOffset.getLimitedValue(); 1941 // Check for overflow. 1942 if (OffsetInBytes == UINT64_MAX) 1943 return std::nullopt; 1944 if (const auto *Alloca = dyn_cast<AllocaInst>(Base)) 1945 return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits); 1946 return std::nullopt; 1947 } 1948 1949 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 1950 const MemIntrinsic *I) { 1951 const Value *StoreDest = I->getRawDest(); 1952 // Assume 8 bit bytes. 1953 auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength()); 1954 if (!ConstLengthInBytes) 1955 // We can't use a non-const size, bail. 1956 return std::nullopt; 1957 uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue(); 1958 return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits)); 1959 } 1960 1961 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 1962 const StoreInst *SI) { 1963 TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType()); 1964 return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits); 1965 } 1966 1967 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL, 1968 const AllocaInst *AI) { 1969 TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType()); 1970 return getAssignmentInfoImpl(DL, AI, SizeInBits); 1971 } 1972 1973 /// Returns nullptr if the assignment shouldn't be attributed to this variable. 1974 static CallInst *emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest, 1975 Instruction &StoreLikeInst, 1976 const VarRecord &VarRec, DIBuilder &DIB) { 1977 auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID); 1978 assert(ID && "Store instruction must have DIAssignID metadata"); 1979 (void)ID; 1980 1981 const uint64_t StoreStartBit = Info.OffsetInBits; 1982 const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits; 1983 1984 uint64_t FragStartBit = StoreStartBit; 1985 uint64_t FragEndBit = StoreEndBit; 1986 1987 bool StoreToWholeVariable = Info.StoreToWholeAlloca; 1988 if (auto Size = VarRec.Var->getSizeInBits()) { 1989 // NOTE: trackAssignments doesn't understand base expressions yet, so all 1990 // variables that reach here are guaranteed to start at offset 0 in the 1991 // alloca. 1992 const uint64_t VarStartBit = 0; 1993 const uint64_t VarEndBit = *Size; 1994 1995 // FIXME: trim FragStartBit when nonzero VarStartBit is supported. 1996 FragEndBit = std::min(FragEndBit, VarEndBit); 1997 1998 // Discard stores to bits outside this variable. 1999 if (FragStartBit >= FragEndBit) 2000 return nullptr; 2001 2002 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size; 2003 } 2004 2005 DIExpression *Expr = 2006 DIExpression::get(StoreLikeInst.getContext(), std::nullopt); 2007 if (!StoreToWholeVariable) { 2008 auto R = DIExpression::createFragmentExpression(Expr, FragStartBit, 2009 FragEndBit - FragStartBit); 2010 assert(R.has_value() && "failed to create fragment expression"); 2011 Expr = *R; 2012 } 2013 DIExpression *AddrExpr = 2014 DIExpression::get(StoreLikeInst.getContext(), std::nullopt); 2015 return DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest, 2016 AddrExpr, VarRec.DL); 2017 } 2018 2019 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h). 2020 #define DEBUG_TYPE "assignment-tracking" 2021 2022 void at::trackAssignments(Function::iterator Start, Function::iterator End, 2023 const StorageToVarsMap &Vars, const DataLayout &DL, 2024 bool DebugPrints) { 2025 // Early-exit if there are no interesting variables. 2026 if (Vars.empty()) 2027 return; 2028 2029 auto &Ctx = Start->getContext(); 2030 auto &Module = *Start->getModule(); 2031 2032 // Undef type doesn't matter, so long as it isn't void. Let's just use i1. 2033 auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx)); 2034 DIBuilder DIB(Module, /*AllowUnresolved*/ false); 2035 2036 // Scan the instructions looking for stores to local variables' storage. 2037 LLVM_DEBUG(errs() << "# Scanning instructions\n"); 2038 for (auto BBI = Start; BBI != End; ++BBI) { 2039 for (Instruction &I : *BBI) { 2040 2041 std::optional<AssignmentInfo> Info; 2042 Value *ValueComponent = nullptr; 2043 Value *DestComponent = nullptr; 2044 if (auto *AI = dyn_cast<AllocaInst>(&I)) { 2045 // We want to track the variable's stack home from its alloca's 2046 // position onwards so we treat it as an assignment (where the stored 2047 // value is Undef). 2048 Info = getAssignmentInfo(DL, AI); 2049 ValueComponent = Undef; 2050 DestComponent = AI; 2051 } else if (auto *SI = dyn_cast<StoreInst>(&I)) { 2052 Info = getAssignmentInfo(DL, SI); 2053 ValueComponent = SI->getValueOperand(); 2054 DestComponent = SI->getPointerOperand(); 2055 } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) { 2056 Info = getAssignmentInfo(DL, MI); 2057 // May not be able to represent this value easily. 2058 ValueComponent = Undef; 2059 DestComponent = MI->getOperand(0); 2060 } else if (auto *MI = dyn_cast<MemSetInst>(&I)) { 2061 Info = getAssignmentInfo(DL, MI); 2062 // If we're zero-initing we can state the assigned value is zero, 2063 // otherwise use undef. 2064 auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1)); 2065 if (ConstValue && ConstValue->isZero()) 2066 ValueComponent = ConstValue; 2067 else 2068 ValueComponent = Undef; 2069 DestComponent = MI->getOperand(0); 2070 } else { 2071 // Not a store-like instruction. 2072 continue; 2073 } 2074 2075 assert(ValueComponent && DestComponent); 2076 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n"); 2077 2078 // Check if getAssignmentInfo failed to understand this store. 2079 if (!Info.has_value()) { 2080 LLVM_DEBUG( 2081 errs() 2082 << " | SKIP: Untrackable store (e.g. through non-const gep)\n"); 2083 continue; 2084 } 2085 LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n"); 2086 2087 // Check if the store destination is a local variable with debug info. 2088 auto LocalIt = Vars.find(Info->Base); 2089 if (LocalIt == Vars.end()) { 2090 LLVM_DEBUG( 2091 errs() 2092 << " | SKIP: Base address not associated with local variable\n"); 2093 continue; 2094 } 2095 2096 DIAssignID *ID = 2097 cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID)); 2098 if (!ID) { 2099 ID = DIAssignID::getDistinct(Ctx); 2100 I.setMetadata(LLVMContext::MD_DIAssignID, ID); 2101 } 2102 2103 for (const VarRecord &R : LocalIt->second) { 2104 auto *Assign = 2105 emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB); 2106 (void)Assign; 2107 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n"); 2108 } 2109 } 2110 } 2111 } 2112 2113 bool AssignmentTrackingPass::runOnFunction(Function &F) { 2114 // No value in assignment tracking without optimisations. 2115 if (F.hasFnAttribute(Attribute::OptimizeNone)) 2116 return /*Changed*/ false; 2117 2118 // FIXME: https://github.com/llvm/llvm-project/issues/76545 2119 if (F.hasFnAttribute(Attribute::SanitizeHWAddress)) 2120 return /*Changed*/ false; 2121 2122 bool Changed = false; 2123 auto *DL = &F.getParent()->getDataLayout(); 2124 // Collect a map of {backing storage : dbg.declares} (currently "backing 2125 // storage" is limited to Allocas). We'll use this to find dbg.declares to 2126 // delete after running `trackAssignments`. 2127 DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares; 2128 // Create another similar map of {storage : variables} that we'll pass to 2129 // trackAssignments. 2130 StorageToVarsMap Vars; 2131 for (auto &BB : F) { 2132 for (auto &I : BB) { 2133 DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I); 2134 if (!DDI) 2135 continue; 2136 // FIXME: trackAssignments doesn't let you specify any modifiers to the 2137 // variable (e.g. fragment) or location (e.g. offset), so we have to 2138 // leave dbg.declares with non-empty expressions in place. 2139 if (DDI->getExpression()->getNumElements() != 0) 2140 continue; 2141 if (!DDI->getAddress()) 2142 continue; 2143 if (AllocaInst *Alloca = 2144 dyn_cast<AllocaInst>(DDI->getAddress()->stripPointerCasts())) { 2145 // FIXME: Skip VLAs for now (let these variables use dbg.declares). 2146 if (!Alloca->isStaticAlloca()) 2147 continue; 2148 // Similarly, skip scalable vectors (use dbg.declares instead). 2149 if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable()) 2150 continue; 2151 DbgDeclares[Alloca].insert(DDI); 2152 Vars[Alloca].insert(VarRecord(DDI)); 2153 } 2154 } 2155 } 2156 2157 // FIXME: Locals can be backed by caller allocas (sret, byval). 2158 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it 2159 // doesn't "understand" dbg.declares). However, this doesn't appear to break 2160 // any rules given this description of dbg.declare from 2161 // llvm/docs/SourceLevelDebugging.rst: 2162 // 2163 // It is not control-dependent, meaning that if a call to llvm.dbg.declare 2164 // exists and has a valid location argument, that address is considered to 2165 // be the true home of the variable across its entire lifetime. 2166 trackAssignments(F.begin(), F.end(), Vars, *DL); 2167 2168 // Delete dbg.declares for variables now tracked with assignment tracking. 2169 for (auto &P : DbgDeclares) { 2170 const AllocaInst *Alloca = P.first; 2171 auto Markers = at::getAssignmentMarkers(Alloca); 2172 (void)Markers; 2173 for (DbgDeclareInst *DDI : P.second) { 2174 // Assert that the alloca that DDI uses is now linked to a dbg.assign 2175 // describing the same variable (i.e. check that this dbg.declare has 2176 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard 2177 // the fragment part because trackAssignments may alter the 2178 // fragment. e.g. if the alloca is smaller than the variable, then 2179 // trackAssignments will create an alloca-sized fragment for the 2180 // dbg.assign. 2181 assert(llvm::any_of(Markers, [DDI](DbgAssignIntrinsic *DAI) { 2182 return DebugVariableAggregate(DAI) == DebugVariableAggregate(DDI); 2183 })); 2184 // Delete DDI because the variable location is now tracked using 2185 // assignment tracking. 2186 DDI->eraseFromParent(); 2187 Changed = true; 2188 } 2189 } 2190 return Changed; 2191 } 2192 2193 static const char *AssignmentTrackingModuleFlag = 2194 "debug-info-assignment-tracking"; 2195 2196 static void setAssignmentTrackingModuleFlag(Module &M) { 2197 M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag, 2198 ConstantAsMetadata::get( 2199 ConstantInt::get(Type::getInt1Ty(M.getContext()), 1))); 2200 } 2201 2202 static bool getAssignmentTrackingModuleFlag(const Module &M) { 2203 Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag); 2204 return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue(); 2205 } 2206 2207 bool llvm::isAssignmentTrackingEnabled(const Module &M) { 2208 return getAssignmentTrackingModuleFlag(M); 2209 } 2210 2211 PreservedAnalyses AssignmentTrackingPass::run(Function &F, 2212 FunctionAnalysisManager &AM) { 2213 if (!runOnFunction(F)) 2214 return PreservedAnalyses::all(); 2215 2216 // Record that this module uses assignment tracking. It doesn't matter that 2217 // some functons in the module may not use it - the debug info in those 2218 // functions will still be handled properly. 2219 setAssignmentTrackingModuleFlag(*F.getParent()); 2220 2221 // Q: Can we return a less conservative set than just CFGAnalyses? Can we 2222 // return PreservedAnalyses::all()? 2223 PreservedAnalyses PA; 2224 PA.preserveSet<CFGAnalyses>(); 2225 return PA; 2226 } 2227 2228 PreservedAnalyses AssignmentTrackingPass::run(Module &M, 2229 ModuleAnalysisManager &AM) { 2230 bool Changed = false; 2231 for (auto &F : M) 2232 Changed |= runOnFunction(F); 2233 2234 if (!Changed) 2235 return PreservedAnalyses::all(); 2236 2237 // Record that this module uses assignment tracking. 2238 setAssignmentTrackingModuleFlag(M); 2239 2240 // Q: Can we return a less conservative set than just CFGAnalyses? Can we 2241 // return PreservedAnalyses::all()? 2242 PreservedAnalyses PA; 2243 PA.preserveSet<CFGAnalyses>(); 2244 return PA; 2245 } 2246 2247 #undef DEBUG_TYPE 2248