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