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