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