1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the helper classes used to build and interpret debug
10 // information in LLVM IR form.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-c/DebugInfo.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DebugProgramInstruction.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/Support/Casting.h"
44 using namespace llvm::at
;
45 using namespace llvm::dwarf
;
47 TinyPtrVector
<DbgDeclareInst
*> llvm::findDbgDeclares(Value
*V
) {
48 // This function is hot. Check whether the value has any metadata to avoid a
50 if (!V
->isUsedByMetadata())
52 auto *L
= LocalAsMetadata::getIfExists(V
);
55 auto *MDV
= MetadataAsValue::getIfExists(V
->getContext(), L
);
59 TinyPtrVector
<DbgDeclareInst
*> Declares
;
60 for (User
*U
: MDV
->users())
61 if (auto *DDI
= dyn_cast
<DbgDeclareInst
>(U
))
62 Declares
.push_back(DDI
);
66 TinyPtrVector
<DPValue
*> llvm::findDPVDeclares(Value
*V
) {
67 // This function is hot. Check whether the value has any metadata to avoid a
69 if (!V
->isUsedByMetadata())
71 auto *L
= LocalAsMetadata::getIfExists(V
);
75 TinyPtrVector
<DPValue
*> Declares
;
76 for (DPValue
*DPV
: L
->getAllDPValueUsers())
77 if (DPV
->getType() == DPValue::LocationType::Declare
)
78 Declares
.push_back(DPV
);
83 template <typename IntrinsicT
,
84 DPValue::LocationType Type
= DPValue::LocationType::Any
>
85 static void findDbgIntrinsics(SmallVectorImpl
<IntrinsicT
*> &Result
, Value
*V
,
86 SmallVectorImpl
<DPValue
*> *DPValues
) {
87 // This function is hot. Check whether the value has any metadata to avoid a
89 if (!V
->isUsedByMetadata())
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
<DPValue
*, 4> EncounteredDPValues
;
101 /// Append IntrinsicT users of MetadataAsValue(MD).
102 auto AppendUsers
= [&Ctx
, &EncounteredIntrinsics
, &Result
,
103 DPValues
](Metadata
*MD
) {
104 if (auto *MDV
= MetadataAsValue::getIfExists(Ctx
, MD
)) {
105 for (User
*U
: MDV
->users())
106 if (IntrinsicT
*DVI
= dyn_cast
<IntrinsicT
>(U
))
107 if (EncounteredIntrinsics
.insert(DVI
).second
)
108 Result
.push_back(DVI
);
112 // Get DPValues that use this as a single value.
113 if (LocalAsMetadata
*L
= dyn_cast
<LocalAsMetadata
>(MD
)) {
114 for (DPValue
*DPV
: L
->getAllDPValueUsers()) {
115 if (Type
== DPValue::LocationType::Any
|| DPV
->getType() == Type
)
116 DPValues
->push_back(DPV
);
121 if (auto *L
= LocalAsMetadata::getIfExists(V
)) {
123 for (Metadata
*AL
: L
->getAllArgListUsers()) {
127 DIArgList
*DI
= cast
<DIArgList
>(AL
);
128 for (DPValue
*DPV
: DI
->getAllDPValueUsers())
129 if (Type
== DPValue::LocationType::Any
|| DPV
->getType() == Type
)
130 if (EncounteredDPValues
.insert(DPV
).second
)
131 DPValues
->push_back(DPV
);
136 void llvm::findDbgValues(SmallVectorImpl
<DbgValueInst
*> &DbgValues
,
137 Value
*V
, SmallVectorImpl
<DPValue
*> *DPValues
) {
138 findDbgIntrinsics
<DbgValueInst
, DPValue::LocationType::Value
>(DbgValues
, V
,
142 void llvm::findDbgUsers(SmallVectorImpl
<DbgVariableIntrinsic
*> &DbgUsers
,
143 Value
*V
, SmallVectorImpl
<DPValue
*> *DPValues
) {
144 findDbgIntrinsics
<DbgVariableIntrinsic
, DPValue::LocationType::Any
>(
145 DbgUsers
, V
, DPValues
);
148 DISubprogram
*llvm::getDISubprogram(const MDNode
*Scope
) {
149 if (auto *LocalScope
= dyn_cast_or_null
<DILocalScope
>(Scope
))
150 return LocalScope
->getSubprogram();
154 DebugLoc
llvm::getDebugValueLoc(DbgVariableIntrinsic
*DII
) {
155 // Original dbg.declare must have a location.
156 const DebugLoc
&DeclareLoc
= DII
->getDebugLoc();
157 MDNode
*Scope
= DeclareLoc
.getScope();
158 DILocation
*InlinedAt
= DeclareLoc
.getInlinedAt();
159 // Because no machine insts can come from debug intrinsics, only the scope
160 // and inlinedAt is significant. Zero line numbers are used in case this
161 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
162 // with the correct scope / inlinedAt fields.
163 return DILocation::get(DII
->getContext(), 0, 0, Scope
, InlinedAt
);
166 DebugLoc
llvm::getDebugValueLoc(DPValue
*DPV
) {
167 // Original dbg.declare must have a location.
168 const DebugLoc
&DeclareLoc
= DPV
->getDebugLoc();
169 MDNode
*Scope
= DeclareLoc
.getScope();
170 DILocation
*InlinedAt
= DeclareLoc
.getInlinedAt();
171 // Because no machine insts can come from debug intrinsics, only the scope
172 // and inlinedAt is significant. Zero line numbers are used in case this
173 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
174 // with the correct scope / inlinedAt fields.
175 return DILocation::get(DPV
->getContext(), 0, 0, Scope
, InlinedAt
);
178 //===----------------------------------------------------------------------===//
179 // DebugInfoFinder implementations.
180 //===----------------------------------------------------------------------===//
182 void DebugInfoFinder::reset() {
191 void DebugInfoFinder::processModule(const Module
&M
) {
192 for (auto *CU
: M
.debug_compile_units())
193 processCompileUnit(CU
);
194 for (auto &F
: M
.functions()) {
195 if (auto *SP
= cast_or_null
<DISubprogram
>(F
.getSubprogram()))
196 processSubprogram(SP
);
197 // There could be subprograms from inlined functions referenced from
198 // instructions only. Walk the function to find them.
199 for (const BasicBlock
&BB
: F
)
200 for (const Instruction
&I
: BB
)
201 processInstruction(M
, I
);
205 void DebugInfoFinder::processCompileUnit(DICompileUnit
*CU
) {
206 if (!addCompileUnit(CU
))
208 for (auto *DIG
: CU
->getGlobalVariables()) {
209 if (!addGlobalVariable(DIG
))
211 auto *GV
= DIG
->getVariable();
212 processScope(GV
->getScope());
213 processType(GV
->getType());
215 for (auto *ET
: CU
->getEnumTypes())
217 for (auto *RT
: CU
->getRetainedTypes())
218 if (auto *T
= dyn_cast
<DIType
>(RT
))
221 processSubprogram(cast
<DISubprogram
>(RT
));
222 for (auto *Import
: CU
->getImportedEntities()) {
223 auto *Entity
= Import
->getEntity();
224 if (auto *T
= dyn_cast
<DIType
>(Entity
))
226 else if (auto *SP
= dyn_cast
<DISubprogram
>(Entity
))
227 processSubprogram(SP
);
228 else if (auto *NS
= dyn_cast
<DINamespace
>(Entity
))
229 processScope(NS
->getScope());
230 else if (auto *M
= dyn_cast
<DIModule
>(Entity
))
231 processScope(M
->getScope());
235 void DebugInfoFinder::processInstruction(const Module
&M
,
236 const Instruction
&I
) {
237 if (auto *DVI
= dyn_cast
<DbgVariableIntrinsic
>(&I
))
238 processVariable(M
, DVI
->getVariable());
240 if (auto DbgLoc
= I
.getDebugLoc())
241 processLocation(M
, DbgLoc
.get());
243 for (const DPValue
&DPV
: I
.getDbgValueRange())
244 processDPValue(M
, DPV
);
247 void DebugInfoFinder::processLocation(const Module
&M
, const DILocation
*Loc
) {
250 processScope(Loc
->getScope());
251 processLocation(M
, Loc
->getInlinedAt());
254 void DebugInfoFinder::processDPValue(const Module
&M
, const DPValue
&DPV
) {
255 processVariable(M
, DPV
.getVariable());
256 processLocation(M
, DPV
.getDebugLoc().get());
259 void DebugInfoFinder::processType(DIType
*DT
) {
262 processScope(DT
->getScope());
263 if (auto *ST
= dyn_cast
<DISubroutineType
>(DT
)) {
264 for (DIType
*Ref
: ST
->getTypeArray())
268 if (auto *DCT
= dyn_cast
<DICompositeType
>(DT
)) {
269 processType(DCT
->getBaseType());
270 for (Metadata
*D
: DCT
->getElements()) {
271 if (auto *T
= dyn_cast
<DIType
>(D
))
273 else if (auto *SP
= dyn_cast
<DISubprogram
>(D
))
274 processSubprogram(SP
);
278 if (auto *DDT
= dyn_cast
<DIDerivedType
>(DT
)) {
279 processType(DDT
->getBaseType());
283 void DebugInfoFinder::processScope(DIScope
*Scope
) {
286 if (auto *Ty
= dyn_cast
<DIType
>(Scope
)) {
290 if (auto *CU
= dyn_cast
<DICompileUnit
>(Scope
)) {
294 if (auto *SP
= dyn_cast
<DISubprogram
>(Scope
)) {
295 processSubprogram(SP
);
298 if (!addScope(Scope
))
300 if (auto *LB
= dyn_cast
<DILexicalBlockBase
>(Scope
)) {
301 processScope(LB
->getScope());
302 } else if (auto *NS
= dyn_cast
<DINamespace
>(Scope
)) {
303 processScope(NS
->getScope());
304 } else if (auto *M
= dyn_cast
<DIModule
>(Scope
)) {
305 processScope(M
->getScope());
309 void DebugInfoFinder::processSubprogram(DISubprogram
*SP
) {
310 if (!addSubprogram(SP
))
312 processScope(SP
->getScope());
313 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
314 // ValueMap containing identity mappings for all of the DICompileUnit's, not
315 // just DISubprogram's, referenced from anywhere within the Function being
316 // cloned prior to calling MapMetadata / RemapInstruction to avoid their
317 // duplication later as DICompileUnit's are also directly referenced by
318 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
319 // Also, DICompileUnit's may reference DISubprogram's too and therefore need
320 // to be at least looked through.
321 processCompileUnit(SP
->getUnit());
322 processType(SP
->getType());
323 for (auto *Element
: SP
->getTemplateParams()) {
324 if (auto *TType
= dyn_cast
<DITemplateTypeParameter
>(Element
)) {
325 processType(TType
->getType());
326 } else if (auto *TVal
= dyn_cast
<DITemplateValueParameter
>(Element
)) {
327 processType(TVal
->getType());
332 void DebugInfoFinder::processVariable(const Module
&M
,
333 const DILocalVariable
*DV
) {
334 if (!NodesSeen
.insert(DV
).second
)
336 processScope(DV
->getScope());
337 processType(DV
->getType());
340 bool DebugInfoFinder::addType(DIType
*DT
) {
344 if (!NodesSeen
.insert(DT
).second
)
347 TYs
.push_back(const_cast<DIType
*>(DT
));
351 bool DebugInfoFinder::addCompileUnit(DICompileUnit
*CU
) {
354 if (!NodesSeen
.insert(CU
).second
)
361 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression
*DIG
) {
362 if (!NodesSeen
.insert(DIG
).second
)
369 bool DebugInfoFinder::addSubprogram(DISubprogram
*SP
) {
373 if (!NodesSeen
.insert(SP
).second
)
380 bool DebugInfoFinder::addScope(DIScope
*Scope
) {
383 // FIXME: Ocaml binding generates a scope with no content, we treat it
385 if (Scope
->getNumOperands() == 0)
387 if (!NodesSeen
.insert(Scope
).second
)
389 Scopes
.push_back(Scope
);
393 static MDNode
*updateLoopMetadataDebugLocationsImpl(
394 MDNode
*OrigLoopID
, function_ref
<Metadata
*(Metadata
*)> Updater
) {
395 assert(OrigLoopID
&& OrigLoopID
->getNumOperands() > 0 &&
396 "Loop ID needs at least one operand");
397 assert(OrigLoopID
&& OrigLoopID
->getOperand(0).get() == OrigLoopID
&&
398 "Loop ID should refer to itself");
400 // Save space for the self-referential LoopID.
401 SmallVector
<Metadata
*, 4> MDs
= {nullptr};
403 for (unsigned i
= 1; i
< OrigLoopID
->getNumOperands(); ++i
) {
404 Metadata
*MD
= OrigLoopID
->getOperand(i
);
406 MDs
.push_back(nullptr);
407 else if (Metadata
*NewMD
= Updater(MD
))
408 MDs
.push_back(NewMD
);
411 MDNode
*NewLoopID
= MDNode::getDistinct(OrigLoopID
->getContext(), MDs
);
412 // Insert the self-referential LoopID.
413 NewLoopID
->replaceOperandWith(0, NewLoopID
);
417 void llvm::updateLoopMetadataDebugLocations(
418 Instruction
&I
, function_ref
<Metadata
*(Metadata
*)> Updater
) {
419 MDNode
*OrigLoopID
= I
.getMetadata(LLVMContext::MD_loop
);
422 MDNode
*NewLoopID
= updateLoopMetadataDebugLocationsImpl(OrigLoopID
, Updater
);
423 I
.setMetadata(LLVMContext::MD_loop
, NewLoopID
);
426 /// Return true if a node is a DILocation or if a DILocation is
427 /// indirectly referenced by one of the node's children.
428 static bool isDILocationReachable(SmallPtrSetImpl
<Metadata
*> &Visited
,
429 SmallPtrSetImpl
<Metadata
*> &Reachable
,
431 MDNode
*N
= dyn_cast_or_null
<MDNode
>(MD
);
434 if (isa
<DILocation
>(N
) || Reachable
.count(N
))
436 if (!Visited
.insert(N
).second
)
438 for (auto &OpIt
: N
->operands()) {
439 Metadata
*Op
= OpIt
.get();
440 if (isDILocationReachable(Visited
, Reachable
, Op
)) {
441 // Don't return just yet as we want to visit all MD's children to
442 // initialize DILocationReachable in stripDebugLocFromLoopID
446 return Reachable
.count(N
);
449 static bool isAllDILocation(SmallPtrSetImpl
<Metadata
*> &Visited
,
450 SmallPtrSetImpl
<Metadata
*> &AllDILocation
,
451 const SmallPtrSetImpl
<Metadata
*> &DIReachable
,
453 MDNode
*N
= dyn_cast_or_null
<MDNode
>(MD
);
456 if (isa
<DILocation
>(N
) || AllDILocation
.count(N
))
458 if (!DIReachable
.count(N
))
460 if (!Visited
.insert(N
).second
)
462 for (auto &OpIt
: N
->operands()) {
463 Metadata
*Op
= OpIt
.get();
466 if (!isAllDILocation(Visited
, AllDILocation
, DIReachable
, Op
)) {
470 AllDILocation
.insert(N
);
475 stripLoopMDLoc(const SmallPtrSetImpl
<Metadata
*> &AllDILocation
,
476 const SmallPtrSetImpl
<Metadata
*> &DIReachable
, Metadata
*MD
) {
477 if (isa
<DILocation
>(MD
) || AllDILocation
.count(MD
))
480 if (!DIReachable
.count(MD
))
483 MDNode
*N
= dyn_cast_or_null
<MDNode
>(MD
);
487 SmallVector
<Metadata
*, 4> Args
;
488 bool HasSelfRef
= false;
489 for (unsigned i
= 0; i
< N
->getNumOperands(); ++i
) {
490 Metadata
*A
= N
->getOperand(i
);
492 Args
.push_back(nullptr);
493 } else if (A
== MD
) {
494 assert(i
== 0 && "expected i==0 for self-reference");
496 Args
.push_back(nullptr);
497 } else if (Metadata
*NewArg
=
498 stripLoopMDLoc(AllDILocation
, DIReachable
, A
)) {
499 Args
.push_back(NewArg
);
502 if (Args
.empty() || (HasSelfRef
&& Args
.size() == 1))
505 MDNode
*NewMD
= N
->isDistinct() ? MDNode::getDistinct(N
->getContext(), Args
)
506 : MDNode::get(N
->getContext(), Args
);
508 NewMD
->replaceOperandWith(0, NewMD
);
512 static MDNode
*stripDebugLocFromLoopID(MDNode
*N
) {
513 assert(!N
->operands().empty() && "Missing self reference?");
514 SmallPtrSet
<Metadata
*, 8> Visited
, DILocationReachable
, AllDILocation
;
515 // If we already visited N, there is nothing to do.
516 if (!Visited
.insert(N
).second
)
519 // If there is no debug location, we do not have to rewrite this
520 // MDNode. This loop also initializes DILocationReachable, later
521 // needed by updateLoopMetadataDebugLocationsImpl; the use of
522 // count_if avoids an early exit.
523 if (!llvm::count_if(llvm::drop_begin(N
->operands()),
524 [&Visited
, &DILocationReachable
](const MDOperand
&Op
) {
525 return isDILocationReachable(
526 Visited
, DILocationReachable
, Op
.get());
531 // If there is only the debug location without any actual loop metadata, we
532 // can remove the metadata.
533 if (llvm::all_of(llvm::drop_begin(N
->operands()),
534 [&Visited
, &AllDILocation
,
535 &DILocationReachable
](const MDOperand
&Op
) {
536 return isAllDILocation(Visited
, AllDILocation
,
537 DILocationReachable
, Op
.get());
541 return updateLoopMetadataDebugLocationsImpl(
542 N
, [&AllDILocation
, &DILocationReachable
](Metadata
*MD
) -> Metadata
* {
543 return stripLoopMDLoc(AllDILocation
, DILocationReachable
, MD
);
547 bool llvm::stripDebugInfo(Function
&F
) {
548 bool Changed
= false;
549 if (F
.hasMetadata(LLVMContext::MD_dbg
)) {
551 F
.setSubprogram(nullptr);
554 DenseMap
<MDNode
*, MDNode
*> LoopIDsMap
;
555 for (BasicBlock
&BB
: F
) {
556 for (Instruction
&I
: llvm::make_early_inc_range(BB
)) {
557 if (isa
<DbgInfoIntrinsic
>(&I
)) {
562 if (I
.getDebugLoc()) {
564 I
.setDebugLoc(DebugLoc());
566 if (auto *LoopID
= I
.getMetadata(LLVMContext::MD_loop
)) {
567 auto *NewLoopID
= LoopIDsMap
.lookup(LoopID
);
569 NewLoopID
= LoopIDsMap
[LoopID
] = stripDebugLocFromLoopID(LoopID
);
570 if (NewLoopID
!= LoopID
)
571 I
.setMetadata(LLVMContext::MD_loop
, NewLoopID
);
573 // Strip other attachments that are or use debug info.
574 if (I
.hasMetadataOtherThanDebugLoc()) {
575 // Heapallocsites point into the DIType system.
576 I
.setMetadata("heapallocsite", nullptr);
577 // DIAssignID are debug info metadata primitives.
578 I
.setMetadata(LLVMContext::MD_DIAssignID
, nullptr);
586 bool llvm::StripDebugInfo(Module
&M
) {
587 bool Changed
= false;
589 for (NamedMDNode
&NMD
: llvm::make_early_inc_range(M
.named_metadata())) {
590 // We're stripping debug info, and without them, coverage information
591 // doesn't quite make sense.
592 if (NMD
.getName().starts_with("llvm.dbg.") ||
593 NMD
.getName() == "llvm.gcov") {
594 NMD
.eraseFromParent();
599 for (Function
&F
: M
)
600 Changed
|= stripDebugInfo(F
);
602 for (auto &GV
: M
.globals()) {
603 Changed
|= GV
.eraseMetadata(LLVMContext::MD_dbg
);
606 if (GVMaterializer
*Materializer
= M
.getMaterializer())
607 Materializer
->setStripDebugInfo();
614 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
615 class DebugTypeInfoRemoval
{
616 DenseMap
<Metadata
*, Metadata
*> Replacements
;
619 /// The (void)() type.
620 MDNode
*EmptySubroutineType
;
623 /// Remember what linkage name we originally had before stripping. If we end
624 /// up making two subprograms identical who originally had different linkage
625 /// names, then we need to make one of them distinct, to avoid them getting
626 /// uniqued. Maps the new node to the old linkage name.
627 DenseMap
<DISubprogram
*, StringRef
> NewToLinkageName
;
629 // TODO: Remember the distinct subprogram we created for a given linkage name,
630 // so that we can continue to unique whenever possible. Map <newly created
631 // node, old linkage name> to the first (possibly distinct) mdsubprogram
632 // created for that combination. This is not strictly needed for correctness,
633 // but can cut down on the number of MDNodes and let us diff cleanly with the
634 // output of -gline-tables-only.
637 DebugTypeInfoRemoval(LLVMContext
&C
)
638 : EmptySubroutineType(DISubroutineType::get(C
, DINode::FlagZero
, 0,
639 MDNode::get(C
, {}))) {}
641 Metadata
*map(Metadata
*M
) {
644 auto Replacement
= Replacements
.find(M
);
645 if (Replacement
!= Replacements
.end())
646 return Replacement
->second
;
650 MDNode
*mapNode(Metadata
*N
) { return dyn_cast_or_null
<MDNode
>(map(N
)); }
652 /// Recursively remap N and all its referenced children. Does a DF post-order
653 /// traversal, so as to remap bottoms up.
654 void traverseAndRemap(MDNode
*N
) { traverse(N
); }
657 // Create a new DISubprogram, to replace the one given.
658 DISubprogram
*getReplacementSubprogram(DISubprogram
*MDS
) {
659 auto *FileAndScope
= cast_or_null
<DIFile
>(map(MDS
->getFile()));
660 StringRef LinkageName
= MDS
->getName().empty() ? MDS
->getLinkageName() : "";
661 DISubprogram
*Declaration
= nullptr;
662 auto *Type
= cast_or_null
<DISubroutineType
>(map(MDS
->getType()));
663 DIType
*ContainingType
=
664 cast_or_null
<DIType
>(map(MDS
->getContainingType()));
665 auto *Unit
= cast_or_null
<DICompileUnit
>(map(MDS
->getUnit()));
666 auto Variables
= nullptr;
667 auto TemplateParams
= nullptr;
669 // Make a distinct DISubprogram, for situations that warrent it.
670 auto distinctMDSubprogram
= [&]() {
671 return DISubprogram::getDistinct(
672 MDS
->getContext(), FileAndScope
, MDS
->getName(), LinkageName
,
673 FileAndScope
, MDS
->getLine(), Type
, MDS
->getScopeLine(),
674 ContainingType
, MDS
->getVirtualIndex(), MDS
->getThisAdjustment(),
675 MDS
->getFlags(), MDS
->getSPFlags(), Unit
, TemplateParams
, Declaration
,
679 if (MDS
->isDistinct())
680 return distinctMDSubprogram();
682 auto *NewMDS
= DISubprogram::get(
683 MDS
->getContext(), FileAndScope
, MDS
->getName(), LinkageName
,
684 FileAndScope
, MDS
->getLine(), Type
, MDS
->getScopeLine(), ContainingType
,
685 MDS
->getVirtualIndex(), MDS
->getThisAdjustment(), MDS
->getFlags(),
686 MDS
->getSPFlags(), Unit
, TemplateParams
, Declaration
, Variables
);
688 StringRef OldLinkageName
= MDS
->getLinkageName();
690 // See if we need to make a distinct one.
691 auto OrigLinkage
= NewToLinkageName
.find(NewMDS
);
692 if (OrigLinkage
!= NewToLinkageName
.end()) {
693 if (OrigLinkage
->second
== OldLinkageName
)
697 // Otherwise, need to make a distinct one.
698 // TODO: Query the map to see if we already have one.
699 return distinctMDSubprogram();
702 NewToLinkageName
.insert({NewMDS
, MDS
->getLinkageName()});
706 /// Create a new compile unit, to replace the one given
707 DICompileUnit
*getReplacementCU(DICompileUnit
*CU
) {
708 // Drop skeleton CUs.
712 auto *File
= cast_or_null
<DIFile
>(map(CU
->getFile()));
713 MDTuple
*EnumTypes
= nullptr;
714 MDTuple
*RetainedTypes
= nullptr;
715 MDTuple
*GlobalVariables
= nullptr;
716 MDTuple
*ImportedEntities
= nullptr;
717 return DICompileUnit::getDistinct(
718 CU
->getContext(), CU
->getSourceLanguage(), File
, CU
->getProducer(),
719 CU
->isOptimized(), CU
->getFlags(), CU
->getRuntimeVersion(),
720 CU
->getSplitDebugFilename(), DICompileUnit::LineTablesOnly
, EnumTypes
,
721 RetainedTypes
, GlobalVariables
, ImportedEntities
, CU
->getMacros(),
722 CU
->getDWOId(), CU
->getSplitDebugInlining(),
723 CU
->getDebugInfoForProfiling(), CU
->getNameTableKind(),
724 CU
->getRangesBaseAddress(), CU
->getSysRoot(), CU
->getSDK());
727 DILocation
*getReplacementMDLocation(DILocation
*MLD
) {
728 auto *Scope
= map(MLD
->getScope());
729 auto *InlinedAt
= map(MLD
->getInlinedAt());
730 if (MLD
->isDistinct())
731 return DILocation::getDistinct(MLD
->getContext(), MLD
->getLine(),
732 MLD
->getColumn(), Scope
, InlinedAt
);
733 return DILocation::get(MLD
->getContext(), MLD
->getLine(), MLD
->getColumn(),
737 /// Create a new generic MDNode, to replace the one given
738 MDNode
*getReplacementMDNode(MDNode
*N
) {
739 SmallVector
<Metadata
*, 8> Ops
;
740 Ops
.reserve(N
->getNumOperands());
741 for (auto &I
: N
->operands())
743 Ops
.push_back(map(I
));
744 auto *Ret
= MDNode::get(N
->getContext(), Ops
);
748 /// Attempt to re-map N to a newly created node.
749 void remap(MDNode
*N
) {
750 if (Replacements
.count(N
))
753 auto doRemap
= [&](MDNode
*N
) -> MDNode
* {
756 if (auto *MDSub
= dyn_cast
<DISubprogram
>(N
)) {
757 remap(MDSub
->getUnit());
758 return getReplacementSubprogram(MDSub
);
760 if (isa
<DISubroutineType
>(N
))
761 return EmptySubroutineType
;
762 if (auto *CU
= dyn_cast
<DICompileUnit
>(N
))
763 return getReplacementCU(CU
);
766 if (auto *MDLB
= dyn_cast
<DILexicalBlockBase
>(N
))
767 // Remap to our referenced scope (recursively).
768 return mapNode(MDLB
->getScope());
769 if (auto *MLD
= dyn_cast
<DILocation
>(N
))
770 return getReplacementMDLocation(MLD
);
772 // Otherwise, if we see these, just drop them now. Not strictly necessary,
773 // but this speeds things up a little.
777 return getReplacementMDNode(N
);
779 Replacements
[N
] = doRemap(N
);
782 /// Do the remapping traversal.
783 void traverse(MDNode
*);
786 } // end anonymous namespace
788 void DebugTypeInfoRemoval::traverse(MDNode
*N
) {
789 if (!N
|| Replacements
.count(N
))
792 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
793 // parts of the graph.
794 auto prune
= [](MDNode
*Parent
, MDNode
*Child
) {
795 if (auto *MDS
= dyn_cast
<DISubprogram
>(Parent
))
796 return Child
== MDS
->getRetainedNodes().get();
800 SmallVector
<MDNode
*, 16> ToVisit
;
801 DenseSet
<MDNode
*> Opened
;
803 // Visit each node starting at N in post order, and map them.
804 ToVisit
.push_back(N
);
805 while (!ToVisit
.empty()) {
806 auto *N
= ToVisit
.back();
807 if (!Opened
.insert(N
).second
) {
813 for (auto &I
: N
->operands())
814 if (auto *MDN
= dyn_cast_or_null
<MDNode
>(I
))
815 if (!Opened
.count(MDN
) && !Replacements
.count(MDN
) && !prune(N
, MDN
) &&
816 !isa
<DICompileUnit
>(MDN
))
817 ToVisit
.push_back(MDN
);
821 bool llvm::stripNonLineTableDebugInfo(Module
&M
) {
822 bool Changed
= false;
824 // First off, delete the debug intrinsics.
825 auto RemoveUses
= [&](StringRef Name
) {
826 if (auto *DbgVal
= M
.getFunction(Name
)) {
827 while (!DbgVal
->use_empty())
828 cast
<Instruction
>(DbgVal
->user_back())->eraseFromParent();
829 DbgVal
->eraseFromParent();
833 RemoveUses("llvm.dbg.declare");
834 RemoveUses("llvm.dbg.label");
835 RemoveUses("llvm.dbg.value");
837 // Delete non-CU debug info named metadata nodes.
838 for (auto NMI
= M
.named_metadata_begin(), NME
= M
.named_metadata_end();
840 NamedMDNode
*NMD
= &*NMI
;
842 // Specifically keep dbg.cu around.
843 if (NMD
->getName() == "llvm.dbg.cu")
847 // Drop all dbg attachments from global variables.
848 for (auto &GV
: M
.globals())
849 GV
.eraseMetadata(LLVMContext::MD_dbg
);
851 DebugTypeInfoRemoval
Mapper(M
.getContext());
852 auto remap
= [&](MDNode
*Node
) -> MDNode
* {
855 Mapper
.traverseAndRemap(Node
);
856 auto *NewNode
= Mapper
.mapNode(Node
);
857 Changed
|= Node
!= NewNode
;
862 // Rewrite the DebugLocs to be equivalent to what
863 // -gline-tables-only would have created.
865 if (auto *SP
= F
.getSubprogram()) {
866 Mapper
.traverseAndRemap(SP
);
867 auto *NewSP
= cast
<DISubprogram
>(Mapper
.mapNode(SP
));
868 Changed
|= SP
!= NewSP
;
869 F
.setSubprogram(NewSP
);
873 auto remapDebugLoc
= [&](const DebugLoc
&DL
) -> DebugLoc
{
874 auto *Scope
= DL
.getScope();
875 MDNode
*InlinedAt
= DL
.getInlinedAt();
876 Scope
= remap(Scope
);
877 InlinedAt
= remap(InlinedAt
);
878 return DILocation::get(M
.getContext(), DL
.getLine(), DL
.getCol(),
882 if (I
.getDebugLoc() != DebugLoc())
883 I
.setDebugLoc(remapDebugLoc(I
.getDebugLoc()));
885 // Remap DILocations in llvm.loop attachments.
886 updateLoopMetadataDebugLocations(I
, [&](Metadata
*MD
) -> Metadata
* {
887 if (auto *Loc
= dyn_cast_or_null
<DILocation
>(MD
))
888 return remapDebugLoc(Loc
).get();
892 // Strip heapallocsite attachments, they point into the DIType system.
893 if (I
.hasMetadataOtherThanDebugLoc())
894 I
.setMetadata("heapallocsite", nullptr);
899 // Create a new llvm.dbg.cu, which is equivalent to the one
900 // -gline-tables-only would have created.
901 for (auto &NMD
: M
.named_metadata()) {
902 SmallVector
<MDNode
*, 8> Ops
;
903 for (MDNode
*Op
: NMD
.operands())
904 Ops
.push_back(remap(Op
));
917 unsigned llvm::getDebugMetadataVersionFromModule(const Module
&M
) {
918 if (auto *Val
= mdconst::dyn_extract_or_null
<ConstantInt
>(
919 M
.getModuleFlag("Debug Info Version")))
920 return Val
->getZExtValue();
924 void Instruction::applyMergedLocation(DILocation
*LocA
, DILocation
*LocB
) {
925 setDebugLoc(DILocation::getMergedLocation(LocA
, LocB
));
928 void Instruction::mergeDIAssignID(
929 ArrayRef
<const Instruction
*> SourceInstructions
) {
930 // Replace all uses (and attachments) of all the DIAssignIDs
931 // on SourceInstructions with a single merged value.
932 assert(getFunction() && "Uninserted instruction merged");
933 // Collect up the DIAssignID tags.
934 SmallVector
<DIAssignID
*, 4> IDs
;
935 for (const Instruction
*I
: SourceInstructions
) {
936 if (auto *MD
= I
->getMetadata(LLVMContext::MD_DIAssignID
))
937 IDs
.push_back(cast
<DIAssignID
>(MD
));
938 assert(getFunction() == I
->getFunction() &&
939 "Merging with instruction from another function not allowed");
942 // Add this instruction's DIAssignID too, if it has one.
943 if (auto *MD
= getMetadata(LLVMContext::MD_DIAssignID
))
944 IDs
.push_back(cast
<DIAssignID
>(MD
));
947 return; // No DIAssignID tags to process.
949 DIAssignID
*MergeID
= IDs
[0];
950 for (auto It
= std::next(IDs
.begin()), End
= IDs
.end(); It
!= End
; ++It
) {
952 at::RAUW(*It
, MergeID
);
954 setMetadata(LLVMContext::MD_DIAssignID
, MergeID
);
957 void Instruction::updateLocationAfterHoist() { dropLocation(); }
959 void Instruction::dropLocation() {
960 const DebugLoc
&DL
= getDebugLoc();
964 // If this isn't a call, drop the location to allow a location from a
965 // preceding instruction to propagate.
966 bool MayLowerToCall
= false;
967 if (isa
<CallBase
>(this)) {
968 auto *II
= dyn_cast
<IntrinsicInst
>(this);
970 !II
|| IntrinsicInst::mayLowerToFunctionCall(II
->getIntrinsicID());
973 if (!MayLowerToCall
) {
974 setDebugLoc(DebugLoc());
978 // Set a line 0 location for calls to preserve scope information in case
980 DISubprogram
*SP
= getFunction()->getSubprogram();
982 // If a function scope is available, set it on the line 0 location. When
983 // hoisting a call to a predecessor block, using the function scope avoids
984 // making it look like the callee was reached earlier than it should be.
985 setDebugLoc(DILocation::get(getContext(), 0, 0, SP
));
987 // The parent function has no scope. Go ahead and drop the location. If
988 // the parent function is inlined, and the callee has a subprogram, the
989 // inliner will attach a location to the call.
991 // One alternative is to set a line 0 location with the existing scope and
992 // inlinedAt info. The location might be sensitive to when inlining occurs.
993 setDebugLoc(DebugLoc());
996 //===----------------------------------------------------------------------===//
997 // LLVM C API implementations.
998 //===----------------------------------------------------------------------===//
1000 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang
) {
1002 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
1003 case LLVMDWARFSourceLanguage##NAME: \
1005 #include "llvm/BinaryFormat/Dwarf.def"
1006 #undef HANDLE_DW_LANG
1008 llvm_unreachable("Unhandled Tag");
1011 template <typename DIT
> DIT
*unwrapDI(LLVMMetadataRef Ref
) {
1012 return (DIT
*)(Ref
? unwrap
<MDNode
>(Ref
) : nullptr);
1015 static DINode::DIFlags
map_from_llvmDIFlags(LLVMDIFlags Flags
) {
1016 return static_cast<DINode::DIFlags
>(Flags
);
1019 static LLVMDIFlags
map_to_llvmDIFlags(DINode::DIFlags Flags
) {
1020 return static_cast<LLVMDIFlags
>(Flags
);
1023 static DISubprogram::DISPFlags
1024 pack_into_DISPFlags(bool IsLocalToUnit
, bool IsDefinition
, bool IsOptimized
) {
1025 return DISubprogram::toSPFlags(IsLocalToUnit
, IsDefinition
, IsOptimized
);
1028 unsigned LLVMDebugMetadataVersion() {
1029 return DEBUG_METADATA_VERSION
;
1032 LLVMDIBuilderRef
LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M
) {
1033 return wrap(new DIBuilder(*unwrap(M
), false));
1036 LLVMDIBuilderRef
LLVMCreateDIBuilder(LLVMModuleRef M
) {
1037 return wrap(new DIBuilder(*unwrap(M
)));
1040 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M
) {
1041 return getDebugMetadataVersionFromModule(*unwrap(M
));
1044 LLVMBool
LLVMStripModuleDebugInfo(LLVMModuleRef M
) {
1045 return StripDebugInfo(*unwrap(M
));
1048 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder
) {
1049 delete unwrap(Builder
);
1052 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder
) {
1053 unwrap(Builder
)->finalize();
1056 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder
,
1057 LLVMMetadataRef subprogram
) {
1058 unwrap(Builder
)->finalizeSubprogram(unwrapDI
<DISubprogram
>(subprogram
));
1061 LLVMMetadataRef
LLVMDIBuilderCreateCompileUnit(
1062 LLVMDIBuilderRef Builder
, LLVMDWARFSourceLanguage Lang
,
1063 LLVMMetadataRef FileRef
, const char *Producer
, size_t ProducerLen
,
1064 LLVMBool isOptimized
, const char *Flags
, size_t FlagsLen
,
1065 unsigned RuntimeVer
, const char *SplitName
, size_t SplitNameLen
,
1066 LLVMDWARFEmissionKind Kind
, unsigned DWOId
, LLVMBool SplitDebugInlining
,
1067 LLVMBool DebugInfoForProfiling
, const char *SysRoot
, size_t SysRootLen
,
1068 const char *SDK
, size_t SDKLen
) {
1069 auto File
= unwrapDI
<DIFile
>(FileRef
);
1071 return wrap(unwrap(Builder
)->createCompileUnit(
1072 map_from_llvmDWARFsourcelanguage(Lang
), File
,
1073 StringRef(Producer
, ProducerLen
), isOptimized
, StringRef(Flags
, FlagsLen
),
1074 RuntimeVer
, StringRef(SplitName
, SplitNameLen
),
1075 static_cast<DICompileUnit::DebugEmissionKind
>(Kind
), DWOId
,
1076 SplitDebugInlining
, DebugInfoForProfiling
,
1077 DICompileUnit::DebugNameTableKind::Default
, false,
1078 StringRef(SysRoot
, SysRootLen
), StringRef(SDK
, SDKLen
)));
1082 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder
, const char *Filename
,
1083 size_t FilenameLen
, const char *Directory
,
1084 size_t DirectoryLen
) {
1085 return wrap(unwrap(Builder
)->createFile(StringRef(Filename
, FilenameLen
),
1086 StringRef(Directory
, DirectoryLen
)));
1090 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder
, LLVMMetadataRef ParentScope
,
1091 const char *Name
, size_t NameLen
,
1092 const char *ConfigMacros
, size_t ConfigMacrosLen
,
1093 const char *IncludePath
, size_t IncludePathLen
,
1094 const char *APINotesFile
, size_t APINotesFileLen
) {
1095 return wrap(unwrap(Builder
)->createModule(
1096 unwrapDI
<DIScope
>(ParentScope
), StringRef(Name
, NameLen
),
1097 StringRef(ConfigMacros
, ConfigMacrosLen
),
1098 StringRef(IncludePath
, IncludePathLen
),
1099 StringRef(APINotesFile
, APINotesFileLen
)));
1102 LLVMMetadataRef
LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder
,
1103 LLVMMetadataRef ParentScope
,
1104 const char *Name
, size_t NameLen
,
1105 LLVMBool ExportSymbols
) {
1106 return wrap(unwrap(Builder
)->createNameSpace(
1107 unwrapDI
<DIScope
>(ParentScope
), StringRef(Name
, NameLen
), ExportSymbols
));
1110 LLVMMetadataRef
LLVMDIBuilderCreateFunction(
1111 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1112 size_t NameLen
, const char *LinkageName
, size_t LinkageNameLen
,
1113 LLVMMetadataRef File
, unsigned LineNo
, LLVMMetadataRef Ty
,
1114 LLVMBool IsLocalToUnit
, LLVMBool IsDefinition
,
1115 unsigned ScopeLine
, LLVMDIFlags Flags
, LLVMBool IsOptimized
) {
1116 return wrap(unwrap(Builder
)->createFunction(
1117 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, {LinkageName
, LinkageNameLen
},
1118 unwrapDI
<DIFile
>(File
), LineNo
, unwrapDI
<DISubroutineType
>(Ty
), ScopeLine
,
1119 map_from_llvmDIFlags(Flags
),
1120 pack_into_DISPFlags(IsLocalToUnit
, IsDefinition
, IsOptimized
), nullptr,
1125 LLVMMetadataRef
LLVMDIBuilderCreateLexicalBlock(
1126 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
,
1127 LLVMMetadataRef File
, unsigned Line
, unsigned Col
) {
1128 return wrap(unwrap(Builder
)->createLexicalBlock(unwrapDI
<DIScope
>(Scope
),
1129 unwrapDI
<DIFile
>(File
),
1134 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder
,
1135 LLVMMetadataRef Scope
,
1136 LLVMMetadataRef File
,
1137 unsigned Discriminator
) {
1138 return wrap(unwrap(Builder
)->createLexicalBlockFile(unwrapDI
<DIScope
>(Scope
),
1139 unwrapDI
<DIFile
>(File
),
1144 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder
,
1145 LLVMMetadataRef Scope
,
1147 LLVMMetadataRef File
,
1149 return wrap(unwrap(Builder
)->createImportedModule(unwrapDI
<DIScope
>(Scope
),
1150 unwrapDI
<DINamespace
>(NS
),
1151 unwrapDI
<DIFile
>(File
),
1155 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromAlias(
1156 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
,
1157 LLVMMetadataRef ImportedEntity
, LLVMMetadataRef File
, unsigned Line
,
1158 LLVMMetadataRef
*Elements
, unsigned NumElements
) {
1161 ? unwrap(Builder
)->getOrCreateArray({unwrap(Elements
), NumElements
})
1163 return wrap(unwrap(Builder
)->createImportedModule(
1164 unwrapDI
<DIScope
>(Scope
), unwrapDI
<DIImportedEntity
>(ImportedEntity
),
1165 unwrapDI
<DIFile
>(File
), Line
, Elts
));
1168 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromModule(
1169 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, LLVMMetadataRef M
,
1170 LLVMMetadataRef File
, unsigned Line
, LLVMMetadataRef
*Elements
,
1171 unsigned NumElements
) {
1174 ? unwrap(Builder
)->getOrCreateArray({unwrap(Elements
), NumElements
})
1176 return wrap(unwrap(Builder
)->createImportedModule(
1177 unwrapDI
<DIScope
>(Scope
), unwrapDI
<DIModule
>(M
), unwrapDI
<DIFile
>(File
),
1181 LLVMMetadataRef
LLVMDIBuilderCreateImportedDeclaration(
1182 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, LLVMMetadataRef Decl
,
1183 LLVMMetadataRef File
, unsigned Line
, const char *Name
, size_t NameLen
,
1184 LLVMMetadataRef
*Elements
, unsigned NumElements
) {
1187 ? unwrap(Builder
)->getOrCreateArray({unwrap(Elements
), NumElements
})
1189 return wrap(unwrap(Builder
)->createImportedDeclaration(
1190 unwrapDI
<DIScope
>(Scope
), unwrapDI
<DINode
>(Decl
), unwrapDI
<DIFile
>(File
),
1191 Line
, {Name
, NameLen
}, Elts
));
1195 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx
, unsigned Line
,
1196 unsigned Column
, LLVMMetadataRef Scope
,
1197 LLVMMetadataRef InlinedAt
) {
1198 return wrap(DILocation::get(*unwrap(Ctx
), Line
, Column
, unwrap(Scope
),
1199 unwrap(InlinedAt
)));
1202 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location
) {
1203 return unwrapDI
<DILocation
>(Location
)->getLine();
1206 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location
) {
1207 return unwrapDI
<DILocation
>(Location
)->getColumn();
1210 LLVMMetadataRef
LLVMDILocationGetScope(LLVMMetadataRef Location
) {
1211 return wrap(unwrapDI
<DILocation
>(Location
)->getScope());
1214 LLVMMetadataRef
LLVMDILocationGetInlinedAt(LLVMMetadataRef Location
) {
1215 return wrap(unwrapDI
<DILocation
>(Location
)->getInlinedAt());
1218 LLVMMetadataRef
LLVMDIScopeGetFile(LLVMMetadataRef Scope
) {
1219 return wrap(unwrapDI
<DIScope
>(Scope
)->getFile());
1222 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File
, unsigned *Len
) {
1223 auto Dir
= unwrapDI
<DIFile
>(File
)->getDirectory();
1228 const char *LLVMDIFileGetFilename(LLVMMetadataRef File
, unsigned *Len
) {
1229 auto Name
= unwrapDI
<DIFile
>(File
)->getFilename();
1234 const char *LLVMDIFileGetSource(LLVMMetadataRef File
, unsigned *Len
) {
1235 if (auto Src
= unwrapDI
<DIFile
>(File
)->getSource()) {
1243 LLVMMetadataRef
LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder
,
1244 LLVMMetadataRef ParentMacroFile
,
1246 LLVMDWARFMacinfoRecordType RecordType
,
1247 const char *Name
, size_t NameLen
,
1248 const char *Value
, size_t ValueLen
) {
1250 unwrap(Builder
)->createMacro(unwrapDI
<DIMacroFile
>(ParentMacroFile
), Line
,
1251 static_cast<MacinfoRecordType
>(RecordType
),
1252 {Name
, NameLen
}, {Value
, ValueLen
}));
1256 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder
,
1257 LLVMMetadataRef ParentMacroFile
, unsigned Line
,
1258 LLVMMetadataRef File
) {
1259 return wrap(unwrap(Builder
)->createTempMacroFile(
1260 unwrapDI
<DIMacroFile
>(ParentMacroFile
), Line
, unwrapDI
<DIFile
>(File
)));
1263 LLVMMetadataRef
LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder
,
1264 const char *Name
, size_t NameLen
,
1266 LLVMBool IsUnsigned
) {
1267 return wrap(unwrap(Builder
)->createEnumerator({Name
, NameLen
}, Value
,
1271 LLVMMetadataRef
LLVMDIBuilderCreateEnumerationType(
1272 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1273 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNumber
,
1274 uint64_t SizeInBits
, uint32_t AlignInBits
, LLVMMetadataRef
*Elements
,
1275 unsigned NumElements
, LLVMMetadataRef ClassTy
) {
1276 auto Elts
= unwrap(Builder
)->getOrCreateArray({unwrap(Elements
),
1278 return wrap(unwrap(Builder
)->createEnumerationType(
1279 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
),
1280 LineNumber
, SizeInBits
, AlignInBits
, Elts
, unwrapDI
<DIType
>(ClassTy
)));
1283 LLVMMetadataRef
LLVMDIBuilderCreateUnionType(
1284 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1285 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNumber
,
1286 uint64_t SizeInBits
, uint32_t AlignInBits
, LLVMDIFlags Flags
,
1287 LLVMMetadataRef
*Elements
, unsigned NumElements
, unsigned RunTimeLang
,
1288 const char *UniqueId
, size_t UniqueIdLen
) {
1289 auto Elts
= unwrap(Builder
)->getOrCreateArray({unwrap(Elements
),
1291 return wrap(unwrap(Builder
)->createUnionType(
1292 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
),
1293 LineNumber
, SizeInBits
, AlignInBits
, map_from_llvmDIFlags(Flags
),
1294 Elts
, RunTimeLang
, {UniqueId
, UniqueIdLen
}));
1299 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder
, uint64_t Size
,
1300 uint32_t AlignInBits
, LLVMMetadataRef Ty
,
1301 LLVMMetadataRef
*Subscripts
,
1302 unsigned NumSubscripts
) {
1303 auto Subs
= unwrap(Builder
)->getOrCreateArray({unwrap(Subscripts
),
1305 return wrap(unwrap(Builder
)->createArrayType(Size
, AlignInBits
,
1306 unwrapDI
<DIType
>(Ty
), Subs
));
1310 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder
, uint64_t Size
,
1311 uint32_t AlignInBits
, LLVMMetadataRef Ty
,
1312 LLVMMetadataRef
*Subscripts
,
1313 unsigned NumSubscripts
) {
1314 auto Subs
= unwrap(Builder
)->getOrCreateArray({unwrap(Subscripts
),
1316 return wrap(unwrap(Builder
)->createVectorType(Size
, AlignInBits
,
1317 unwrapDI
<DIType
>(Ty
), Subs
));
1321 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder
, const char *Name
,
1322 size_t NameLen
, uint64_t SizeInBits
,
1323 LLVMDWARFTypeEncoding Encoding
,
1324 LLVMDIFlags Flags
) {
1325 return wrap(unwrap(Builder
)->createBasicType({Name
, NameLen
},
1326 SizeInBits
, Encoding
,
1327 map_from_llvmDIFlags(Flags
)));
1330 LLVMMetadataRef
LLVMDIBuilderCreatePointerType(
1331 LLVMDIBuilderRef Builder
, LLVMMetadataRef PointeeTy
,
1332 uint64_t SizeInBits
, uint32_t AlignInBits
, unsigned AddressSpace
,
1333 const char *Name
, size_t NameLen
) {
1334 return wrap(unwrap(Builder
)->createPointerType(unwrapDI
<DIType
>(PointeeTy
),
1335 SizeInBits
, AlignInBits
,
1336 AddressSpace
, {Name
, NameLen
}));
1339 LLVMMetadataRef
LLVMDIBuilderCreateStructType(
1340 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1341 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNumber
,
1342 uint64_t SizeInBits
, uint32_t AlignInBits
, LLVMDIFlags Flags
,
1343 LLVMMetadataRef DerivedFrom
, LLVMMetadataRef
*Elements
,
1344 unsigned NumElements
, unsigned RunTimeLang
, LLVMMetadataRef VTableHolder
,
1345 const char *UniqueId
, size_t UniqueIdLen
) {
1346 auto Elts
= unwrap(Builder
)->getOrCreateArray({unwrap(Elements
),
1348 return wrap(unwrap(Builder
)->createStructType(
1349 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
),
1350 LineNumber
, SizeInBits
, AlignInBits
, map_from_llvmDIFlags(Flags
),
1351 unwrapDI
<DIType
>(DerivedFrom
), Elts
, RunTimeLang
,
1352 unwrapDI
<DIType
>(VTableHolder
), {UniqueId
, UniqueIdLen
}));
1355 LLVMMetadataRef
LLVMDIBuilderCreateMemberType(
1356 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1357 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNo
, uint64_t SizeInBits
,
1358 uint32_t AlignInBits
, uint64_t OffsetInBits
, LLVMDIFlags Flags
,
1359 LLVMMetadataRef Ty
) {
1360 return wrap(unwrap(Builder
)->createMemberType(unwrapDI
<DIScope
>(Scope
),
1361 {Name
, NameLen
}, unwrapDI
<DIFile
>(File
), LineNo
, SizeInBits
, AlignInBits
,
1362 OffsetInBits
, map_from_llvmDIFlags(Flags
), unwrapDI
<DIType
>(Ty
)));
1366 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder
, const char *Name
,
1368 return wrap(unwrap(Builder
)->createUnspecifiedType({Name
, NameLen
}));
1371 LLVMMetadataRef
LLVMDIBuilderCreateStaticMemberType(
1372 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1373 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNumber
,
1374 LLVMMetadataRef Type
, LLVMDIFlags Flags
, LLVMValueRef ConstantVal
,
1375 uint32_t AlignInBits
) {
1376 return wrap(unwrap(Builder
)->createStaticMemberType(
1377 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
),
1378 LineNumber
, unwrapDI
<DIType
>(Type
), map_from_llvmDIFlags(Flags
),
1379 unwrap
<Constant
>(ConstantVal
), DW_TAG_member
, AlignInBits
));
1383 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder
,
1384 const char *Name
, size_t NameLen
,
1385 LLVMMetadataRef File
, unsigned LineNo
,
1386 uint64_t SizeInBits
, uint32_t AlignInBits
,
1387 uint64_t OffsetInBits
, LLVMDIFlags Flags
,
1388 LLVMMetadataRef Ty
, LLVMMetadataRef PropertyNode
) {
1389 return wrap(unwrap(Builder
)->createObjCIVar(
1390 {Name
, NameLen
}, unwrapDI
<DIFile
>(File
), LineNo
,
1391 SizeInBits
, AlignInBits
, OffsetInBits
,
1392 map_from_llvmDIFlags(Flags
), unwrapDI
<DIType
>(Ty
),
1393 unwrapDI
<MDNode
>(PropertyNode
)));
1397 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder
,
1398 const char *Name
, size_t NameLen
,
1399 LLVMMetadataRef File
, unsigned LineNo
,
1400 const char *GetterName
, size_t GetterNameLen
,
1401 const char *SetterName
, size_t SetterNameLen
,
1402 unsigned PropertyAttributes
,
1403 LLVMMetadataRef Ty
) {
1404 return wrap(unwrap(Builder
)->createObjCProperty(
1405 {Name
, NameLen
}, unwrapDI
<DIFile
>(File
), LineNo
,
1406 {GetterName
, GetterNameLen
}, {SetterName
, SetterNameLen
},
1407 PropertyAttributes
, unwrapDI
<DIType
>(Ty
)));
1411 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder
,
1412 LLVMMetadataRef Type
) {
1413 return wrap(unwrap(Builder
)->createObjectPointerType(unwrapDI
<DIType
>(Type
)));
1417 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder
, LLVMMetadataRef Type
,
1418 const char *Name
, size_t NameLen
,
1419 LLVMMetadataRef File
, unsigned LineNo
,
1420 LLVMMetadataRef Scope
, uint32_t AlignInBits
) {
1421 return wrap(unwrap(Builder
)->createTypedef(
1422 unwrapDI
<DIType
>(Type
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
), LineNo
,
1423 unwrapDI
<DIScope
>(Scope
), AlignInBits
));
1427 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder
,
1428 LLVMMetadataRef Ty
, LLVMMetadataRef BaseTy
,
1429 uint64_t BaseOffset
, uint32_t VBPtrOffset
,
1430 LLVMDIFlags Flags
) {
1431 return wrap(unwrap(Builder
)->createInheritance(
1432 unwrapDI
<DIType
>(Ty
), unwrapDI
<DIType
>(BaseTy
),
1433 BaseOffset
, VBPtrOffset
, map_from_llvmDIFlags(Flags
)));
1437 LLVMDIBuilderCreateForwardDecl(
1438 LLVMDIBuilderRef Builder
, unsigned Tag
, const char *Name
,
1439 size_t NameLen
, LLVMMetadataRef Scope
, LLVMMetadataRef File
, unsigned Line
,
1440 unsigned RuntimeLang
, uint64_t SizeInBits
, uint32_t AlignInBits
,
1441 const char *UniqueIdentifier
, size_t UniqueIdentifierLen
) {
1442 return wrap(unwrap(Builder
)->createForwardDecl(
1443 Tag
, {Name
, NameLen
}, unwrapDI
<DIScope
>(Scope
),
1444 unwrapDI
<DIFile
>(File
), Line
, RuntimeLang
, SizeInBits
,
1445 AlignInBits
, {UniqueIdentifier
, UniqueIdentifierLen
}));
1449 LLVMDIBuilderCreateReplaceableCompositeType(
1450 LLVMDIBuilderRef Builder
, unsigned Tag
, const char *Name
,
1451 size_t NameLen
, LLVMMetadataRef Scope
, LLVMMetadataRef File
, unsigned Line
,
1452 unsigned RuntimeLang
, uint64_t SizeInBits
, uint32_t AlignInBits
,
1453 LLVMDIFlags Flags
, const char *UniqueIdentifier
,
1454 size_t UniqueIdentifierLen
) {
1455 return wrap(unwrap(Builder
)->createReplaceableCompositeType(
1456 Tag
, {Name
, NameLen
}, unwrapDI
<DIScope
>(Scope
),
1457 unwrapDI
<DIFile
>(File
), Line
, RuntimeLang
, SizeInBits
,
1458 AlignInBits
, map_from_llvmDIFlags(Flags
),
1459 {UniqueIdentifier
, UniqueIdentifierLen
}));
1463 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder
, unsigned Tag
,
1464 LLVMMetadataRef Type
) {
1465 return wrap(unwrap(Builder
)->createQualifiedType(Tag
,
1466 unwrapDI
<DIType
>(Type
)));
1470 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder
, unsigned Tag
,
1471 LLVMMetadataRef Type
) {
1472 return wrap(unwrap(Builder
)->createReferenceType(Tag
,
1473 unwrapDI
<DIType
>(Type
)));
1477 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder
) {
1478 return wrap(unwrap(Builder
)->createNullPtrType());
1482 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder
,
1483 LLVMMetadataRef PointeeType
,
1484 LLVMMetadataRef ClassType
,
1485 uint64_t SizeInBits
,
1486 uint32_t AlignInBits
,
1487 LLVMDIFlags Flags
) {
1488 return wrap(unwrap(Builder
)->createMemberPointerType(
1489 unwrapDI
<DIType
>(PointeeType
),
1490 unwrapDI
<DIType
>(ClassType
), AlignInBits
, SizeInBits
,
1491 map_from_llvmDIFlags(Flags
)));
1495 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder
,
1496 LLVMMetadataRef Scope
,
1497 const char *Name
, size_t NameLen
,
1498 LLVMMetadataRef File
, unsigned LineNumber
,
1499 uint64_t SizeInBits
,
1500 uint64_t OffsetInBits
,
1501 uint64_t StorageOffsetInBits
,
1502 LLVMDIFlags Flags
, LLVMMetadataRef Type
) {
1503 return wrap(unwrap(Builder
)->createBitFieldMemberType(
1504 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
},
1505 unwrapDI
<DIFile
>(File
), LineNumber
,
1506 SizeInBits
, OffsetInBits
, StorageOffsetInBits
,
1507 map_from_llvmDIFlags(Flags
), unwrapDI
<DIType
>(Type
)));
1510 LLVMMetadataRef
LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder
,
1511 LLVMMetadataRef Scope
, const char *Name
, size_t NameLen
,
1512 LLVMMetadataRef File
, unsigned LineNumber
, uint64_t SizeInBits
,
1513 uint32_t AlignInBits
, uint64_t OffsetInBits
, LLVMDIFlags Flags
,
1514 LLVMMetadataRef DerivedFrom
,
1515 LLVMMetadataRef
*Elements
, unsigned NumElements
,
1516 LLVMMetadataRef VTableHolder
, LLVMMetadataRef TemplateParamsNode
,
1517 const char *UniqueIdentifier
, size_t UniqueIdentifierLen
) {
1518 auto Elts
= unwrap(Builder
)->getOrCreateArray({unwrap(Elements
),
1520 return wrap(unwrap(Builder
)->createClassType(
1521 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, unwrapDI
<DIFile
>(File
),
1522 LineNumber
, SizeInBits
, AlignInBits
, OffsetInBits
,
1523 map_from_llvmDIFlags(Flags
), unwrapDI
<DIType
>(DerivedFrom
), Elts
,
1524 /*RunTimeLang=*/0, unwrapDI
<DIType
>(VTableHolder
),
1525 unwrapDI
<MDNode
>(TemplateParamsNode
),
1526 {UniqueIdentifier
, UniqueIdentifierLen
}));
1530 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder
,
1531 LLVMMetadataRef Type
) {
1532 return wrap(unwrap(Builder
)->createArtificialType(unwrapDI
<DIType
>(Type
)));
1535 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD
) {
1536 return unwrapDI
<DINode
>(MD
)->getTag();
1539 const char *LLVMDITypeGetName(LLVMMetadataRef DType
, size_t *Length
) {
1540 StringRef Str
= unwrapDI
<DIType
>(DType
)->getName();
1541 *Length
= Str
.size();
1545 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType
) {
1546 return unwrapDI
<DIType
>(DType
)->getSizeInBits();
1549 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType
) {
1550 return unwrapDI
<DIType
>(DType
)->getOffsetInBits();
1553 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType
) {
1554 return unwrapDI
<DIType
>(DType
)->getAlignInBits();
1557 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType
) {
1558 return unwrapDI
<DIType
>(DType
)->getLine();
1561 LLVMDIFlags
LLVMDITypeGetFlags(LLVMMetadataRef DType
) {
1562 return map_to_llvmDIFlags(unwrapDI
<DIType
>(DType
)->getFlags());
1565 LLVMMetadataRef
LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder
,
1566 LLVMMetadataRef
*Types
,
1569 unwrap(Builder
)->getOrCreateTypeArray({unwrap(Types
), Length
}).get());
1573 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder
,
1574 LLVMMetadataRef File
,
1575 LLVMMetadataRef
*ParameterTypes
,
1576 unsigned NumParameterTypes
,
1577 LLVMDIFlags Flags
) {
1578 auto Elts
= unwrap(Builder
)->getOrCreateTypeArray({unwrap(ParameterTypes
),
1579 NumParameterTypes
});
1580 return wrap(unwrap(Builder
)->createSubroutineType(
1581 Elts
, map_from_llvmDIFlags(Flags
)));
1584 LLVMMetadataRef
LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder
,
1585 uint64_t *Addr
, size_t Length
) {
1587 unwrap(Builder
)->createExpression(ArrayRef
<uint64_t>(Addr
, Length
)));
1591 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder
,
1593 return wrap(unwrap(Builder
)->createConstantValueExpression(Value
));
1596 LLVMMetadataRef
LLVMDIBuilderCreateGlobalVariableExpression(
1597 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1598 size_t NameLen
, const char *Linkage
, size_t LinkLen
, LLVMMetadataRef File
,
1599 unsigned LineNo
, LLVMMetadataRef Ty
, LLVMBool LocalToUnit
,
1600 LLVMMetadataRef Expr
, LLVMMetadataRef Decl
, uint32_t AlignInBits
) {
1601 return wrap(unwrap(Builder
)->createGlobalVariableExpression(
1602 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, {Linkage
, LinkLen
},
1603 unwrapDI
<DIFile
>(File
), LineNo
, unwrapDI
<DIType
>(Ty
), LocalToUnit
,
1604 true, unwrap
<DIExpression
>(Expr
), unwrapDI
<MDNode
>(Decl
),
1605 nullptr, AlignInBits
));
1608 LLVMMetadataRef
LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE
) {
1609 return wrap(unwrapDI
<DIGlobalVariableExpression
>(GVE
)->getVariable());
1612 LLVMMetadataRef
LLVMDIGlobalVariableExpressionGetExpression(
1613 LLVMMetadataRef GVE
) {
1614 return wrap(unwrapDI
<DIGlobalVariableExpression
>(GVE
)->getExpression());
1617 LLVMMetadataRef
LLVMDIVariableGetFile(LLVMMetadataRef Var
) {
1618 return wrap(unwrapDI
<DIVariable
>(Var
)->getFile());
1621 LLVMMetadataRef
LLVMDIVariableGetScope(LLVMMetadataRef Var
) {
1622 return wrap(unwrapDI
<DIVariable
>(Var
)->getScope());
1625 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var
) {
1626 return unwrapDI
<DIVariable
>(Var
)->getLine();
1629 LLVMMetadataRef
LLVMTemporaryMDNode(LLVMContextRef Ctx
, LLVMMetadataRef
*Data
,
1632 MDTuple::getTemporary(*unwrap(Ctx
), {unwrap(Data
), Count
}).release());
1635 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode
) {
1636 MDNode::deleteTemporary(unwrapDI
<MDNode
>(TempNode
));
1639 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata
,
1640 LLVMMetadataRef Replacement
) {
1641 auto *Node
= unwrapDI
<MDNode
>(TargetMetadata
);
1642 Node
->replaceAllUsesWith(unwrap(Replacement
));
1643 MDNode::deleteTemporary(Node
);
1646 LLVMMetadataRef
LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1647 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1648 size_t NameLen
, const char *Linkage
, size_t LnkLen
, LLVMMetadataRef File
,
1649 unsigned LineNo
, LLVMMetadataRef Ty
, LLVMBool LocalToUnit
,
1650 LLVMMetadataRef Decl
, uint32_t AlignInBits
) {
1651 return wrap(unwrap(Builder
)->createTempGlobalVariableFwdDecl(
1652 unwrapDI
<DIScope
>(Scope
), {Name
, NameLen
}, {Linkage
, LnkLen
},
1653 unwrapDI
<DIFile
>(File
), LineNo
, unwrapDI
<DIType
>(Ty
), LocalToUnit
,
1654 unwrapDI
<MDNode
>(Decl
), nullptr, AlignInBits
));
1658 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder
, LLVMValueRef Storage
,
1659 LLVMMetadataRef VarInfo
, LLVMMetadataRef Expr
,
1660 LLVMMetadataRef DL
, LLVMValueRef Instr
) {
1661 return wrap(unwrap(Builder
)->insertDeclare(
1662 unwrap(Storage
), unwrap
<DILocalVariable
>(VarInfo
),
1663 unwrap
<DIExpression
>(Expr
), unwrap
<DILocation
>(DL
),
1664 unwrap
<Instruction
>(Instr
)));
1667 LLVMValueRef
LLVMDIBuilderInsertDeclareAtEnd(
1668 LLVMDIBuilderRef Builder
, LLVMValueRef Storage
, LLVMMetadataRef VarInfo
,
1669 LLVMMetadataRef Expr
, LLVMMetadataRef DL
, LLVMBasicBlockRef Block
) {
1670 return wrap(unwrap(Builder
)->insertDeclare(
1671 unwrap(Storage
), unwrap
<DILocalVariable
>(VarInfo
),
1672 unwrap
<DIExpression
>(Expr
), unwrap
<DILocation
>(DL
),
1676 LLVMValueRef
LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder
,
1678 LLVMMetadataRef VarInfo
,
1679 LLVMMetadataRef Expr
,
1680 LLVMMetadataRef DebugLoc
,
1681 LLVMValueRef Instr
) {
1682 return wrap(unwrap(Builder
)->insertDbgValueIntrinsic(
1683 unwrap(Val
), unwrap
<DILocalVariable
>(VarInfo
),
1684 unwrap
<DIExpression
>(Expr
), unwrap
<DILocation
>(DebugLoc
),
1685 unwrap
<Instruction
>(Instr
)));
1688 LLVMValueRef
LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder
,
1690 LLVMMetadataRef VarInfo
,
1691 LLVMMetadataRef Expr
,
1692 LLVMMetadataRef DebugLoc
,
1693 LLVMBasicBlockRef Block
) {
1694 return wrap(unwrap(Builder
)->insertDbgValueIntrinsic(
1695 unwrap(Val
), unwrap
<DILocalVariable
>(VarInfo
),
1696 unwrap
<DIExpression
>(Expr
), unwrap
<DILocation
>(DebugLoc
),
1700 LLVMMetadataRef
LLVMDIBuilderCreateAutoVariable(
1701 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1702 size_t NameLen
, LLVMMetadataRef File
, unsigned LineNo
, LLVMMetadataRef Ty
,
1703 LLVMBool AlwaysPreserve
, LLVMDIFlags Flags
, uint32_t AlignInBits
) {
1704 return wrap(unwrap(Builder
)->createAutoVariable(
1705 unwrap
<DIScope
>(Scope
), {Name
, NameLen
}, unwrap
<DIFile
>(File
),
1706 LineNo
, unwrap
<DIType
>(Ty
), AlwaysPreserve
,
1707 map_from_llvmDIFlags(Flags
), AlignInBits
));
1710 LLVMMetadataRef
LLVMDIBuilderCreateParameterVariable(
1711 LLVMDIBuilderRef Builder
, LLVMMetadataRef Scope
, const char *Name
,
1712 size_t NameLen
, unsigned ArgNo
, LLVMMetadataRef File
, unsigned LineNo
,
1713 LLVMMetadataRef Ty
, LLVMBool AlwaysPreserve
, LLVMDIFlags Flags
) {
1714 return wrap(unwrap(Builder
)->createParameterVariable(
1715 unwrap
<DIScope
>(Scope
), {Name
, NameLen
}, ArgNo
, unwrap
<DIFile
>(File
),
1716 LineNo
, unwrap
<DIType
>(Ty
), AlwaysPreserve
,
1717 map_from_llvmDIFlags(Flags
)));
1720 LLVMMetadataRef
LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder
,
1721 int64_t Lo
, int64_t Count
) {
1722 return wrap(unwrap(Builder
)->getOrCreateSubrange(Lo
, Count
));
1725 LLVMMetadataRef
LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder
,
1726 LLVMMetadataRef
*Data
,
1728 Metadata
**DataValue
= unwrap(Data
);
1729 return wrap(unwrap(Builder
)->getOrCreateArray({DataValue
, Length
}).get());
1732 LLVMMetadataRef
LLVMGetSubprogram(LLVMValueRef Func
) {
1733 return wrap(unwrap
<Function
>(Func
)->getSubprogram());
1736 void LLVMSetSubprogram(LLVMValueRef Func
, LLVMMetadataRef SP
) {
1737 unwrap
<Function
>(Func
)->setSubprogram(unwrap
<DISubprogram
>(SP
));
1740 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram
) {
1741 return unwrapDI
<DISubprogram
>(Subprogram
)->getLine();
1744 LLVMMetadataRef
LLVMInstructionGetDebugLoc(LLVMValueRef Inst
) {
1745 return wrap(unwrap
<Instruction
>(Inst
)->getDebugLoc().getAsMDNode());
1748 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst
, LLVMMetadataRef Loc
) {
1750 unwrap
<Instruction
>(Inst
)->setDebugLoc(DebugLoc(unwrap
<MDNode
>(Loc
)));
1752 unwrap
<Instruction
>(Inst
)->setDebugLoc(DebugLoc());
1755 LLVMMetadataKind
LLVMGetMetadataKind(LLVMMetadataRef Metadata
) {
1756 switch(unwrap(Metadata
)->getMetadataID()) {
1757 #define HANDLE_METADATA_LEAF(CLASS) \
1758 case Metadata::CLASS##Kind: \
1759 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1760 #include "llvm/IR/Metadata.def"
1762 return (LLVMMetadataKind
)LLVMGenericDINodeMetadataKind
;
1766 AssignmentInstRange
at::getAssignmentInsts(DIAssignID
*ID
) {
1767 assert(ID
&& "Expected non-null ID");
1768 LLVMContext
&Ctx
= ID
->getContext();
1769 auto &Map
= Ctx
.pImpl
->AssignmentIDToInstrs
;
1771 auto MapIt
= Map
.find(ID
);
1772 if (MapIt
== Map
.end())
1773 return make_range(nullptr, nullptr);
1775 return make_range(MapIt
->second
.begin(), MapIt
->second
.end());
1778 AssignmentMarkerRange
at::getAssignmentMarkers(DIAssignID
*ID
) {
1779 assert(ID
&& "Expected non-null ID");
1780 LLVMContext
&Ctx
= ID
->getContext();
1782 auto *IDAsValue
= MetadataAsValue::getIfExists(Ctx
, ID
);
1784 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
1785 // one of those already exists first.
1787 return make_range(Value::user_iterator(), Value::user_iterator());
1789 return make_range(IDAsValue
->user_begin(), IDAsValue
->user_end());
1792 void at::deleteAssignmentMarkers(const Instruction
*Inst
) {
1793 auto Range
= getAssignmentMarkers(Inst
);
1794 SmallVector
<DPValue
*> DPVAssigns
= getDPVAssignmentMarkers(Inst
);
1795 if (Range
.empty() && DPVAssigns
.empty())
1797 SmallVector
<DbgAssignIntrinsic
*> ToDelete(Range
.begin(), Range
.end());
1798 for (auto *DAI
: ToDelete
)
1799 DAI
->eraseFromParent();
1800 for (auto *DPV
: DPVAssigns
)
1801 DPV
->eraseFromParent();
1804 void at::RAUW(DIAssignID
*Old
, DIAssignID
*New
) {
1805 // Replace attachments.
1806 AssignmentInstRange InstRange
= getAssignmentInsts(Old
);
1807 // Use intermediate storage for the instruction ptrs because the
1808 // getAssignmentInsts range iterators will be invalidated by adding and
1809 // removing DIAssignID attachments.
1810 SmallVector
<Instruction
*> InstVec(InstRange
.begin(), InstRange
.end());
1811 for (auto *I
: InstVec
)
1812 I
->setMetadata(LLVMContext::MD_DIAssignID
, New
);
1814 Old
->replaceAllUsesWith(New
);
1817 void at::deleteAll(Function
*F
) {
1818 SmallVector
<DbgAssignIntrinsic
*, 12> ToDelete
;
1819 for (BasicBlock
&BB
: *F
) {
1820 for (Instruction
&I
: BB
) {
1821 if (auto *DAI
= dyn_cast
<DbgAssignIntrinsic
>(&I
))
1822 ToDelete
.push_back(DAI
);
1824 I
.setMetadata(LLVMContext::MD_DIAssignID
, nullptr);
1827 for (auto *DAI
: ToDelete
)
1828 DAI
->eraseFromParent();
1831 /// Get the FragmentInfo for the variable if it exists, otherwise return a
1832 /// FragmentInfo that covers the entire variable if the variable size is
1833 /// known, otherwise return a zero-sized fragment.
1834 static DIExpression::FragmentInfo
1835 getFragmentOrEntireVariable(const DPValue
*DPV
) {
1836 DIExpression::FragmentInfo
VariableSlice(0, 0);
1837 // Get the fragment or variable size, or zero.
1838 if (auto Sz
= DPV
->getFragmentSizeInBits())
1839 VariableSlice
.SizeInBits
= *Sz
;
1840 if (auto Frag
= DPV
->getExpression()->getFragmentInfo())
1841 VariableSlice
.OffsetInBits
= Frag
->OffsetInBits
;
1842 return VariableSlice
;
1845 static DIExpression::FragmentInfo
1846 getFragmentOrEntireVariable(const DbgVariableIntrinsic
*DVI
) {
1847 DIExpression::FragmentInfo
VariableSlice(0, 0);
1848 // Get the fragment or variable size, or zero.
1849 if (auto Sz
= DVI
->getFragmentSizeInBits())
1850 VariableSlice
.SizeInBits
= *Sz
;
1851 if (auto Frag
= DVI
->getExpression()->getFragmentInfo())
1852 VariableSlice
.OffsetInBits
= Frag
->OffsetInBits
;
1853 return VariableSlice
;
1855 template <typename T
>
1856 bool calculateFragmentIntersectImpl(
1857 const DataLayout
&DL
, const Value
*Dest
, uint64_t SliceOffsetInBits
,
1858 uint64_t SliceSizeInBits
, const T
*AssignRecord
,
1859 std::optional
<DIExpression::FragmentInfo
> &Result
) {
1860 // There are multiple offsets at play in this function, so let's break it
1861 // down. Starting with how variables may be stored in allocas:
1863 // 1 Simplest case: variable is alloca sized and starts at offset 0.
1864 // 2 Variable is larger than the alloca: the alloca holds just a part of it.
1865 // 3 Variable is smaller than the alloca: the alloca may hold multiple
1868 // Imagine we have a store to the entire alloca. In case (3) the store
1869 // affects bits outside of the bounds of each variable. In case (2), where
1870 // the alloca holds the Xth bit to the Yth bit of a variable, the
1871 // zero-offset store doesn't represent an assignment at offset zero to the
1872 // variable. It is an assignment to offset X.
1875 // Obviously, not all stores are alloca-sized and have zero offset. Imagine
1876 // the lower 32 bits of this store are dead and are going to be DSEd:
1878 // store i64 %v, ptr %dest, !DIAssignID !1
1879 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1880 // !DIExpression(DW_OP_plus_uconst, 4))
1882 // Goal: Given our dead bits at offset:0 size:32 for the store, determine the
1883 // part of the variable, which fits in the fragment expressed by the
1884 // dbg.assign, that has been killed, if any.
1886 // calculateFragmentIntersect(..., SliceOffsetInBits=0,
1887 // SliceSizeInBits=32, Dest=%dest, Assign=dbg.assign)
1889 // Drawing the store (s) in memory followed by the shortened version ($),
1890 // then the dbg.assign (d), with the fragment information on a seperate scale
1898 // s[######] - Original stores 64 bits to Dest.
1899 // $----[##] - DSE says the lower 32 bits are dead, to be removed.
1900 // d [##] - Assign's address-modifying expression adds 4 bytes to
1906 // The answer is achieved in a few steps:
1907 // 1. Add the fragment offset to the store offset:
1908 // SliceOffsetInBits:0 + VarFrag.OffsetInBits:128 = 128
1910 // 2. Subtract the address-modifying expression offset plus difference
1911 // between d.address and dest:
1912 // 128 - (expression_offset:32 + (d.address - dest):0) = 96
1914 // 3. That offset along with the store size (32) represents the bits of the
1915 // variable that'd be affected by the store. Call it SliceOfVariable.
1916 // Intersect that with Assign's fragment info:
1917 // SliceOfVariable ∩ Assign_fragment = none
1919 // In this case: none of the dead bits of the store affect Assign.
1922 // Similar example with the same goal. This time the upper 16 bits
1923 // of the store are going to be DSE'd.
1925 // store i64 %v, ptr %dest, !DIAssignID !1
1926 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1927 // !DIExpression(DW_OP_plus_uconst, 4))
1929 // calculateFragmentIntersect(..., SliceOffsetInBits=48,
1930 // SliceSizeInBits=16, Dest=%dest, Assign=dbg.assign)
1937 // s[######] - Original stores 64 bits to Dest.
1938 // $[####]-- - DSE says the upper 16 bits are dead, to be removed.
1939 // d [##] - Assign's address-modifying expression adds 4 bytes to
1945 // Using the same steps in the first example:
1946 // 1. SliceOffsetInBits:48 + VarFrag.OffsetInBits:128 = 176
1947 // 2. 176 - (expression_offset:32 + (d.address - dest):0) = 144
1948 // 3. SliceOfVariable offset = 144, size = 16:
1949 // SliceOfVariable ∩ Assign_fragment = (offset: 144, size: 16)
1950 // SliceOfVariable tells us the bits of the variable described by Assign that
1951 // are affected by the DSE.
1952 if (AssignRecord
->isKillAddress())
1955 DIExpression::FragmentInfo VarFrag
=
1956 getFragmentOrEntireVariable(AssignRecord
);
1957 if (VarFrag
.SizeInBits
== 0)
1958 return false; // Variable size is unknown.
1960 // Calculate the difference between Dest and the dbg.assign address +
1961 // address-modifying expression.
1962 int64_t PointerOffsetInBits
;
1964 auto DestOffsetInBytes
=
1965 AssignRecord
->getAddress()->getPointerOffsetFrom(Dest
, DL
);
1966 if (!DestOffsetInBytes
)
1967 return false; // Can't calculate difference in addresses.
1969 int64_t ExprOffsetInBytes
;
1970 if (!AssignRecord
->getAddressExpression()->extractIfOffset(
1974 int64_t PointerOffsetInBytes
= *DestOffsetInBytes
+ ExprOffsetInBytes
;
1975 PointerOffsetInBits
= PointerOffsetInBytes
* 8;
1978 // Adjust the slice offset so that we go from describing the a slice
1979 // of memory to a slice of the variable.
1980 int64_t NewOffsetInBits
=
1981 SliceOffsetInBits
+ VarFrag
.OffsetInBits
- PointerOffsetInBits
;
1982 if (NewOffsetInBits
< 0)
1983 return false; // Fragment offsets can only be positive.
1984 DIExpression::FragmentInfo
SliceOfVariable(SliceSizeInBits
, NewOffsetInBits
);
1985 // Intersect the variable slice with AssignRecord's fragment to trim it down
1987 DIExpression::FragmentInfo TrimmedSliceOfVariable
=
1988 DIExpression::FragmentInfo::intersect(SliceOfVariable
, VarFrag
);
1989 if (TrimmedSliceOfVariable
== VarFrag
)
1990 Result
= std::nullopt
;
1992 Result
= TrimmedSliceOfVariable
;
1995 bool at::calculateFragmentIntersect(
1996 const DataLayout
&DL
, const Value
*Dest
, uint64_t SliceOffsetInBits
,
1997 uint64_t SliceSizeInBits
, const DbgAssignIntrinsic
*DbgAssign
,
1998 std::optional
<DIExpression::FragmentInfo
> &Result
) {
1999 return calculateFragmentIntersectImpl(DL
, Dest
, SliceOffsetInBits
,
2000 SliceSizeInBits
, DbgAssign
, Result
);
2002 bool at::calculateFragmentIntersect(
2003 const DataLayout
&DL
, const Value
*Dest
, uint64_t SliceOffsetInBits
,
2004 uint64_t SliceSizeInBits
, const DPValue
*DPVAssign
,
2005 std::optional
<DIExpression::FragmentInfo
> &Result
) {
2006 return calculateFragmentIntersectImpl(DL
, Dest
, SliceOffsetInBits
,
2007 SliceSizeInBits
, DPVAssign
, Result
);
2010 /// Collect constant properies (base, size, offset) of \p StoreDest.
2011 /// Return std::nullopt if any properties are not constants or the
2012 /// offset from the base pointer is negative.
2013 static std::optional
<AssignmentInfo
>
2014 getAssignmentInfoImpl(const DataLayout
&DL
, const Value
*StoreDest
,
2015 TypeSize SizeInBits
) {
2016 if (SizeInBits
.isScalable())
2017 return std::nullopt
;
2018 APInt
GEPOffset(DL
.getIndexTypeSizeInBits(StoreDest
->getType()), 0);
2019 const Value
*Base
= StoreDest
->stripAndAccumulateConstantOffsets(
2020 DL
, GEPOffset
, /*AllowNonInbounds*/ true);
2022 if (GEPOffset
.isNegative())
2023 return std::nullopt
;
2025 uint64_t OffsetInBytes
= GEPOffset
.getLimitedValue();
2026 // Check for overflow.
2027 if (OffsetInBytes
== UINT64_MAX
)
2028 return std::nullopt
;
2029 if (const auto *Alloca
= dyn_cast
<AllocaInst
>(Base
))
2030 return AssignmentInfo(DL
, Alloca
, OffsetInBytes
* 8, SizeInBits
);
2031 return std::nullopt
;
2034 std::optional
<AssignmentInfo
> at::getAssignmentInfo(const DataLayout
&DL
,
2035 const MemIntrinsic
*I
) {
2036 const Value
*StoreDest
= I
->getRawDest();
2037 // Assume 8 bit bytes.
2038 auto *ConstLengthInBytes
= dyn_cast
<ConstantInt
>(I
->getLength());
2039 if (!ConstLengthInBytes
)
2040 // We can't use a non-const size, bail.
2041 return std::nullopt
;
2042 uint64_t SizeInBits
= 8 * ConstLengthInBytes
->getZExtValue();
2043 return getAssignmentInfoImpl(DL
, StoreDest
, TypeSize::getFixed(SizeInBits
));
2046 std::optional
<AssignmentInfo
> at::getAssignmentInfo(const DataLayout
&DL
,
2047 const StoreInst
*SI
) {
2048 TypeSize SizeInBits
= DL
.getTypeSizeInBits(SI
->getValueOperand()->getType());
2049 return getAssignmentInfoImpl(DL
, SI
->getPointerOperand(), SizeInBits
);
2052 std::optional
<AssignmentInfo
> at::getAssignmentInfo(const DataLayout
&DL
,
2053 const AllocaInst
*AI
) {
2054 TypeSize SizeInBits
= DL
.getTypeSizeInBits(AI
->getAllocatedType());
2055 return getAssignmentInfoImpl(DL
, AI
, SizeInBits
);
2058 /// Returns nullptr if the assignment shouldn't be attributed to this variable.
2059 static CallInst
*emitDbgAssign(AssignmentInfo Info
, Value
*Val
, Value
*Dest
,
2060 Instruction
&StoreLikeInst
,
2061 const VarRecord
&VarRec
, DIBuilder
&DIB
) {
2062 auto *ID
= StoreLikeInst
.getMetadata(LLVMContext::MD_DIAssignID
);
2063 assert(ID
&& "Store instruction must have DIAssignID metadata");
2066 const uint64_t StoreStartBit
= Info
.OffsetInBits
;
2067 const uint64_t StoreEndBit
= Info
.OffsetInBits
+ Info
.SizeInBits
;
2069 uint64_t FragStartBit
= StoreStartBit
;
2070 uint64_t FragEndBit
= StoreEndBit
;
2072 bool StoreToWholeVariable
= Info
.StoreToWholeAlloca
;
2073 if (auto Size
= VarRec
.Var
->getSizeInBits()) {
2074 // NOTE: trackAssignments doesn't understand base expressions yet, so all
2075 // variables that reach here are guaranteed to start at offset 0 in the
2077 const uint64_t VarStartBit
= 0;
2078 const uint64_t VarEndBit
= *Size
;
2080 // FIXME: trim FragStartBit when nonzero VarStartBit is supported.
2081 FragEndBit
= std::min(FragEndBit
, VarEndBit
);
2083 // Discard stores to bits outside this variable.
2084 if (FragStartBit
>= FragEndBit
)
2087 StoreToWholeVariable
= FragStartBit
<= VarStartBit
&& FragEndBit
>= *Size
;
2090 DIExpression
*Expr
=
2091 DIExpression::get(StoreLikeInst
.getContext(), std::nullopt
);
2092 if (!StoreToWholeVariable
) {
2093 auto R
= DIExpression::createFragmentExpression(Expr
, FragStartBit
,
2094 FragEndBit
- FragStartBit
);
2095 assert(R
.has_value() && "failed to create fragment expression");
2098 DIExpression
*AddrExpr
=
2099 DIExpression::get(StoreLikeInst
.getContext(), std::nullopt
);
2100 return DIB
.insertDbgAssign(&StoreLikeInst
, Val
, VarRec
.Var
, Expr
, Dest
,
2101 AddrExpr
, VarRec
.DL
);
2104 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
2105 #define DEBUG_TYPE "assignment-tracking"
2107 void at::trackAssignments(Function::iterator Start
, Function::iterator End
,
2108 const StorageToVarsMap
&Vars
, const DataLayout
&DL
,
2110 // Early-exit if there are no interesting variables.
2114 auto &Ctx
= Start
->getContext();
2115 auto &Module
= *Start
->getModule();
2117 // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
2118 auto *Undef
= UndefValue::get(Type::getInt1Ty(Ctx
));
2119 DIBuilder
DIB(Module
, /*AllowUnresolved*/ false);
2121 // Scan the instructions looking for stores to local variables' storage.
2122 LLVM_DEBUG(errs() << "# Scanning instructions\n");
2123 for (auto BBI
= Start
; BBI
!= End
; ++BBI
) {
2124 for (Instruction
&I
: *BBI
) {
2126 std::optional
<AssignmentInfo
> Info
;
2127 Value
*ValueComponent
= nullptr;
2128 Value
*DestComponent
= nullptr;
2129 if (auto *AI
= dyn_cast
<AllocaInst
>(&I
)) {
2130 // We want to track the variable's stack home from its alloca's
2131 // position onwards so we treat it as an assignment (where the stored
2133 Info
= getAssignmentInfo(DL
, AI
);
2134 ValueComponent
= Undef
;
2136 } else if (auto *SI
= dyn_cast
<StoreInst
>(&I
)) {
2137 Info
= getAssignmentInfo(DL
, SI
);
2138 ValueComponent
= SI
->getValueOperand();
2139 DestComponent
= SI
->getPointerOperand();
2140 } else if (auto *MI
= dyn_cast
<MemTransferInst
>(&I
)) {
2141 Info
= getAssignmentInfo(DL
, MI
);
2142 // May not be able to represent this value easily.
2143 ValueComponent
= Undef
;
2144 DestComponent
= MI
->getOperand(0);
2145 } else if (auto *MI
= dyn_cast
<MemSetInst
>(&I
)) {
2146 Info
= getAssignmentInfo(DL
, MI
);
2147 // If we're zero-initing we can state the assigned value is zero,
2148 // otherwise use undef.
2149 auto *ConstValue
= dyn_cast
<ConstantInt
>(MI
->getOperand(1));
2150 if (ConstValue
&& ConstValue
->isZero())
2151 ValueComponent
= ConstValue
;
2153 ValueComponent
= Undef
;
2154 DestComponent
= MI
->getOperand(0);
2156 // Not a store-like instruction.
2160 assert(ValueComponent
&& DestComponent
);
2161 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I
<< "\n");
2163 // Check if getAssignmentInfo failed to understand this store.
2164 if (!Info
.has_value()) {
2167 << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
2170 LLVM_DEBUG(errs() << " | BASE: " << *Info
->Base
<< "\n");
2172 // Check if the store destination is a local variable with debug info.
2173 auto LocalIt
= Vars
.find(Info
->Base
);
2174 if (LocalIt
== Vars
.end()) {
2177 << " | SKIP: Base address not associated with local variable\n");
2182 cast_or_null
<DIAssignID
>(I
.getMetadata(LLVMContext::MD_DIAssignID
));
2184 ID
= DIAssignID::getDistinct(Ctx
);
2185 I
.setMetadata(LLVMContext::MD_DIAssignID
, ID
);
2188 for (const VarRecord
&R
: LocalIt
->second
) {
2190 emitDbgAssign(*Info
, ValueComponent
, DestComponent
, I
, R
, DIB
);
2192 LLVM_DEBUG(if (Assign
) errs() << " > INSERT: " << *Assign
<< "\n");
2198 bool AssignmentTrackingPass::runOnFunction(Function
&F
) {
2199 // No value in assignment tracking without optimisations.
2200 if (F
.hasFnAttribute(Attribute::OptimizeNone
))
2201 return /*Changed*/ false;
2203 // FIXME: https://github.com/llvm/llvm-project/issues/76545
2204 if (F
.hasFnAttribute(Attribute::SanitizeHWAddress
))
2205 return /*Changed*/ false;
2207 bool Changed
= false;
2208 auto *DL
= &F
.getParent()->getDataLayout();
2209 // Collect a map of {backing storage : dbg.declares} (currently "backing
2210 // storage" is limited to Allocas). We'll use this to find dbg.declares to
2211 // delete after running `trackAssignments`.
2212 DenseMap
<const AllocaInst
*, SmallPtrSet
<DbgDeclareInst
*, 2>> DbgDeclares
;
2213 // Create another similar map of {storage : variables} that we'll pass to
2214 // trackAssignments.
2215 StorageToVarsMap Vars
;
2216 for (auto &BB
: F
) {
2217 for (auto &I
: BB
) {
2218 DbgDeclareInst
*DDI
= dyn_cast
<DbgDeclareInst
>(&I
);
2221 // FIXME: trackAssignments doesn't let you specify any modifiers to the
2222 // variable (e.g. fragment) or location (e.g. offset), so we have to
2223 // leave dbg.declares with non-empty expressions in place.
2224 if (DDI
->getExpression()->getNumElements() != 0)
2226 if (!DDI
->getAddress())
2228 if (AllocaInst
*Alloca
=
2229 dyn_cast
<AllocaInst
>(DDI
->getAddress()->stripPointerCasts())) {
2230 // FIXME: Skip VLAs for now (let these variables use dbg.declares).
2231 if (!Alloca
->isStaticAlloca())
2233 // Similarly, skip scalable vectors (use dbg.declares instead).
2234 if (auto Sz
= Alloca
->getAllocationSize(*DL
); Sz
&& Sz
->isScalable())
2236 DbgDeclares
[Alloca
].insert(DDI
);
2237 Vars
[Alloca
].insert(VarRecord(DDI
));
2242 // FIXME: Locals can be backed by caller allocas (sret, byval).
2243 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
2244 // doesn't "understand" dbg.declares). However, this doesn't appear to break
2245 // any rules given this description of dbg.declare from
2246 // llvm/docs/SourceLevelDebugging.rst:
2248 // It is not control-dependent, meaning that if a call to llvm.dbg.declare
2249 // exists and has a valid location argument, that address is considered to
2250 // be the true home of the variable across its entire lifetime.
2251 trackAssignments(F
.begin(), F
.end(), Vars
, *DL
);
2253 // Delete dbg.declares for variables now tracked with assignment tracking.
2254 for (auto &P
: DbgDeclares
) {
2255 const AllocaInst
*Alloca
= P
.first
;
2256 auto Markers
= at::getAssignmentMarkers(Alloca
);
2257 SmallVector
<DPValue
*> DPMarkers
= at::getDPVAssignmentMarkers(Alloca
);
2260 for (DbgDeclareInst
*DDI
: P
.second
) {
2261 // Assert that the alloca that DDI uses is now linked to a dbg.assign
2262 // describing the same variable (i.e. check that this dbg.declare has
2263 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard
2264 // the fragment part because trackAssignments may alter the
2265 // fragment. e.g. if the alloca is smaller than the variable, then
2266 // trackAssignments will create an alloca-sized fragment for the
2268 assert(llvm::any_of(Markers
,
2269 [DDI
](DbgAssignIntrinsic
*DAI
) {
2270 return DebugVariableAggregate(DAI
) ==
2271 DebugVariableAggregate(DDI
);
2273 llvm::any_of(DPMarkers
, [DDI
](DPValue
*DPV
) {
2274 return DebugVariableAggregate(DPV
) ==
2275 DebugVariableAggregate(DDI
);
2277 // Delete DDI because the variable location is now tracked using
2278 // assignment tracking.
2279 DDI
->eraseFromParent();
2286 static const char *AssignmentTrackingModuleFlag
=
2287 "debug-info-assignment-tracking";
2289 static void setAssignmentTrackingModuleFlag(Module
&M
) {
2290 M
.setModuleFlag(Module::ModFlagBehavior::Max
, AssignmentTrackingModuleFlag
,
2291 ConstantAsMetadata::get(
2292 ConstantInt::get(Type::getInt1Ty(M
.getContext()), 1)));
2295 static bool getAssignmentTrackingModuleFlag(const Module
&M
) {
2296 Metadata
*Value
= M
.getModuleFlag(AssignmentTrackingModuleFlag
);
2297 return Value
&& !cast
<ConstantAsMetadata
>(Value
)->getValue()->isZeroValue();
2300 bool llvm::isAssignmentTrackingEnabled(const Module
&M
) {
2301 return getAssignmentTrackingModuleFlag(M
);
2304 PreservedAnalyses
AssignmentTrackingPass::run(Function
&F
,
2305 FunctionAnalysisManager
&AM
) {
2306 if (!runOnFunction(F
))
2307 return PreservedAnalyses::all();
2309 // Record that this module uses assignment tracking. It doesn't matter that
2310 // some functons in the module may not use it - the debug info in those
2311 // functions will still be handled properly.
2312 setAssignmentTrackingModuleFlag(*F
.getParent());
2314 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2315 // return PreservedAnalyses::all()?
2316 PreservedAnalyses PA
;
2317 PA
.preserveSet
<CFGAnalyses
>();
2321 PreservedAnalyses
AssignmentTrackingPass::run(Module
&M
,
2322 ModuleAnalysisManager
&AM
) {
2323 bool Changed
= false;
2325 Changed
|= runOnFunction(F
);
2328 return PreservedAnalyses::all();
2330 // Record that this module uses assignment tracking.
2331 setAssignmentTrackingModuleFlag(M
);
2333 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2334 // return PreservedAnalyses::all()?
2335 PreservedAnalyses PA
;
2336 PA
.preserveSet
<CFGAnalyses
>();