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