1//===- DynamicDebugging.cpp - Dynamic Debugging utils --------------------===//
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#include "llvm/Transforms/Utils/DynamicDebugging.h"
10#include "llvm/IR/Module.h"
11#include "llvm/Transforms/Utils/Cloning.h"
12#include "llvm/Transforms/Utils/ModuleUtils.h"
13#include "llvm/Transforms/Utils/ValueMapper.h"
14
15using namespace llvm;
16
17std::unique_ptr<Module>
18llvm::prepareForDynamicDebugging(Module *M, StringRef PromotionSuffix) {
19 using namespace llvm;
20 assert(M->getNamedMetadata("llvm.dbg.cu") &&
21 "Expected module with debug info");
22
23 auto ShouldPromoteGlobal = [](const GlobalValue &GV) {
24 if (!GV.hasLocalLinkage())
25 return false;
26
27 // Local symbols in a comdat shouldn't be promoted either.
28 // This can happen with (at least) __cxx_global_var_init (which is local
29 // and may initialize an ODR-weak global variable).
30 if (GV.hasComdat())
31 return false;
32
33 return true;
34 };
35
36 // Clone functions definitions only - CloneModule will clone data definitions
37 // as declarations. We rename these and explicitly set their linkage later.
38 auto ShouldCloneDefinition = [](const GlobalValue *GV) {
39 return isa<Function>(Val: GV);
40 };
41 ValueToValueMapTy VMap;
42 std::unique_ptr<Module> UnoptM = CloneModule(M: *M, VMap, ShouldCloneDefinition);
43
44 // Insert declarations into Inner that point to Outer, apply attributes to
45 // Outer functions.
46 for (Function &OuterDef : M->functions()) {
47 if (OuterDef.isDeclaration())
48 continue;
49
50 // Find the Inner version of Outer's function.
51 Function *InnerDef = cast<Function>(Val&: VMap[&OuterDef]);
52
53 // Apply some attributes to both Inner and Outer defs.
54 {
55 // Unoptimized module wants no inlining at all.
56 InnerDef->addFnAttr(Kind: Attribute::NoInline);
57 InnerDef->removeFnAttr(Kind: Attribute::AlwaysInline);
58
59 // Apply optnone, remove clashing attributes.
60 InnerDef->addFnAttr(Kind: Attribute::OptimizeNone);
61 InnerDef->removeFnAttr(Kind: Attribute::OptimizeForSize);
62 InnerDef->removeFnAttr(Kind: Attribute::MinSize);
63
64 // Add attributes to the outer-object functions to ensure they're
65 // always patchable.
66 //
67 // The debugger patches outer (optimized) functions to redirect to inner
68 // (unoptimized) functions. Block interprocedural analysis to ensure
69 // the two function implementations share the same interface.
70 OuterDef.addFnAttr(Kind: Attribute::NoIPA);
71 // Outlining creates specialized functions in the outer (optimized)
72 // module without an inner (unoptimized) equivalent, meaning the debugger
73 // can't switch to an unoptimized version, so block outlining.
74 OuterDef.addFnAttr(Kind: Attribute::NoOutline);
75 // TODO: Add patch bytes size/value for other targets.
76 if (M->getTargetTriple().isX86_64()) {
77 OuterDef.addFnAttr(Kind: "tail-pad-to-size", Val: "5");
78 OuterDef.addFnAttr(Kind: "tail-pad-value", Val: "144"); // 0x90
79 }
80 }
81
82 // Apply COMDAT grouping to the clone if OuterDef is in one.
83 if (OuterDef.hasComdat()) {
84 std::string NewComdat =
85 Twine("__dyndbg." + OuterDef.getComdat()->getName()).str();
86 Comdat *C = M->getOrInsertComdat(Name: NewComdat);
87 C->setSelectionKind(OuterDef.getComdat()->getSelectionKind());
88 InnerDef->setComdat(C);
89 }
90
91 // Rename Inner's copy and set appropriate linkage depending on whether
92 // it'll get promoted in Outer or not.
93 if (ShouldPromoteGlobal(OuterDef)) {
94 InnerDef->setName("__dyndbg." + InnerDef->getName() + PromotionSuffix);
95 InnerDef->setLinkage(GlobalValue::ExternalLinkage);
96 InnerDef->setVisibility(GlobalValue::HiddenVisibility);
97 } else {
98 InnerDef->setName("__dyndbg." + InnerDef->getName());
99 InnerDef->setLinkage(OuterDef.getLinkage());
100 InnerDef->setVisibility(OuterDef.getVisibility());
101 }
102
103 // Create Inner's external reference to Outer's version.
104 Function *InnerDeclOfOuterDef = Function::Create(
105 Ty: cast<FunctionType>(Val: OuterDef.getValueType()), Linkage: OuterDef.getLinkage(),
106 AddrSpace: OuterDef.getAddressSpace(), N: OuterDef.getName(), M: UnoptM.get());
107 InnerDeclOfOuterDef->copyAttributesFrom(Src: &OuterDef);
108 // Re-set linkage and visibility after copyAttributesFrom.
109 InnerDeclOfOuterDef->setLinkage(GlobalValue::ExternalLinkage);
110 InnerDeclOfOuterDef->setPersonalityFn(nullptr);
111
112 // Replace Inner uses of function with that external reference.
113 InnerDef->replaceAllUsesWith(V: InnerDeclOfOuterDef);
114
115 VMap[&OuterDef] = InnerDeclOfOuterDef;
116 }
117
118 // Add Outer aliases for globals with internal linkage, adding
119 // ".dyndbg.<TU-unique-hash>" suffix. Update Inner's external references to
120 // these promoted functions to use their new names.
121 SmallVector<GlobalValue *> GlobalsToPreserve;
122 for (GlobalValue &GV : M->global_values()) {
123 // If the global is used but may be discarded after optimizations
124 // (e.g. inlining) then ensure it's marked as compiler-used to prevent
125 // that. It may be referenced from the inner module.
126 if (GV.isDiscardableIfUnused()) {
127 if (GV.getNumUses()) {
128 GlobalsToPreserve.push_back(Elt: &GV);
129 // Name unnamed globals. Compiler-used expects named globals only.
130 if (GV.getName().empty())
131 GV.setName("__unnamed");
132 } else {
133 // No uses, so the inner module doesn't need a reference nor do we need
134 // to produce an alias.
135 // Remove the inner module reference.
136 auto GVAndUnoptPair = VMap.find(Val: &GV);
137 assert(GVAndUnoptPair != VMap.end() && "Unmapped global?");
138 // Delete the external reference - VMap should only contain mappings to
139 // those declarations now.
140 assert(cast<GlobalValue>(GVAndUnoptPair->second)->isDeclaration() &&
141 "expected only declarations in VMap now");
142 cast<GlobalValue>(Val&: GVAndUnoptPair->second)->eraseFromParent();
143 GVAndUnoptPair->second = nullptr;
144 // Nothing else to do for this global.
145 continue;
146 }
147 }
148
149 if (!ShouldPromoteGlobal(GV))
150 continue;
151
152 // We need external aliases with a mangled name and hidden visibility.
153 auto *Alias = GlobalAlias::create(Linkage: GlobalValue::ExternalLinkage,
154 Name: GV.getName() + PromotionSuffix, Aliasee: &GV);
155 Alias->setVisibility(GlobalValue::HiddenVisibility);
156
157 // Update the Inner external reference that corresponds to the promoted
158 // Outer global (created just now as an alias in opt) to reference the new
159 // alias.
160 GlobalValue *UnoptGV = cast<GlobalValue>(Val&: VMap[&GV]);
161 UnoptGV->setName(Alias->getName());
162 UnoptGV->setVisibility(GlobalValue::HiddenVisibility);
163 assert(UnoptGV->getLinkage() == GlobalValue::ExternalLinkage &&
164 "Expected ExternalLinkage from CloneModule or inserted decl");
165 }
166
167 // Preserve functions that may be discarded after optimizing away call sites
168 // (e.g. ODR-weak). Another desirable effect of this is that it prevents
169 // GlobalOpt promoting the alias. If the function-preservation mechanism
170 // changes in the future GlobalOpt alias promotion must be handled another
171 // way.
172 appendToCompilerUsed(M&: *M, Values: GlobalsToPreserve);
173
174 return UnoptM;
175}