1 //===- llvm/unittest/Linker/LinkModulesTest.cpp - IRBuilder tests ---------===// 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-c/Core.h" 10 #include "llvm-c/Linker.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/AsmParser/Parser.h" 13 #include "llvm/IR/BasicBlock.h" 14 #include "llvm/IR/DataLayout.h" 15 #include "llvm/IR/Function.h" 16 #include "llvm/IR/IRBuilder.h" 17 #include "llvm/IR/Module.h" 18 #include "llvm/Linker/Linker.h" 19 #include "llvm/Support/SourceMgr.h" 20 #include "gtest/gtest.h" 21 22 using namespace llvm; 23 24 namespace { 25 26 class LinkModuleTest : public testing::Test { 27 protected: 28 void SetUp() override { 29 M.reset(new Module("MyModule", Ctx)); 30 FunctionType *FTy = FunctionType::get( 31 Type::getInt8PtrTy(Ctx), Type::getInt32Ty(Ctx), false /*=isVarArg*/); 32 F = Function::Create(FTy, Function::ExternalLinkage, "ba_func", M.get()); 33 F->setCallingConv(CallingConv::C); 34 35 EntryBB = BasicBlock::Create(Ctx, "entry", F); 36 SwitchCase1BB = BasicBlock::Create(Ctx, "switch.case.1", F); 37 SwitchCase2BB = BasicBlock::Create(Ctx, "switch.case.2", F); 38 ExitBB = BasicBlock::Create(Ctx, "exit", F); 39 40 AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3); 41 42 GV = new GlobalVariable(*M.get(), AT, false /*=isConstant*/, 43 GlobalValue::InternalLinkage, nullptr,"switch.bas"); 44 45 // Global Initializer 46 std::vector<Constant *> Init; 47 Constant *SwitchCase1BA = BlockAddress::get(SwitchCase1BB); 48 Init.push_back(SwitchCase1BA); 49 50 Constant *SwitchCase2BA = BlockAddress::get(SwitchCase2BB); 51 Init.push_back(SwitchCase2BA); 52 53 ConstantInt *One = ConstantInt::get(Type::getInt32Ty(Ctx), 1); 54 Constant *OnePtr = ConstantExpr::getIntToPtr(One, Type::getInt8PtrTy(Ctx)); 55 Init.push_back(OnePtr); 56 57 GV->setInitializer(ConstantArray::get(AT, Init)); 58 } 59 60 void TearDown() override { M.reset(); } 61 62 LLVMContext Ctx; 63 std::unique_ptr<Module> M; 64 Function *F; 65 ArrayType *AT; 66 GlobalVariable *GV; 67 BasicBlock *EntryBB; 68 BasicBlock *SwitchCase1BB; 69 BasicBlock *SwitchCase2BB; 70 BasicBlock *ExitBB; 71 }; 72 73 static void expectNoDiags(const DiagnosticInfo &DI, void *C) { 74 llvm_unreachable("expectNoDiags called!"); 75 } 76 77 TEST_F(LinkModuleTest, BlockAddress) { 78 IRBuilder<> Builder(EntryBB); 79 80 std::vector<Value *> GEPIndices; 81 GEPIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ctx), 0)); 82 GEPIndices.push_back(&*F->arg_begin()); 83 84 Value *GEP = Builder.CreateGEP(AT, GV, GEPIndices, "switch.gep"); 85 Value *Load = Builder.CreateLoad(AT->getElementType(), GEP, "switch.load"); 86 87 Builder.CreateRet(Load); 88 89 Builder.SetInsertPoint(SwitchCase1BB); 90 Builder.CreateBr(ExitBB); 91 92 Builder.SetInsertPoint(SwitchCase2BB); 93 Builder.CreateBr(ExitBB); 94 95 Builder.SetInsertPoint(ExitBB); 96 Builder.CreateRet(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx))); 97 98 Module *LinkedModule = new Module("MyModuleLinked", Ctx); 99 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 100 Linker::linkModules(*LinkedModule, std::move(M)); 101 102 // Check that the global "@switch.bas" is well-formed. 103 const GlobalVariable *LinkedGV = LinkedModule->getNamedGlobal("switch.bas"); 104 const Constant *Init = LinkedGV->getInitializer(); 105 106 // @switch.bas = internal global [3 x i8*] 107 // [i8* blockaddress(@ba_func, %switch.case.1), 108 // i8* blockaddress(@ba_func, %switch.case.2), 109 // i8* inttoptr (i32 1 to i8*)] 110 111 ArrayType *AT = ArrayType::get(Type::getInt8PtrTy(Ctx), 3); 112 EXPECT_EQ(AT, Init->getType()); 113 114 Value *Elem = Init->getOperand(0); 115 ASSERT_TRUE(isa<BlockAddress>(Elem)); 116 EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(), 117 LinkedModule->getFunction("ba_func")); 118 EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(), 119 LinkedModule->getFunction("ba_func")); 120 121 Elem = Init->getOperand(1); 122 ASSERT_TRUE(isa<BlockAddress>(Elem)); 123 EXPECT_EQ(cast<BlockAddress>(Elem)->getFunction(), 124 LinkedModule->getFunction("ba_func")); 125 EXPECT_EQ(cast<BlockAddress>(Elem)->getBasicBlock()->getParent(), 126 LinkedModule->getFunction("ba_func")); 127 128 delete LinkedModule; 129 } 130 131 static Module *getExternal(LLVMContext &Ctx, StringRef FuncName) { 132 // Create a module with an empty externally-linked function 133 Module *M = new Module("ExternalModule", Ctx); 134 FunctionType *FTy = FunctionType::get( 135 Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/); 136 137 Function *F = 138 Function::Create(FTy, Function::ExternalLinkage, FuncName, M); 139 F->setCallingConv(CallingConv::C); 140 141 BasicBlock *BB = BasicBlock::Create(Ctx, "", F); 142 IRBuilder<> Builder(BB); 143 Builder.CreateRetVoid(); 144 return M; 145 } 146 147 static Module *getInternal(LLVMContext &Ctx) { 148 Module *InternalM = new Module("InternalModule", Ctx); 149 FunctionType *FTy = FunctionType::get( 150 Type::getVoidTy(Ctx), Type::getInt8PtrTy(Ctx), false /*=isVarArgs*/); 151 152 Function *F = 153 Function::Create(FTy, Function::InternalLinkage, "bar", InternalM); 154 F->setCallingConv(CallingConv::C); 155 156 BasicBlock *BB = BasicBlock::Create(Ctx, "", F); 157 IRBuilder<> Builder(BB); 158 Builder.CreateRetVoid(); 159 160 StructType *STy = StructType::create(Ctx, PointerType::get(FTy, 0)); 161 162 GlobalVariable *GV = 163 new GlobalVariable(*InternalM, STy, false /*=isConstant*/, 164 GlobalValue::InternalLinkage, nullptr, "g"); 165 166 GV->setInitializer(ConstantStruct::get(STy, F)); 167 return InternalM; 168 } 169 170 TEST_F(LinkModuleTest, EmptyModule) { 171 std::unique_ptr<Module> InternalM(getInternal(Ctx)); 172 std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx)); 173 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 174 Linker::linkModules(*EmptyM, std::move(InternalM)); 175 } 176 177 TEST_F(LinkModuleTest, EmptyModule2) { 178 std::unique_ptr<Module> InternalM(getInternal(Ctx)); 179 std::unique_ptr<Module> EmptyM(new Module("EmptyModule1", Ctx)); 180 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 181 Linker::linkModules(*InternalM, std::move(EmptyM)); 182 } 183 184 TEST_F(LinkModuleTest, TypeMerge) { 185 LLVMContext C; 186 SMDiagnostic Err; 187 188 const char *M1Str = "%t = type {i32}\n" 189 "@t1 = weak global %t zeroinitializer\n"; 190 std::unique_ptr<Module> M1 = parseAssemblyString(M1Str, Err, C); 191 192 const char *M2Str = "%t = type {i32}\n" 193 "@t2 = weak global %t zeroinitializer\n"; 194 std::unique_ptr<Module> M2 = parseAssemblyString(M2Str, Err, C); 195 196 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 197 Linker::linkModules(*M1, std::move(M2)); 198 199 EXPECT_EQ(M1->getNamedGlobal("t1")->getType(), 200 M1->getNamedGlobal("t2")->getType()); 201 } 202 203 TEST_F(LinkModuleTest, NewCAPISuccess) { 204 std::unique_ptr<Module> DestM(getExternal(Ctx, "foo")); 205 std::unique_ptr<Module> SourceM(getExternal(Ctx, "bar")); 206 LLVMBool Result = 207 LLVMLinkModules2(wrap(DestM.get()), wrap(SourceM.release())); 208 EXPECT_EQ(0, Result); 209 // "bar" is present in destination module 210 EXPECT_NE(nullptr, DestM->getFunction("bar")); 211 } 212 213 static void diagnosticHandler(LLVMDiagnosticInfoRef DI, void *C) { 214 auto *Err = reinterpret_cast<std::string *>(C); 215 char *CErr = LLVMGetDiagInfoDescription(DI); 216 *Err = CErr; 217 LLVMDisposeMessage(CErr); 218 } 219 220 TEST_F(LinkModuleTest, NewCAPIFailure) { 221 // Symbol clash between two modules 222 LLVMContext Ctx; 223 std::string Err; 224 LLVMContextSetDiagnosticHandler(wrap(&Ctx), diagnosticHandler, &Err); 225 226 std::unique_ptr<Module> DestM(getExternal(Ctx, "foo")); 227 std::unique_ptr<Module> SourceM(getExternal(Ctx, "foo")); 228 LLVMBool Result = 229 LLVMLinkModules2(wrap(DestM.get()), wrap(SourceM.release())); 230 EXPECT_EQ(1, Result); 231 EXPECT_EQ("Linking globals named 'foo': symbol multiply defined!", Err); 232 } 233 234 TEST_F(LinkModuleTest, MoveDistinctMDs) { 235 LLVMContext C; 236 SMDiagnostic Err; 237 238 const char *SrcStr = "define void @foo() !attach !0 {\n" 239 "entry:\n" 240 " call void @llvm.md(metadata !1)\n" 241 " ret void, !attach !2\n" 242 "}\n" 243 "declare void @llvm.md(metadata)\n" 244 "!named = !{!3, !4}\n" 245 "!0 = distinct !{}\n" 246 "!1 = distinct !{}\n" 247 "!2 = distinct !{}\n" 248 "!3 = distinct !{}\n" 249 "!4 = !{!3}\n"; 250 251 std::unique_ptr<Module> Src = parseAssemblyString(SrcStr, Err, C); 252 assert(Src); 253 ASSERT_TRUE(Src.get()); 254 255 // Get the addresses of the Metadata before merging. 256 Function *F = &*Src->begin(); 257 ASSERT_EQ("foo", F->getName()); 258 BasicBlock *BB = &F->getEntryBlock(); 259 auto *CI = cast<CallInst>(&BB->front()); 260 auto *RI = cast<ReturnInst>(BB->getTerminator()); 261 NamedMDNode *NMD = &*Src->named_metadata_begin(); 262 263 MDNode *M0 = F->getMetadata("attach"); 264 MDNode *M1 = 265 cast<MDNode>(cast<MetadataAsValue>(CI->getArgOperand(0))->getMetadata()); 266 MDNode *M2 = RI->getMetadata("attach"); 267 MDNode *M3 = NMD->getOperand(0); 268 MDNode *M4 = NMD->getOperand(1); 269 270 // Confirm a few things about the IR. 271 EXPECT_TRUE(M0->isDistinct()); 272 EXPECT_TRUE(M1->isDistinct()); 273 EXPECT_TRUE(M2->isDistinct()); 274 EXPECT_TRUE(M3->isDistinct()); 275 EXPECT_TRUE(M4->isUniqued()); 276 EXPECT_EQ(M3, M4->getOperand(0)); 277 278 // Link into destination module. 279 auto Dst = std::make_unique<Module>("Linked", C); 280 ASSERT_TRUE(Dst.get()); 281 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 282 Linker::linkModules(*Dst, std::move(Src)); 283 284 // Check that distinct metadata was moved, not cloned. Even !4, the uniqued 285 // node, should effectively be moved, since its only operand hasn't changed. 286 F = &*Dst->begin(); 287 BB = &F->getEntryBlock(); 288 CI = cast<CallInst>(&BB->front()); 289 RI = cast<ReturnInst>(BB->getTerminator()); 290 NMD = &*Dst->named_metadata_begin(); 291 292 EXPECT_EQ(M0, F->getMetadata("attach")); 293 EXPECT_EQ(M1, cast<MetadataAsValue>(CI->getArgOperand(0))->getMetadata()); 294 EXPECT_EQ(M2, RI->getMetadata("attach")); 295 EXPECT_EQ(M3, NMD->getOperand(0)); 296 EXPECT_EQ(M4, NMD->getOperand(1)); 297 298 // Confirm a few things about the IR. This shouldn't have changed. 299 EXPECT_TRUE(M0->isDistinct()); 300 EXPECT_TRUE(M1->isDistinct()); 301 EXPECT_TRUE(M2->isDistinct()); 302 EXPECT_TRUE(M3->isDistinct()); 303 EXPECT_TRUE(M4->isUniqued()); 304 EXPECT_EQ(M3, M4->getOperand(0)); 305 } 306 307 TEST_F(LinkModuleTest, RemangleIntrinsics) { 308 LLVMContext C; 309 SMDiagnostic Err; 310 311 // We load two modules inside the same context C. In both modules there is a 312 // "struct.rtx_def" type. In the module loaded the second (Bar) this type will 313 // be renamed to "struct.rtx_def.0". Check that the intrinsics which have this 314 // type in the signature are properly remangled. 315 const char *FooStr = 316 "%struct.rtx_def = type { i16 }\n" 317 "define void @foo(%struct.rtx_def %a) {\n" 318 " call %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def %a)\n" 319 " ret void\n" 320 "}\n" 321 "declare %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def)\n"; 322 323 const char *BarStr = 324 "%struct.rtx_def = type { i16 }\n" 325 "define void @bar(%struct.rtx_def %a) {\n" 326 " call %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def %a)\n" 327 " ret void\n" 328 "}\n" 329 "declare %struct.rtx_def @llvm.ssa.copy.s_struct.rtx_defs(%struct.rtx_def)\n"; 330 331 std::unique_ptr<Module> Foo = parseAssemblyString(FooStr, Err, C); 332 assert(Foo); 333 ASSERT_TRUE(Foo.get()); 334 // Foo is loaded first, so the type and the intrinsic have theis original 335 // names. 336 ASSERT_TRUE(Foo->getFunction("llvm.ssa.copy.s_struct.rtx_defs")); 337 ASSERT_FALSE(Foo->getFunction("llvm.ssa.copy.s_struct.rtx_defs.0")); 338 339 std::unique_ptr<Module> Bar = parseAssemblyString(BarStr, Err, C); 340 assert(Bar); 341 ASSERT_TRUE(Bar.get()); 342 // Bar is loaded after Foo, so the type is renamed to struct.rtx_def.0. Check 343 // that the intrinsic is also renamed. 344 ASSERT_FALSE(Bar->getFunction("llvm.ssa.copy.s_struct.rtx_defs")); 345 ASSERT_TRUE(Bar->getFunction("llvm.ssa.copy.s_struct.rtx_def.0s")); 346 347 // Link two modules together. 348 auto Dst = std::make_unique<Module>("Linked", C); 349 ASSERT_TRUE(Dst.get()); 350 Ctx.setDiagnosticHandlerCallBack(expectNoDiags); 351 bool Failed = Linker::linkModules(*Foo, std::move(Bar)); 352 ASSERT_FALSE(Failed); 353 354 // "struct.rtx_def" from Foo and "struct.rtx_def.0" from Bar are isomorphic 355 // types, so they must be uniquified by linker. Check that they use the same 356 // intrinsic definition. 357 Function *F = Foo->getFunction("llvm.ssa.copy.s_struct.rtx_defs"); 358 ASSERT_EQ(F->getNumUses(), (unsigned)2); 359 } 360 361 } // end anonymous namespace 362