1 //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass lowers instrprof_* intrinsics emitted by a frontend for profiling. 11 // It also builds the data structures and initialization code needed for 12 // updating execution counts and emitting the profile at runtime. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Transforms/InstrProfiling.h" 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/IR/IRBuilder.h" 19 #include "llvm/IR/IntrinsicInst.h" 20 #include "llvm/IR/Module.h" 21 #include "llvm/ProfileData/InstrProf.h" 22 #include "llvm/Transforms/Utils/ModuleUtils.h" 23 24 using namespace llvm; 25 26 #define DEBUG_TYPE "instrprof" 27 28 namespace { 29 30 cl::opt<bool> DoNameCompression("enable-name-compression", 31 cl::desc("Enable name string compression"), 32 cl::init(true)); 33 34 cl::opt<bool> ValueProfileStaticAlloc( 35 "vp-static-alloc", 36 cl::desc("Do static counter allocation for value profiler"), 37 cl::init(true)); 38 cl::opt<double> NumCountersPerValueSite( 39 "vp-counters-per-site", 40 cl::desc("The average number of profile counters allocated " 41 "per value profiling site."), 42 // This is set to a very small value because in real programs, only 43 // a very small percentage of value sites have non-zero targets, e.g, 1/30. 44 // For those sites with non-zero profile, the average number of targets 45 // is usually smaller than 2. 46 cl::init(1.0)); 47 48 class InstrProfilingLegacyPass : public ModulePass { 49 InstrProfiling InstrProf; 50 51 public: 52 static char ID; 53 InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {} 54 InstrProfilingLegacyPass(const InstrProfOptions &Options) 55 : ModulePass(ID), InstrProf(Options) {} 56 const char *getPassName() const override { 57 return "Frontend instrumentation-based coverage lowering"; 58 } 59 60 bool runOnModule(Module &M) override { return InstrProf.run(M); } 61 62 void getAnalysisUsage(AnalysisUsage &AU) const override { 63 AU.setPreservesCFG(); 64 } 65 }; 66 67 } // anonymous namespace 68 69 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) { 70 if (!run(M)) 71 return PreservedAnalyses::all(); 72 73 return PreservedAnalyses::none(); 74 } 75 76 char InstrProfilingLegacyPass::ID = 0; 77 INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof", 78 "Frontend instrumentation-based coverage lowering.", false, 79 false) 80 81 ModulePass * 82 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) { 83 return new InstrProfilingLegacyPass(Options); 84 } 85 86 bool InstrProfiling::isMachO() const { 87 return Triple(M->getTargetTriple()).isOSBinFormatMachO(); 88 } 89 90 /// Get the section name for the counter variables. 91 StringRef InstrProfiling::getCountersSection() const { 92 return getInstrProfCountersSectionName(isMachO()); 93 } 94 95 /// Get the section name for the name variables. 96 StringRef InstrProfiling::getNameSection() const { 97 return getInstrProfNameSectionName(isMachO()); 98 } 99 100 /// Get the section name for the profile data variables. 101 StringRef InstrProfiling::getDataSection() const { 102 return getInstrProfDataSectionName(isMachO()); 103 } 104 105 /// Get the section name for the coverage mapping data. 106 StringRef InstrProfiling::getCoverageSection() const { 107 return getInstrProfCoverageSectionName(isMachO()); 108 } 109 110 bool InstrProfiling::run(Module &M) { 111 bool MadeChange = false; 112 113 this->M = &M; 114 NamesVar = nullptr; 115 NamesSize = 0; 116 ProfileDataMap.clear(); 117 UsedVars.clear(); 118 119 // We did not know how many value sites there would be inside 120 // the instrumented function. This is counting the number of instrumented 121 // target value sites to enter it as field in the profile data variable. 122 for (Function &F : M) { 123 InstrProfIncrementInst *FirstProfIncInst = nullptr; 124 for (BasicBlock &BB : F) 125 for (auto I = BB.begin(), E = BB.end(); I != E; I++) 126 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I)) 127 computeNumValueSiteCounts(Ind); 128 else if (FirstProfIncInst == nullptr) 129 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I); 130 131 // Value profiling intrinsic lowering requires per-function profile data 132 // variable to be created first. 133 if (FirstProfIncInst != nullptr) 134 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst)); 135 } 136 137 for (Function &F : M) 138 for (BasicBlock &BB : F) 139 for (auto I = BB.begin(), E = BB.end(); I != E;) { 140 auto Instr = I++; 141 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) { 142 lowerIncrement(Inc); 143 MadeChange = true; 144 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) { 145 lowerValueProfileInst(Ind); 146 MadeChange = true; 147 } 148 } 149 150 if (GlobalVariable *CoverageNamesVar = 151 M.getNamedGlobal(getCoverageUnusedNamesVarName())) { 152 lowerCoverageData(CoverageNamesVar); 153 MadeChange = true; 154 } 155 156 if (!MadeChange) 157 return false; 158 159 emitVNodes(); 160 emitNameData(); 161 emitRegistration(); 162 emitRuntimeHook(); 163 emitUses(); 164 emitInitialization(); 165 return true; 166 } 167 168 static Constant *getOrInsertValueProfilingCall(Module &M) { 169 LLVMContext &Ctx = M.getContext(); 170 auto *ReturnTy = Type::getVoidTy(M.getContext()); 171 Type *ParamTypes[] = { 172 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType 173 #include "llvm/ProfileData/InstrProfData.inc" 174 }; 175 auto *ValueProfilingCallTy = 176 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false); 177 return M.getOrInsertFunction(getInstrProfValueProfFuncName(), 178 ValueProfilingCallTy); 179 } 180 181 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) { 182 183 GlobalVariable *Name = Ind->getName(); 184 uint64_t ValueKind = Ind->getValueKind()->getZExtValue(); 185 uint64_t Index = Ind->getIndex()->getZExtValue(); 186 auto It = ProfileDataMap.find(Name); 187 if (It == ProfileDataMap.end()) { 188 PerFunctionProfileData PD; 189 PD.NumValueSites[ValueKind] = Index + 1; 190 ProfileDataMap[Name] = PD; 191 } else if (It->second.NumValueSites[ValueKind] <= Index) 192 It->second.NumValueSites[ValueKind] = Index + 1; 193 } 194 195 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) { 196 197 GlobalVariable *Name = Ind->getName(); 198 auto It = ProfileDataMap.find(Name); 199 assert(It != ProfileDataMap.end() && It->second.DataVar && 200 "value profiling detected in function with no counter incerement"); 201 202 GlobalVariable *DataVar = It->second.DataVar; 203 uint64_t ValueKind = Ind->getValueKind()->getZExtValue(); 204 uint64_t Index = Ind->getIndex()->getZExtValue(); 205 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind) 206 Index += It->second.NumValueSites[Kind]; 207 208 IRBuilder<> Builder(Ind); 209 Value *Args[3] = {Ind->getTargetValue(), 210 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()), 211 Builder.getInt32(Index)}; 212 Ind->replaceAllUsesWith( 213 Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args)); 214 Ind->eraseFromParent(); 215 } 216 217 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) { 218 GlobalVariable *Counters = getOrCreateRegionCounters(Inc); 219 220 IRBuilder<> Builder(Inc); 221 uint64_t Index = Inc->getIndex()->getZExtValue(); 222 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index); 223 Value *Count = Builder.CreateLoad(Addr, "pgocount"); 224 Count = Builder.CreateAdd(Count, Builder.getInt64(1)); 225 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr)); 226 Inc->eraseFromParent(); 227 } 228 229 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) { 230 231 ConstantArray *Names = 232 cast<ConstantArray>(CoverageNamesVar->getInitializer()); 233 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) { 234 Constant *NC = Names->getOperand(I); 235 Value *V = NC->stripPointerCasts(); 236 assert(isa<GlobalVariable>(V) && "Missing reference to function name"); 237 GlobalVariable *Name = cast<GlobalVariable>(V); 238 239 Name->setLinkage(GlobalValue::PrivateLinkage); 240 ReferencedNames.push_back(Name); 241 } 242 } 243 244 /// Get the name of a profiling variable for a particular function. 245 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) { 246 StringRef NamePrefix = getInstrProfNameVarPrefix(); 247 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size()); 248 return (Prefix + Name).str(); 249 } 250 251 static inline bool shouldRecordFunctionAddr(Function *F) { 252 // Check the linkage 253 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() && 254 !F->hasAvailableExternallyLinkage()) 255 return true; 256 // Prohibit function address recording if the function is both internal and 257 // COMDAT. This avoids the profile data variable referencing internal symbols 258 // in COMDAT. 259 if (F->hasLocalLinkage() && F->hasComdat()) 260 return false; 261 // Check uses of this function for other than direct calls or invokes to it. 262 // Inline virtual functions have linkeOnceODR linkage. When a key method 263 // exists, the vtable will only be emitted in the TU where the key method 264 // is defined. In a TU where vtable is not available, the function won't 265 // be 'addresstaken'. If its address is not recorded here, the profile data 266 // with missing address may be picked by the linker leading to missing 267 // indirect call target info. 268 return F->hasAddressTaken() || F->hasLinkOnceLinkage(); 269 } 270 271 static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F, 272 InstrProfIncrementInst *Inc) { 273 if (!needsComdatForCounter(F, M)) 274 return nullptr; 275 276 // COFF format requires a COMDAT section to have a key symbol with the same 277 // name. The linker targeting COFF also requires that the COMDAT 278 // a section is associated to must precede the associating section. For this 279 // reason, we must choose the counter var's name as the name of the comdat. 280 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF() 281 ? getInstrProfCountersVarPrefix() 282 : getInstrProfComdatPrefix()); 283 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix))); 284 } 285 286 static bool needsRuntimeRegistrationOfSectionRange(const Module &M) { 287 // Don't do this for Darwin. compiler-rt uses linker magic. 288 if (Triple(M.getTargetTriple()).isOSDarwin()) 289 return false; 290 291 // Use linker script magic to get data/cnts/name start/end. 292 if (Triple(M.getTargetTriple()).isOSLinux() || 293 Triple(M.getTargetTriple()).isOSFreeBSD() || 294 Triple(M.getTargetTriple()).isPS4CPU()) 295 return false; 296 297 return true; 298 } 299 300 GlobalVariable * 301 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) { 302 GlobalVariable *NamePtr = Inc->getName(); 303 auto It = ProfileDataMap.find(NamePtr); 304 PerFunctionProfileData PD; 305 if (It != ProfileDataMap.end()) { 306 if (It->second.RegionCounters) 307 return It->second.RegionCounters; 308 PD = It->second; 309 } 310 311 // Move the name variable to the right section. Place them in a COMDAT group 312 // if the associated function is a COMDAT. This will make sure that 313 // only one copy of counters of the COMDAT function will be emitted after 314 // linking. 315 Function *Fn = Inc->getParent()->getParent(); 316 Comdat *ProfileVarsComdat = nullptr; 317 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc); 318 319 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue(); 320 LLVMContext &Ctx = M->getContext(); 321 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters); 322 323 // Create the counters variable. 324 auto *CounterPtr = 325 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(), 326 Constant::getNullValue(CounterTy), 327 getVarName(Inc, getInstrProfCountersVarPrefix())); 328 CounterPtr->setVisibility(NamePtr->getVisibility()); 329 CounterPtr->setSection(getCountersSection()); 330 CounterPtr->setAlignment(8); 331 CounterPtr->setComdat(ProfileVarsComdat); 332 333 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx); 334 // Allocate statically the array of pointers to value profile nodes for 335 // the current function. 336 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy); 337 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) { 338 339 uint64_t NS = 0; 340 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 341 NS += PD.NumValueSites[Kind]; 342 if (NS) { 343 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS); 344 345 auto *ValuesVar = 346 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(), 347 Constant::getNullValue(ValuesTy), 348 getVarName(Inc, getInstrProfValuesVarPrefix())); 349 ValuesVar->setVisibility(NamePtr->getVisibility()); 350 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO())); 351 ValuesVar->setAlignment(8); 352 ValuesVar->setComdat(ProfileVarsComdat); 353 ValuesPtrExpr = 354 ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx)); 355 } 356 } 357 358 // Create data variable. 359 auto *Int16Ty = Type::getInt16Ty(Ctx); 360 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1); 361 Type *DataTypes[] = { 362 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType, 363 #include "llvm/ProfileData/InstrProfData.inc" 364 }; 365 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes)); 366 367 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn) 368 ? ConstantExpr::getBitCast(Fn, Int8PtrTy) 369 : ConstantPointerNull::get(Int8PtrTy); 370 371 Constant *Int16ArrayVals[IPVK_Last + 1]; 372 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 373 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]); 374 375 Constant *DataVals[] = { 376 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init, 377 #include "llvm/ProfileData/InstrProfData.inc" 378 }; 379 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(), 380 ConstantStruct::get(DataTy, DataVals), 381 getVarName(Inc, getInstrProfDataVarPrefix())); 382 Data->setVisibility(NamePtr->getVisibility()); 383 Data->setSection(getDataSection()); 384 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT); 385 Data->setComdat(ProfileVarsComdat); 386 387 PD.RegionCounters = CounterPtr; 388 PD.DataVar = Data; 389 ProfileDataMap[NamePtr] = PD; 390 391 // Mark the data variable as used so that it isn't stripped out. 392 UsedVars.push_back(Data); 393 // Now that the linkage set by the FE has been passed to the data and counter 394 // variables, reset Name variable's linkage and visibility to private so that 395 // it can be removed later by the compiler. 396 NamePtr->setLinkage(GlobalValue::PrivateLinkage); 397 // Collect the referenced names to be used by emitNameData. 398 ReferencedNames.push_back(NamePtr); 399 400 return CounterPtr; 401 } 402 403 void InstrProfiling::emitVNodes() { 404 if (!ValueProfileStaticAlloc) 405 return; 406 407 // For now only support this on platforms that do 408 // not require runtime registration to discover 409 // named section start/end. 410 if (needsRuntimeRegistrationOfSectionRange(*M)) 411 return; 412 413 size_t TotalNS = 0; 414 for (auto &PD : ProfileDataMap) { 415 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 416 TotalNS += PD.second.NumValueSites[Kind]; 417 } 418 419 if (!TotalNS) 420 return; 421 422 uint64_t NumCounters = TotalNS * NumCountersPerValueSite; 423 // Heuristic for small programs with very few total value sites. 424 // The default value of vp-counters-per-site is chosen based on 425 // the observation that large apps usually have a low percentage 426 // of value sites that actually have any profile data, and thus 427 // the average number of counters per site is low. For small 428 // apps with very few sites, this may not be true. Bump up the 429 // number of counters in this case. 430 #define INSTR_PROF_MIN_VAL_COUNTS 10 431 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS) 432 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2); 433 434 auto &Ctx = M->getContext(); 435 Type *VNodeTypes[] = { 436 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType, 437 #include "llvm/ProfileData/InstrProfData.inc" 438 }; 439 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes)); 440 441 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters); 442 auto *VNodesVar = new GlobalVariable( 443 *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage, 444 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName()); 445 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO())); 446 UsedVars.push_back(VNodesVar); 447 } 448 449 void InstrProfiling::emitNameData() { 450 std::string UncompressedData; 451 452 if (ReferencedNames.empty()) 453 return; 454 455 std::string CompressedNameStr; 456 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr, 457 DoNameCompression)) { 458 llvm::report_fatal_error(toString(std::move(E)), false); 459 } 460 461 auto &Ctx = M->getContext(); 462 auto *NamesVal = llvm::ConstantDataArray::getString( 463 Ctx, StringRef(CompressedNameStr), false); 464 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true, 465 llvm::GlobalValue::PrivateLinkage, 466 NamesVal, getInstrProfNamesVarName()); 467 NamesSize = CompressedNameStr.size(); 468 NamesVar->setSection(getNameSection()); 469 UsedVars.push_back(NamesVar); 470 } 471 472 void InstrProfiling::emitRegistration() { 473 if (!needsRuntimeRegistrationOfSectionRange(*M)) 474 return; 475 476 // Construct the function. 477 auto *VoidTy = Type::getVoidTy(M->getContext()); 478 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext()); 479 auto *Int64Ty = Type::getInt64Ty(M->getContext()); 480 auto *RegisterFTy = FunctionType::get(VoidTy, false); 481 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage, 482 getInstrProfRegFuncsName(), M); 483 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 484 if (Options.NoRedZone) 485 RegisterF->addFnAttr(Attribute::NoRedZone); 486 487 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false); 488 auto *RuntimeRegisterF = 489 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage, 490 getInstrProfRegFuncName(), M); 491 492 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF)); 493 for (Value *Data : UsedVars) 494 if (Data != NamesVar) 495 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy)); 496 497 if (NamesVar) { 498 Type *ParamTypes[] = {VoidPtrTy, Int64Ty}; 499 auto *NamesRegisterTy = 500 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false); 501 auto *NamesRegisterF = 502 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage, 503 getInstrProfNamesRegFuncName(), M); 504 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy), 505 IRB.getInt64(NamesSize)}); 506 } 507 508 IRB.CreateRetVoid(); 509 } 510 511 void InstrProfiling::emitRuntimeHook() { 512 513 // We expect the linker to be invoked with -u<hook_var> flag for linux, 514 // for which case there is no need to emit the user function. 515 if (Triple(M->getTargetTriple()).isOSLinux()) 516 return; 517 518 // If the module's provided its own runtime, we don't need to do anything. 519 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) 520 return; 521 522 // Declare an external variable that will pull in the runtime initialization. 523 auto *Int32Ty = Type::getInt32Ty(M->getContext()); 524 auto *Var = 525 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage, 526 nullptr, getInstrProfRuntimeHookVarName()); 527 528 // Make a function that uses it. 529 auto *User = Function::Create(FunctionType::get(Int32Ty, false), 530 GlobalValue::LinkOnceODRLinkage, 531 getInstrProfRuntimeHookVarUseFuncName(), M); 532 User->addFnAttr(Attribute::NoInline); 533 if (Options.NoRedZone) 534 User->addFnAttr(Attribute::NoRedZone); 535 User->setVisibility(GlobalValue::HiddenVisibility); 536 if (Triple(M->getTargetTriple()).supportsCOMDAT()) 537 User->setComdat(M->getOrInsertComdat(User->getName())); 538 539 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User)); 540 auto *Load = IRB.CreateLoad(Var); 541 IRB.CreateRet(Load); 542 543 // Mark the user variable as used so that it isn't stripped out. 544 UsedVars.push_back(User); 545 } 546 547 void InstrProfiling::emitUses() { 548 if (UsedVars.empty()) 549 return; 550 551 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used"); 552 std::vector<Constant *> MergedVars; 553 if (LLVMUsed) { 554 // Collect the existing members of llvm.used. 555 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer()); 556 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I) 557 MergedVars.push_back(Inits->getOperand(I)); 558 LLVMUsed->eraseFromParent(); 559 } 560 561 Type *i8PTy = Type::getInt8PtrTy(M->getContext()); 562 // Add uses for our data. 563 for (auto *Value : UsedVars) 564 MergedVars.push_back( 565 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy)); 566 567 // Recreate llvm.used. 568 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size()); 569 LLVMUsed = 570 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage, 571 ConstantArray::get(ATy, MergedVars), "llvm.used"); 572 LLVMUsed->setSection("llvm.metadata"); 573 } 574 575 void InstrProfiling::emitInitialization() { 576 StringRef InstrProfileOutput = Options.InstrProfileOutput; 577 578 if (!InstrProfileOutput.empty()) { 579 // Create variable for profile name. 580 Constant *ProfileNameConst = 581 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true); 582 GlobalVariable *ProfileNameVar = new GlobalVariable( 583 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage, 584 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR)); 585 Triple TT(M->getTargetTriple()); 586 if (TT.supportsCOMDAT()) { 587 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage); 588 ProfileNameVar->setComdat(M->getOrInsertComdat( 589 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR)))); 590 } 591 } 592 593 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName()); 594 if (!RegisterF) 595 return; 596 597 // Create the initialization function. 598 auto *VoidTy = Type::getVoidTy(M->getContext()); 599 auto *F = Function::Create(FunctionType::get(VoidTy, false), 600 GlobalValue::InternalLinkage, 601 getInstrProfInitFuncName(), M); 602 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 603 F->addFnAttr(Attribute::NoInline); 604 if (Options.NoRedZone) 605 F->addFnAttr(Attribute::NoRedZone); 606 607 // Add the basic block and the necessary calls. 608 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F)); 609 if (RegisterF) 610 IRB.CreateCall(RegisterF, {}); 611 IRB.CreateRetVoid(); 612 613 appendToGlobalCtors(*M, F, 0); 614 } 615