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