1 //===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===// 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 family of functions perform manipulations on Modules. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/Utils/ModuleUtils.h" 14 #include "llvm/Analysis/VectorUtils.h" 15 #include "llvm/IR/DerivedTypes.h" 16 #include "llvm/IR/Function.h" 17 #include "llvm/IR/IRBuilder.h" 18 #include "llvm/IR/MDBuilder.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include "llvm/Support/xxhash.h" 22 using namespace llvm; 23 24 #define DEBUG_TYPE "moduleutils" 25 26 static void appendToGlobalArray(StringRef ArrayName, Module &M, Function *F, 27 int Priority, Constant *Data) { 28 IRBuilder<> IRB(M.getContext()); 29 FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false); 30 31 // Get the current set of static global constructors and add the new ctor 32 // to the list. 33 SmallVector<Constant *, 16> CurrentCtors; 34 StructType *EltTy = StructType::get( 35 IRB.getInt32Ty(), PointerType::get(FnTy, F->getAddressSpace()), 36 IRB.getInt8PtrTy()); 37 38 if (GlobalVariable *GVCtor = M.getNamedGlobal(ArrayName)) { 39 if (Constant *Init = GVCtor->getInitializer()) { 40 unsigned n = Init->getNumOperands(); 41 CurrentCtors.reserve(n + 1); 42 for (unsigned i = 0; i != n; ++i) 43 CurrentCtors.push_back(cast<Constant>(Init->getOperand(i))); 44 } 45 GVCtor->eraseFromParent(); 46 } 47 48 // Build a 3 field global_ctor entry. We don't take a comdat key. 49 Constant *CSVals[3]; 50 CSVals[0] = IRB.getInt32(Priority); 51 CSVals[1] = F; 52 CSVals[2] = Data ? ConstantExpr::getPointerCast(Data, IRB.getInt8PtrTy()) 53 : Constant::getNullValue(IRB.getInt8PtrTy()); 54 Constant *RuntimeCtorInit = 55 ConstantStruct::get(EltTy, ArrayRef(CSVals, EltTy->getNumElements())); 56 57 CurrentCtors.push_back(RuntimeCtorInit); 58 59 // Create a new initializer. 60 ArrayType *AT = ArrayType::get(EltTy, CurrentCtors.size()); 61 Constant *NewInit = ConstantArray::get(AT, CurrentCtors); 62 63 // Create the new global variable and replace all uses of 64 // the old global variable with the new one. 65 (void)new GlobalVariable(M, NewInit->getType(), false, 66 GlobalValue::AppendingLinkage, NewInit, ArrayName); 67 } 68 69 void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data) { 70 appendToGlobalArray("llvm.global_ctors", M, F, Priority, Data); 71 } 72 73 void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data) { 74 appendToGlobalArray("llvm.global_dtors", M, F, Priority, Data); 75 } 76 77 static void collectUsedGlobals(GlobalVariable *GV, 78 SmallSetVector<Constant *, 16> &Init) { 79 if (!GV || !GV->hasInitializer()) 80 return; 81 82 auto *CA = cast<ConstantArray>(GV->getInitializer()); 83 for (Use &Op : CA->operands()) 84 Init.insert(cast<Constant>(Op)); 85 } 86 87 static void appendToUsedList(Module &M, StringRef Name, ArrayRef<GlobalValue *> Values) { 88 GlobalVariable *GV = M.getGlobalVariable(Name); 89 90 SmallSetVector<Constant *, 16> Init; 91 collectUsedGlobals(GV, Init); 92 if (GV) 93 GV->eraseFromParent(); 94 95 Type *ArrayEltTy = llvm::Type::getInt8PtrTy(M.getContext()); 96 for (auto *V : Values) 97 Init.insert(ConstantExpr::getPointerBitCastOrAddrSpaceCast(V, ArrayEltTy)); 98 99 if (Init.empty()) 100 return; 101 102 ArrayType *ATy = ArrayType::get(ArrayEltTy, Init.size()); 103 GV = new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage, 104 ConstantArray::get(ATy, Init.getArrayRef()), 105 Name); 106 GV->setSection("llvm.metadata"); 107 } 108 109 void llvm::appendToUsed(Module &M, ArrayRef<GlobalValue *> Values) { 110 appendToUsedList(M, "llvm.used", Values); 111 } 112 113 void llvm::appendToCompilerUsed(Module &M, ArrayRef<GlobalValue *> Values) { 114 appendToUsedList(M, "llvm.compiler.used", Values); 115 } 116 117 static void removeFromUsedList(Module &M, StringRef Name, 118 function_ref<bool(Constant *)> ShouldRemove) { 119 GlobalVariable *GV = M.getNamedGlobal(Name); 120 if (!GV) 121 return; 122 123 SmallSetVector<Constant *, 16> Init; 124 collectUsedGlobals(GV, Init); 125 126 Type *ArrayEltTy = cast<ArrayType>(GV->getValueType())->getElementType(); 127 128 SmallVector<Constant *, 16> NewInit; 129 for (Constant *MaybeRemoved : Init) { 130 if (!ShouldRemove(MaybeRemoved->stripPointerCasts())) 131 NewInit.push_back(MaybeRemoved); 132 } 133 134 if (!NewInit.empty()) { 135 ArrayType *ATy = ArrayType::get(ArrayEltTy, NewInit.size()); 136 GlobalVariable *NewGV = 137 new GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage, 138 ConstantArray::get(ATy, NewInit), "", GV, 139 GV->getThreadLocalMode(), GV->getAddressSpace()); 140 NewGV->setSection(GV->getSection()); 141 NewGV->takeName(GV); 142 } 143 144 GV->eraseFromParent(); 145 } 146 147 void llvm::removeFromUsedLists(Module &M, 148 function_ref<bool(Constant *)> ShouldRemove) { 149 removeFromUsedList(M, "llvm.used", ShouldRemove); 150 removeFromUsedList(M, "llvm.compiler.used", ShouldRemove); 151 } 152 153 void llvm::setKCFIType(Module &M, Function &F, StringRef MangledType) { 154 if (!M.getModuleFlag("kcfi")) 155 return; 156 // Matches CodeGenModule::CreateKCFITypeId in Clang. 157 LLVMContext &Ctx = M.getContext(); 158 MDBuilder MDB(Ctx); 159 F.setMetadata( 160 LLVMContext::MD_kcfi_type, 161 MDNode::get(Ctx, MDB.createConstant(ConstantInt::get( 162 Type::getInt32Ty(Ctx), 163 static_cast<uint32_t>(xxHash64(MangledType)))))); 164 } 165 166 FunctionCallee 167 llvm::declareSanitizerInitFunction(Module &M, StringRef InitName, 168 ArrayRef<Type *> InitArgTypes) { 169 assert(!InitName.empty() && "Expected init function name"); 170 return M.getOrInsertFunction( 171 InitName, 172 FunctionType::get(Type::getVoidTy(M.getContext()), InitArgTypes, false), 173 AttributeList()); 174 } 175 176 Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) { 177 Function *Ctor = Function::createWithDefaultAttr( 178 FunctionType::get(Type::getVoidTy(M.getContext()), false), 179 GlobalValue::InternalLinkage, M.getDataLayout().getProgramAddressSpace(), 180 CtorName, &M); 181 Ctor->addFnAttr(Attribute::NoUnwind); 182 setKCFIType(M, *Ctor, "_ZTSFvvE"); // void (*)(void) 183 BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor); 184 ReturnInst::Create(M.getContext(), CtorBB); 185 // Ensure Ctor cannot be discarded, even if in a comdat. 186 appendToUsed(M, {Ctor}); 187 return Ctor; 188 } 189 190 std::pair<Function *, FunctionCallee> llvm::createSanitizerCtorAndInitFunctions( 191 Module &M, StringRef CtorName, StringRef InitName, 192 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs, 193 StringRef VersionCheckName) { 194 assert(!InitName.empty() && "Expected init function name"); 195 assert(InitArgs.size() == InitArgTypes.size() && 196 "Sanitizer's init function expects different number of arguments"); 197 FunctionCallee InitFunction = 198 declareSanitizerInitFunction(M, InitName, InitArgTypes); 199 Function *Ctor = createSanitizerCtor(M, CtorName); 200 IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator()); 201 IRB.CreateCall(InitFunction, InitArgs); 202 if (!VersionCheckName.empty()) { 203 FunctionCallee VersionCheckFunction = M.getOrInsertFunction( 204 VersionCheckName, FunctionType::get(IRB.getVoidTy(), {}, false), 205 AttributeList()); 206 IRB.CreateCall(VersionCheckFunction, {}); 207 } 208 return std::make_pair(Ctor, InitFunction); 209 } 210 211 std::pair<Function *, FunctionCallee> 212 llvm::getOrCreateSanitizerCtorAndInitFunctions( 213 Module &M, StringRef CtorName, StringRef InitName, 214 ArrayRef<Type *> InitArgTypes, ArrayRef<Value *> InitArgs, 215 function_ref<void(Function *, FunctionCallee)> FunctionsCreatedCallback, 216 StringRef VersionCheckName) { 217 assert(!CtorName.empty() && "Expected ctor function name"); 218 219 if (Function *Ctor = M.getFunction(CtorName)) 220 // FIXME: Sink this logic into the module, similar to the handling of 221 // globals. This will make moving to a concurrent model much easier. 222 if (Ctor->arg_empty() || 223 Ctor->getReturnType() == Type::getVoidTy(M.getContext())) 224 return {Ctor, declareSanitizerInitFunction(M, InitName, InitArgTypes)}; 225 226 Function *Ctor; 227 FunctionCallee InitFunction; 228 std::tie(Ctor, InitFunction) = llvm::createSanitizerCtorAndInitFunctions( 229 M, CtorName, InitName, InitArgTypes, InitArgs, VersionCheckName); 230 FunctionsCreatedCallback(Ctor, InitFunction); 231 return std::make_pair(Ctor, InitFunction); 232 } 233 234 void llvm::filterDeadComdatFunctions( 235 SmallVectorImpl<Function *> &DeadComdatFunctions) { 236 SmallPtrSet<Function *, 32> MaybeDeadFunctions; 237 SmallPtrSet<Comdat *, 32> MaybeDeadComdats; 238 for (Function *F : DeadComdatFunctions) { 239 MaybeDeadFunctions.insert(F); 240 if (Comdat *C = F->getComdat()) 241 MaybeDeadComdats.insert(C); 242 } 243 244 // Find comdats for which all users are dead now. 245 SmallPtrSet<Comdat *, 32> DeadComdats; 246 for (Comdat *C : MaybeDeadComdats) { 247 auto IsUserDead = [&](GlobalObject *GO) { 248 auto *F = dyn_cast<Function>(GO); 249 return F && MaybeDeadFunctions.contains(F); 250 }; 251 if (all_of(C->getUsers(), IsUserDead)) 252 DeadComdats.insert(C); 253 } 254 255 // Only keep functions which have no comdat or a dead comdat. 256 erase_if(DeadComdatFunctions, [&](Function *F) { 257 Comdat *C = F->getComdat(); 258 return C && !DeadComdats.contains(C); 259 }); 260 } 261 262 std::string llvm::getUniqueModuleId(Module *M) { 263 MD5 Md5; 264 bool ExportsSymbols = false; 265 auto AddGlobal = [&](GlobalValue &GV) { 266 if (GV.isDeclaration() || GV.getName().startswith("llvm.") || 267 !GV.hasExternalLinkage() || GV.hasComdat()) 268 return; 269 ExportsSymbols = true; 270 Md5.update(GV.getName()); 271 Md5.update(ArrayRef<uint8_t>{0}); 272 }; 273 274 for (auto &F : *M) 275 AddGlobal(F); 276 for (auto &GV : M->globals()) 277 AddGlobal(GV); 278 for (auto &GA : M->aliases()) 279 AddGlobal(GA); 280 for (auto &IF : M->ifuncs()) 281 AddGlobal(IF); 282 283 if (!ExportsSymbols) 284 return ""; 285 286 MD5::MD5Result R; 287 Md5.final(R); 288 289 SmallString<32> Str; 290 MD5::stringifyResult(R, Str); 291 return ("." + Str).str(); 292 } 293 294 void VFABI::setVectorVariantNames(CallInst *CI, 295 ArrayRef<std::string> VariantMappings) { 296 if (VariantMappings.empty()) 297 return; 298 299 SmallString<256> Buffer; 300 llvm::raw_svector_ostream Out(Buffer); 301 for (const std::string &VariantMapping : VariantMappings) 302 Out << VariantMapping << ","; 303 // Get rid of the trailing ','. 304 assert(!Buffer.str().empty() && "Must have at least one char."); 305 Buffer.pop_back(); 306 307 Module *M = CI->getModule(); 308 #ifndef NDEBUG 309 for (const std::string &VariantMapping : VariantMappings) { 310 LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << VariantMapping << "'\n"); 311 std::optional<VFInfo> VI = VFABI::tryDemangleForVFABI(VariantMapping, *M); 312 assert(VI && "Cannot add an invalid VFABI name."); 313 assert(M->getNamedValue(VI->VectorName) && 314 "Cannot add variant to attribute: " 315 "vector function declaration is missing."); 316 } 317 #endif 318 CI->addFnAttr( 319 Attribute::get(M->getContext(), MappingsAttrName, Buffer.str())); 320 } 321 322 void llvm::embedBufferInModule(Module &M, MemoryBufferRef Buf, 323 StringRef SectionName, Align Alignment) { 324 // Embed the memory buffer into the module. 325 Constant *ModuleConstant = ConstantDataArray::get( 326 M.getContext(), ArrayRef(Buf.getBufferStart(), Buf.getBufferSize())); 327 GlobalVariable *GV = new GlobalVariable( 328 M, ModuleConstant->getType(), true, GlobalValue::PrivateLinkage, 329 ModuleConstant, "llvm.embedded.object"); 330 GV->setSection(SectionName); 331 GV->setAlignment(Alignment); 332 333 LLVMContext &Ctx = M.getContext(); 334 NamedMDNode *MD = M.getOrInsertNamedMetadata("llvm.embedded.objects"); 335 Metadata *MDVals[] = {ConstantAsMetadata::get(GV), 336 MDString::get(Ctx, SectionName)}; 337 338 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 339 GV->setMetadata(LLVMContext::MD_exclude, llvm::MDNode::get(Ctx, {})); 340 341 appendToCompilerUsed(M, GV); 342 } 343