1 //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass lowers instrprof_increment intrinsics emitted by a frontend for
11 // profiling. It also builds the data structures and initialization code needed
12 // for updating execution counts and emitting the profile at runtime.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Instrumentation.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Transforms/Utils/ModuleUtils.h"
26 #define DEBUG_TYPE "instrprof"
30 class InstrProfiling : public ModulePass {
34 InstrProfiling() : ModulePass(ID) {}
36 InstrProfiling(const InstrProfOptions &Options)
37 : ModulePass(ID), Options(Options) {}
39 const char *getPassName() const override {
40 return "Frontend instrumentation-based coverage lowering";
43 bool runOnModule(Module &M) override;
45 void getAnalysisUsage(AnalysisUsage &AU) const override {
50 InstrProfOptions Options;
52 DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
53 std::vector<Value *> UsedVars;
55 bool isMachO() const {
56 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
59 /// Get the section name for the counter variables.
60 StringRef getCountersSection() const {
61 return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
64 /// Get the section name for the name variables.
65 StringRef getNameSection() const {
66 return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
69 /// Get the section name for the profile data variables.
70 StringRef getDataSection() const {
71 return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
74 /// Replace instrprof_increment with an increment of the appropriate value.
75 void lowerIncrement(InstrProfIncrementInst *Inc);
77 /// Get the region counters for an increment, creating them if necessary.
79 /// If the counter array doesn't yet exist, the profile data variables
80 /// referring to them will also be created.
81 GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
83 /// Emit runtime registration functions for each profile data variable.
84 void emitRegistration();
86 /// Emit the necessary plumbing to pull in the runtime initialization.
87 void emitRuntimeHook();
89 /// Add uses of our data variables and runtime hook.
92 /// Create a static initializer for our data, on platforms that need it.
93 void emitInitialization();
96 } // anonymous namespace
98 char InstrProfiling::ID = 0;
99 INITIALIZE_PASS(InstrProfiling, "instrprof",
100 "Frontend instrumentation-based coverage lowering.", false,
103 ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
104 return new InstrProfiling(Options);
107 bool InstrProfiling::runOnModule(Module &M) {
108 bool MadeChange = false;
111 RegionCounters.clear();
114 for (Function &F : M)
115 for (BasicBlock &BB : F)
116 for (auto I = BB.begin(), E = BB.end(); I != E;)
117 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
127 emitInitialization();
131 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
132 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
134 IRBuilder<> Builder(Inc->getParent(), *Inc);
135 uint64_t Index = Inc->getIndex()->getZExtValue();
136 llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
137 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
138 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
139 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
140 Inc->eraseFromParent();
143 /// Get the name of a profiling variable for a particular function.
144 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) {
145 auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
146 StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
147 return ("__llvm_profile_" + VarName + "_" + Name).str();
151 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
152 GlobalVariable *Name = Inc->getName();
153 auto It = RegionCounters.find(Name);
154 if (It != RegionCounters.end())
157 // Move the name variable to the right section.
158 Name->setSection(getNameSection());
159 Name->setAlignment(1);
161 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
162 LLVMContext &Ctx = M->getContext();
163 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
165 // Create the counters variable.
166 auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
167 Constant::getNullValue(CounterTy),
168 getVarName(Inc, "counters"));
169 Counters->setVisibility(Name->getVisibility());
170 Counters->setSection(getCountersSection());
171 Counters->setAlignment(8);
173 RegionCounters[Inc->getName()] = Counters;
175 // Create data variable.
176 auto *NameArrayTy = Name->getType()->getPointerElementType();
177 auto *Int32Ty = Type::getInt32Ty(Ctx);
178 auto *Int64Ty = Type::getInt64Ty(Ctx);
179 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
180 auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
182 Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
183 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
184 Constant *DataVals[] = {
185 ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
186 ConstantInt::get(Int32Ty, NumCounters),
187 ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
188 ConstantExpr::getBitCast(Name, Int8PtrTy),
189 ConstantExpr::getBitCast(Counters, Int64PtrTy)};
190 auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
191 ConstantStruct::get(DataTy, DataVals),
192 getVarName(Inc, "data"));
193 Data->setVisibility(Name->getVisibility());
194 Data->setSection(getDataSection());
195 Data->setAlignment(8);
197 // Mark the data variable as used so that it isn't stripped out.
198 UsedVars.push_back(Data);
203 void InstrProfiling::emitRegistration() {
204 // Don't do this for Darwin. compiler-rt uses linker magic.
205 if (Triple(M->getTargetTriple()).isOSDarwin())
208 // Construct the function.
209 auto *VoidTy = Type::getVoidTy(M->getContext());
210 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
211 auto *RegisterFTy = FunctionType::get(VoidTy, false);
212 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
213 "__llvm_profile_register_functions", M);
214 RegisterF->setUnnamedAddr(true);
215 if (Options.NoRedZone)
216 RegisterF->addFnAttr(Attribute::NoRedZone);
218 auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
219 auto *RuntimeRegisterF =
220 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
221 "__llvm_profile_register_function", M);
223 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
224 for (Value *Data : UsedVars)
225 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
229 void InstrProfiling::emitRuntimeHook() {
230 const char *const RuntimeVarName = "__llvm_profile_runtime";
231 const char *const RuntimeUserName = "__llvm_profile_runtime_user";
233 // If the module's provided its own runtime, we don't need to do anything.
234 if (M->getGlobalVariable(RuntimeVarName))
237 // Declare an external variable that will pull in the runtime initialization.
238 auto *Int32Ty = Type::getInt32Ty(M->getContext());
240 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
241 nullptr, RuntimeVarName);
243 // Make a function that uses it.
245 Function::Create(FunctionType::get(Int32Ty, false),
246 GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M);
247 User->addFnAttr(Attribute::NoInline);
248 if (Options.NoRedZone)
249 User->addFnAttr(Attribute::NoRedZone);
251 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
252 auto *Load = IRB.CreateLoad(Var);
255 // Mark the user variable as used so that it isn't stripped out.
256 UsedVars.push_back(User);
259 void InstrProfiling::emitUses() {
260 if (UsedVars.empty())
263 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
264 std::vector<Constant*> MergedVars;
266 // Collect the existing members of llvm.used.
267 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
268 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
269 MergedVars.push_back(Inits->getOperand(I));
270 LLVMUsed->eraseFromParent();
273 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
274 // Add uses for our data.
275 for (auto *Value : UsedVars)
276 MergedVars.push_back(
277 ConstantExpr::getBitCast(cast<llvm::Constant>(Value), i8PTy));
279 // Recreate llvm.used.
280 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
281 LLVMUsed = new llvm::GlobalVariable(
282 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
283 llvm::ConstantArray::get(ATy, MergedVars), "llvm.used");
285 LLVMUsed->setSection("llvm.metadata");
288 void InstrProfiling::emitInitialization() {
289 Constant *RegisterF = M->getFunction("__llvm_profile_register_functions");
293 // Create the initialization function.
294 auto *VoidTy = Type::getVoidTy(M->getContext());
296 Function::Create(FunctionType::get(VoidTy, false),
297 GlobalValue::InternalLinkage, "__llvm_profile_init", M);
298 F->setUnnamedAddr(true);
299 F->addFnAttr(Attribute::NoInline);
300 if (Options.NoRedZone)
301 F->addFnAttr(Attribute::NoRedZone);
303 // Add the basic block and the necessary calls.
304 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
305 IRB.CreateCall(RegisterF);
308 appendToGlobalCtors(*M, F, 0);