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