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