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