Debian Codegraph @

llvm/unittests/Transforms/Utils/CloningTest.cpp

raw
1 //===- Cloning.cpp - Unit tests for the Cloner ----------------------------===//
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/Cloning.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/Analysis/AliasAnalysis.h"
13 #include "llvm/Analysis/DomTreeUpdater.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/AsmParser/Parser.h"
16 #include "llvm/IR/Argument.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Transforms/Utils/ValueMapper.h"
32 #include "gtest/gtest.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 class CloneInstruction : public ::testing::Test {
39 protected:
40 void SetUp() override { V = nullptr; }
41
42 template <typename T>
43 T *clone(T *V1) {
44 Value *V2 = V1->clone();
45 Orig.insert(V1);
46 Clones.insert(V2);
47 return cast<T>(V2);
48 }
49
50 void eraseClones() {
51 for (Value *V : Clones)
52 V->deleteValue();
53 Clones.clear();
54 }
55
56 void TearDown() override {
57 eraseClones();
58 for (Value *V : Orig)
59 V->deleteValue();
60 Orig.clear();
61 if (V)
62 V->deleteValue();
63 }
64
65 SmallPtrSet<Value *, 4> Orig; // Erase on exit
66 SmallPtrSet<Value *, 4> Clones; // Erase in eraseClones
67
68 LLVMContext context;
69 Value *V;
70 };
71
72 TEST_F(CloneInstruction, OverflowBits) {
73 V = new Argument(Type::getInt32Ty(context));
74
75 BinaryOperator *Add = BinaryOperator::Create(Instruction::Add, V, V);
76 BinaryOperator *Sub = BinaryOperator::Create(Instruction::Sub, V, V);
77 BinaryOperator *Mul = BinaryOperator::Create(Instruction::Mul, V, V);
78
79 BinaryOperator *AddClone = this->clone(Add);
80 BinaryOperator *SubClone = this->clone(Sub);
81 BinaryOperator *MulClone = this->clone(Mul);
82
83 EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
84 EXPECT_FALSE(AddClone->hasNoSignedWrap());
85 EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
86 EXPECT_FALSE(SubClone->hasNoSignedWrap());
87 EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
88 EXPECT_FALSE(MulClone->hasNoSignedWrap());
89
90 eraseClones();
91
92 Add->setHasNoUnsignedWrap();
93 Sub->setHasNoUnsignedWrap();
94 Mul->setHasNoUnsignedWrap();
95
96 AddClone = this->clone(Add);
97 SubClone = this->clone(Sub);
98 MulClone = this->clone(Mul);
99
100 EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
101 EXPECT_FALSE(AddClone->hasNoSignedWrap());
102 EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
103 EXPECT_FALSE(SubClone->hasNoSignedWrap());
104 EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
105 EXPECT_FALSE(MulClone->hasNoSignedWrap());
106
107 eraseClones();
108
109 Add->setHasNoSignedWrap();
110 Sub->setHasNoSignedWrap();
111 Mul->setHasNoSignedWrap();
112
113 AddClone = this->clone(Add);
114 SubClone = this->clone(Sub);
115 MulClone = this->clone(Mul);
116
117 EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
118 EXPECT_TRUE(AddClone->hasNoSignedWrap());
119 EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
120 EXPECT_TRUE(SubClone->hasNoSignedWrap());
121 EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
122 EXPECT_TRUE(MulClone->hasNoSignedWrap());
123
124 eraseClones();
125
126 Add->setHasNoUnsignedWrap(false);
127 Sub->setHasNoUnsignedWrap(false);
128 Mul->setHasNoUnsignedWrap(false);
129
130 AddClone = this->clone(Add);
131 SubClone = this->clone(Sub);
132 MulClone = this->clone(Mul);
133
134 EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
135 EXPECT_TRUE(AddClone->hasNoSignedWrap());
136 EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
137 EXPECT_TRUE(SubClone->hasNoSignedWrap());
138 EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
139 EXPECT_TRUE(MulClone->hasNoSignedWrap());
140 }
141
142 TEST_F(CloneInstruction, Inbounds) {
143 V = new Argument(PointerType::get(context, 0));
144
145 Constant *Z = Constant::getNullValue(Type::getInt32Ty(context));
146 std::vector<Value *> ops;
147 ops.push_back(Z);
148 GetElementPtrInst *GEP =
149 GetElementPtrInst::Create(Type::getInt32Ty(context), V, ops);
150 EXPECT_FALSE(this->clone(GEP)->isInBounds());
151
152 GEP->setIsInBounds();
153 EXPECT_TRUE(this->clone(GEP)->isInBounds());
154 }
155
156 TEST_F(CloneInstruction, Exact) {
157 V = new Argument(Type::getInt32Ty(context));
158
159 BinaryOperator *SDiv = BinaryOperator::Create(Instruction::SDiv, V, V);
160 EXPECT_FALSE(this->clone(SDiv)->isExact());
161
162 SDiv->setIsExact(true);
163 EXPECT_TRUE(this->clone(SDiv)->isExact());
164 }
165
166 TEST_F(CloneInstruction, Attributes) {
167 Type *ArgTy1[] = {PointerType::get(context, 0)};
168 FunctionType *FT1 =
169 FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
170
171 Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
172 BasicBlock *BB = BasicBlock::Create(context, "", F1);
173 IRBuilder<> Builder(BB);
174 Builder.CreateRetVoid();
175
176 Function *F2 = Function::Create(FT1, Function::ExternalLinkage);
177
178 Argument *A = &*F1->arg_begin();
179 A->addAttr(
180 Attribute::getWithCaptureInfo(A->getContext(), CaptureInfo::none()));
181
182 SmallVector<ReturnInst*, 4> Returns;
183 ValueToValueMapTy VMap;
184 VMap[A] = UndefValue::get(A->getType());
185
186 CloneFunctionInto(F2, F1, VMap, CloneFunctionChangeType::LocalChangesOnly,
187 Returns);
188 EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr());
189
190 delete F1;
191 delete F2;
192 }
193
194 TEST_F(CloneInstruction, CallingConvention) {
195 Type *ArgTy1[] = {PointerType::get(context, 0)};
196 FunctionType *FT1 =
197 FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
198
199 Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
200 F1->setCallingConv(CallingConv::Cold);
201 BasicBlock *BB = BasicBlock::Create(context, "", F1);
202 IRBuilder<> Builder(BB);
203 Builder.CreateRetVoid();
204
205 Function *F2 = Function::Create(FT1, Function::ExternalLinkage);
206
207 SmallVector<ReturnInst*, 4> Returns;
208 ValueToValueMapTy VMap;
209 VMap[&*F1->arg_begin()] = &*F2->arg_begin();
210
211 CloneFunctionInto(F2, F1, VMap, CloneFunctionChangeType::LocalChangesOnly,
212 Returns);
213 EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());
214
215 delete F1;
216 delete F2;
217 }
218
219 TEST_F(CloneInstruction, DuplicateInstructionsToSplit) {
220 Type *ArgTy1[] = {PointerType::get(context, 0)};
221 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
222 V = new Argument(Type::getInt32Ty(context));
223
224 Function *F = Function::Create(FT, Function::ExternalLinkage);
225
226 BasicBlock *BB1 = BasicBlock::Create(context, "", F);
227 IRBuilder<> Builder1(BB1);
228
229 BasicBlock *BB2 = BasicBlock::Create(context, "", F);
230 IRBuilder<> Builder2(BB2);
231
232 Builder1.CreateBr(BB2);
233
234 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
235 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
236 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
237 Builder2.CreateRetVoid();
238
239 // Dummy DTU.
240 ValueToValueMapTy Mapping;
241 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
242 auto Split =
243 DuplicateInstructionsInSplitBetween(BB2, BB1, SubInst, Mapping, DTU);
244
245 EXPECT_TRUE(Split);
246 EXPECT_EQ(Mapping.size(), 2u);
247 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
248 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
249
250 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
251 EXPECT_TRUE(AddSplit);
252 EXPECT_EQ(AddSplit->getOperand(0), V);
253 EXPECT_EQ(AddSplit->getOperand(1), V);
254 EXPECT_EQ(AddSplit->getParent(), Split);
255
256 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
257 EXPECT_TRUE(MulSplit);
258 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
259 EXPECT_EQ(MulSplit->getOperand(1), V);
260 EXPECT_EQ(MulSplit->getParent(), Split);
261
262 EXPECT_EQ(AddSplit->getNextNode(), MulSplit);
263 EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());
264
265 delete F;
266 }
267
268 TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq1) {
269 Type *ArgTy1[] = {PointerType::get(context, 0)};
270 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
271 V = new Argument(Type::getInt32Ty(context));
272
273 Function *F = Function::Create(FT, Function::ExternalLinkage);
274
275 BasicBlock *BB1 = BasicBlock::Create(context, "", F);
276 IRBuilder<> Builder1(BB1);
277
278 BasicBlock *BB2 = BasicBlock::Create(context, "", F);
279 IRBuilder<> Builder2(BB2);
280
281 Builder1.CreateBr(BB2);
282
283 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
284 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
285 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
286 Builder2.CreateBr(BB2);
287
288 // Dummy DTU.
289 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
290 ValueToValueMapTy Mapping;
291 auto Split = DuplicateInstructionsInSplitBetween(
292 BB2, BB2, BB2->getTerminator(), Mapping, DTU);
293
294 EXPECT_TRUE(Split);
295 EXPECT_EQ(Mapping.size(), 3u);
296 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
297 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
298 EXPECT_TRUE(Mapping.find(SubInst) != Mapping.end());
299
300 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
301 EXPECT_TRUE(AddSplit);
302 EXPECT_EQ(AddSplit->getOperand(0), V);
303 EXPECT_EQ(AddSplit->getOperand(1), V);
304 EXPECT_EQ(AddSplit->getParent(), Split);
305
306 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
307 EXPECT_TRUE(MulSplit);
308 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
309 EXPECT_EQ(MulSplit->getOperand(1), V);
310 EXPECT_EQ(MulSplit->getParent(), Split);
311
312 auto SubSplit = dyn_cast<Instruction>(Mapping[SubInst]);
313 EXPECT_EQ(MulSplit->getNextNode(), SubSplit);
314 EXPECT_EQ(SubSplit->getNextNode(), Split->getTerminator());
315 EXPECT_EQ(Split->getSingleSuccessor(), BB2);
316 EXPECT_EQ(BB2->getSingleSuccessor(), Split);
317
318 delete F;
319 }
320
321 TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq2) {
322 Type *ArgTy1[] = {PointerType::get(context, 0)};
323 FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
324 V = new Argument(Type::getInt32Ty(context));
325
326 Function *F = Function::Create(FT, Function::ExternalLinkage);
327
328 BasicBlock *BB1 = BasicBlock::Create(context, "", F);
329 IRBuilder<> Builder1(BB1);
330
331 BasicBlock *BB2 = BasicBlock::Create(context, "", F);
332 IRBuilder<> Builder2(BB2);
333
334 Builder1.CreateBr(BB2);
335
336 Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
337 Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
338 Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
339 Builder2.CreateBr(BB2);
340
341 // Dummy DTU.
342 DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
343 ValueToValueMapTy Mapping;
344 auto Split =
345 DuplicateInstructionsInSplitBetween(BB2, BB2, SubInst, Mapping, DTU);
346
347 EXPECT_TRUE(Split);
348 EXPECT_EQ(Mapping.size(), 2u);
349 EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
350 EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
351
352 auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
353 EXPECT_TRUE(AddSplit);
354 EXPECT_EQ(AddSplit->getOperand(0), V);
355 EXPECT_EQ(AddSplit->getOperand(1), V);
356 EXPECT_EQ(AddSplit->getParent(), Split);
357
358 auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
359 EXPECT_TRUE(MulSplit);
360 EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
361 EXPECT_EQ(MulSplit->getOperand(1), V);
362 EXPECT_EQ(MulSplit->getParent(), Split);
363 EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());
364 EXPECT_EQ(Split->getSingleSuccessor(), BB2);
365 EXPECT_EQ(BB2->getSingleSuccessor(), Split);
366
367 delete F;
368 }
369
370 static void runWithLoopInfoAndDominatorTree(
371 Module &M, StringRef FuncName,
372 function_ref<void(Function &F, LoopInfo &LI, DominatorTree &DT)> Test) {
373 auto *F = M.getFunction(FuncName);
374 ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
375
376 DominatorTree DT(*F);
377 LoopInfo LI(DT);
378
379 Test(*F, LI, DT);
380 }
381
382 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
383 SMDiagnostic Err;
384 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
385 if (!Mod)
386 Err.print("CloneLoop", errs());
387 return Mod;
388 }
389
390 TEST(CloneLoop, CloneLoopNest) {
391 // Parse the module.
392 LLVMContext Context;
393
394 std::unique_ptr<Module> M = parseIR(
395 Context,
396 R"(define void @foo(i32* %A, i32 %ub) {
397 entry:
398 %guardcmp = icmp slt i32 0, %ub
399 br i1 %guardcmp, label %for.outer.preheader, label %for.end
400 for.outer.preheader:
401 br label %for.outer
402 for.outer:
403 %j = phi i32 [ 0, %for.outer.preheader ], [ %inc.outer, %for.outer.latch ]
404 br i1 %guardcmp, label %for.inner.preheader, label %for.outer.latch
405 for.inner.preheader:
406 br label %for.inner
407 for.inner:
408 %i = phi i32 [ 0, %for.inner.preheader ], [ %inc, %for.inner ]
409 %idxprom = sext i32 %i to i64
410 %arrayidx = getelementptr inbounds i32, i32* %A, i64 %idxprom
411 store i32 %i, i32* %arrayidx, align 4
412 %inc = add nsw i32 %i, 1
413 %cmp = icmp slt i32 %inc, %ub
414 br i1 %cmp, label %for.inner, label %for.inner.exit
415 for.inner.exit:
416 br label %for.outer.latch
417 for.outer.latch:
418 %inc.outer = add nsw i32 %j, 1
419 %cmp.outer = icmp slt i32 %inc.outer, %ub
420 br i1 %cmp.outer, label %for.outer, label %for.outer.exit
421 for.outer.exit:
422 br label %for.end
423 for.end:
424 ret void
425 })"
426 );
427
428 runWithLoopInfoAndDominatorTree(
429 *M, "foo", [&](Function &F, LoopInfo &LI, DominatorTree &DT) {
430 Function::iterator FI = F.begin();
431 // First basic block is entry - skip it.
432 BasicBlock *Preheader = &*(++FI);
433 BasicBlock *Header = &*(++FI);
434 assert(Header->getName() == "for.outer");
435 Loop *L = LI.getLoopFor(Header);
436 EXPECT_NE(L, nullptr);
437 EXPECT_EQ(Header, L->getHeader());
438 EXPECT_EQ(Preheader, L->getLoopPreheader());
439
440 ValueToValueMapTy VMap;
441 SmallVector<BasicBlock *, 4> ClonedLoopBlocks;
442 Loop *NewLoop = cloneLoopWithPreheader(Preheader, Preheader, L, VMap,
443 "", &LI, &DT, ClonedLoopBlocks);
444 EXPECT_NE(NewLoop, nullptr);
445 EXPECT_EQ(NewLoop->getSubLoops().size(), 1u);
446 Loop::block_iterator BI = NewLoop->block_begin();
447 EXPECT_TRUE((*BI)->getName().starts_with("for.outer"));
448 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner.preheader"));
449 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner"));
450 EXPECT_TRUE((*(++BI))->getName().starts_with("for.inner.exit"));
451 EXPECT_TRUE((*(++BI))->getName().starts_with("for.outer.latch"));
452 });
453 }
454
455 class CloneFunc : public ::testing::Test {
456 protected:
457 void SetUp() override {
458 SetupModule();
459 CreateOldFunc();
460 CreateNewFunc();
461 SetupFinder();
462 }
463
464 void TearDown() override { delete Finder; }
465
466 void SetupModule() {
467 M = new Module("", C);
468 }
469
470 void CreateOldFunc() {
471 FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false);
472 OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M);
473 CreateOldFunctionBodyAndDI();
474 }
475
476 void CreateOldFunctionBodyAndDI() {
477 DIBuilder DBuilder(*M);
478 IRBuilder<> IBuilder(C);
479
480 // Function DI
481 auto *File = DBuilder.createFile("filename.c", "/file/dir/");
482 DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray({});
483 DISubroutineType *FuncType =
484 DBuilder.createSubroutineType(ParamTypes);
485 auto *CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
486 DBuilder.createFile("filename.c",
487 "/file/dir"),
488 "CloneFunc", false, "", 0);
489
490 auto *Subprogram = DBuilder.createFunction(
491 CU, "f", "f", File, 4, FuncType, 3, DINode::FlagZero,
492 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
493 OldFunc->setSubprogram(Subprogram);
494
495 // Function body
496 BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc);
497 IBuilder.SetInsertPoint(Entry);
498 DebugLoc Loc = DILocation::get(Subprogram->getContext(), 3, 2, Subprogram);
499 IBuilder.SetCurrentDebugLocation(Loc);
500 AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C));
501 IBuilder.SetCurrentDebugLocation(
502 DILocation::get(Subprogram->getContext(), 4, 2, Subprogram));
503 Value* AllocaContent = IBuilder.getInt32(1);
504 Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca);
505 IBuilder.SetCurrentDebugLocation(
506 DILocation::get(Subprogram->getContext(), 5, 2, Subprogram));
507
508 // Create a local variable around the alloca
509 auto *IntType = DBuilder.createBasicType("int", 32, dwarf::DW_ATE_signed);
510 auto *E = DBuilder.createExpression();
511 auto *Variable =
512 DBuilder.createAutoVariable(Subprogram, "x", File, 5, IntType, true);
513 auto *DL = DILocation::get(Subprogram->getContext(), 5, 0, Subprogram);
514 DBuilder.insertDeclare(Alloca, Variable, E, DL, Store->getIterator());
515 DBuilder.insertDbgValueIntrinsic(AllocaContent, Variable, E, DL, Entry);
516 // Also create an inlined variable.
517 // Create a distinct struct type that we should not duplicate during
518 // cloning).
519 auto *StructType = DICompositeType::getDistinct(
520 C, dwarf::DW_TAG_structure_type, "some_struct", nullptr, 0, nullptr,
521 nullptr, 32, 32, 0, DINode::FlagZero, nullptr, 0, std::nullopt, nullptr,
522 nullptr);
523 auto *InlinedSP = DBuilder.createFunction(
524 CU, "inlined", "inlined", File, 8, FuncType, 9, DINode::FlagZero,
525 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
526 auto *InlinedVar =
527 DBuilder.createAutoVariable(InlinedSP, "inlined", File, 5, StructType, true);
528 auto *Scope = DBuilder.createLexicalBlock(
529 DBuilder.createLexicalBlockFile(InlinedSP, File), File, 1, 1);
530 auto InlinedDL = DILocation::get(
531 Subprogram->getContext(), 9, 4, Scope,
532 DILocation::get(Subprogram->getContext(), 5, 2, Subprogram));
533 IBuilder.SetCurrentDebugLocation(InlinedDL);
534 DBuilder.insertDeclare(Alloca, InlinedVar, E, InlinedDL,
535 Store->getIterator());
536 IBuilder.CreateStore(IBuilder.getInt32(2), Alloca);
537 // Finalize the debug info.
538 DBuilder.finalize();
539 IBuilder.CreateRetVoid();
540
541 // Create another, empty, compile unit.
542 DIBuilder DBuilder2(*M);
543 DBuilder2.createCompileUnit(dwarf::DW_LANG_C99,
544 DBuilder.createFile("extra.c", "/file/dir"),
545 "CloneFunc", false, "", 0);
546 DBuilder2.finalize();
547 }
548
549 void CreateNewFunc() {
550 ValueToValueMapTy VMap;
551 NewFunc = CloneFunction(OldFunc, VMap, nullptr);
552 }
553
554 void SetupFinder() {
555 Finder = new DebugInfoFinder();
556 Finder->processModule(*M);
557 }
558
559 LLVMContext C;
560 Function* OldFunc;
561 Function* NewFunc;
562 Module* M;
563 DebugInfoFinder* Finder;
564 };
565
566 // Test that a new, distinct function was created.
567 TEST_F(CloneFunc, NewFunctionCreated) {
568 EXPECT_NE(OldFunc, NewFunc);
569 }
570
571 // Test that a new subprogram entry was added and is pointing to the new
572 // function, while the original subprogram still points to the old one.
573 TEST_F(CloneFunc, Subprogram) {
574 EXPECT_FALSE(verifyModule(*M, &errs()));
575 EXPECT_EQ(3U, Finder->subprogram_count());
576 EXPECT_NE(NewFunc->getSubprogram(), OldFunc->getSubprogram());
577 }
578
579 // Test that instructions in the old function still belong to it in the
580 // metadata, while instruction in the new function belong to the new one.
581 TEST_F(CloneFunc, InstructionOwnership) {
582 EXPECT_FALSE(verifyModule(*M));
583
584 inst_iterator OldIter = inst_begin(OldFunc);
585 inst_iterator OldEnd = inst_end(OldFunc);
586 inst_iterator NewIter = inst_begin(NewFunc);
587 inst_iterator NewEnd = inst_end(NewFunc);
588 while (OldIter != OldEnd && NewIter != NewEnd) {
589 Instruction& OldI = *OldIter;
590 Instruction& NewI = *NewIter;
591 EXPECT_NE(&OldI, &NewI);
592
593 EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata());
594 if (OldI.hasMetadata()) {
595 const DebugLoc& OldDL = OldI.getDebugLoc();
596 const DebugLoc& NewDL = NewI.getDebugLoc();
597
598 // Verify that the debug location data is the same
599 EXPECT_EQ(OldDL.getLine(), NewDL.getLine());
600 EXPECT_EQ(OldDL.getCol(), NewDL.getCol());
601
602 // But that they belong to different functions
603 auto *OldSubprogram = cast<DISubprogram>(OldDL.getInlinedAtScope());
604 auto *NewSubprogram = cast<DISubprogram>(NewDL.getInlinedAtScope());
605 EXPECT_EQ(OldFunc->getSubprogram(), OldSubprogram);
606 EXPECT_EQ(NewFunc->getSubprogram(), NewSubprogram);
607 }
608
609 ++OldIter;
610 ++NewIter;
611 }
612 EXPECT_EQ(OldEnd, OldIter);
613 EXPECT_EQ(NewEnd, NewIter);
614 }
615
616 // Test that the arguments for debug intrinsics in the new function were
617 // properly cloned
618 TEST_F(CloneFunc, DebugIntrinsics) {
619 EXPECT_FALSE(verifyModule(*M));
620
621 inst_iterator OldIter = inst_begin(OldFunc);
622 inst_iterator OldEnd = inst_end(OldFunc);
623 inst_iterator NewIter = inst_begin(NewFunc);
624 inst_iterator NewEnd = inst_end(NewFunc);
625 while (OldIter != OldEnd && NewIter != NewEnd) {
626 Instruction& OldI = *OldIter;
627 Instruction& NewI = *NewIter;
628 if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) {
629 DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI);
630 EXPECT_TRUE(NewIntrin);
631
632 // Old address must belong to the old function
633 EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())->
634 getParent()->getParent());
635 // New address must belong to the new function
636 EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())->
637 getParent()->getParent());
638
639 if (OldIntrin->getDebugLoc()->getInlinedAt()) {
640 // Inlined variable should refer to the same DILocalVariable as in the
641 // Old Function
642 EXPECT_EQ(OldIntrin->getVariable(), NewIntrin->getVariable());
643 } else {
644 // Old variable must belong to the old function.
645 EXPECT_EQ(OldFunc->getSubprogram(),
646 cast<DISubprogram>(OldIntrin->getVariable()->getScope()));
647 // New variable must belong to the new function.
648 EXPECT_EQ(NewFunc->getSubprogram(),
649 cast<DISubprogram>(NewIntrin->getVariable()->getScope()));
650 }
651 } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) {
652 DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI);
653 EXPECT_TRUE(NewIntrin);
654
655 if (!OldIntrin->getDebugLoc()->getInlinedAt()) {
656 // Old variable must belong to the old function.
657 EXPECT_EQ(OldFunc->getSubprogram(),
658 cast<DISubprogram>(OldIntrin->getVariable()->getScope()));
659 // New variable must belong to the new function.
660 EXPECT_EQ(NewFunc->getSubprogram(),
661 cast<DISubprogram>(NewIntrin->getVariable()->getScope()));
662 }
663 }
664
665 ++OldIter;
666 ++NewIter;
667 }
668 }
669
670 static int GetDICompileUnitCount(const Module& M) {
671 if (const auto* LLVM_DBG_CU = M.getNamedMetadata("llvm.dbg.cu")) {
672 return LLVM_DBG_CU->getNumOperands();
673 }
674 return 0;
675 }
676
677 static bool haveCompileUnitsInCommon(const Module &LHS, const Module &RHS) {
678 const NamedMDNode *LHSCUs = LHS.getNamedMetadata("llvm.dbg.cu");
679 if (!LHSCUs)
680 return false;
681
682 const NamedMDNode *RHSCUs = RHS.getNamedMetadata("llvm.dbg.cu");
683 if (!RHSCUs)
684 return false;
685
686 SmallPtrSet<const MDNode *, 8> Found;
687 for (int I = 0, E = LHSCUs->getNumOperands(); I != E; ++I)
688 if (const MDNode *N = LHSCUs->getOperand(I))
689 Found.insert(N);
690
691 for (int I = 0, E = RHSCUs->getNumOperands(); I != E; ++I)
692 if (const MDNode *N = RHSCUs->getOperand(I))
693 if (Found.count(N))
694 return true;
695
696 return false;
697 }
698
699 TEST(CloneFunction, CloneEmptyFunction) {
700 StringRef ImplAssembly = R"(
701 define void @foo() {
702 ret void
703 }
704 declare void @bar()
705 )";
706
707 LLVMContext Context;
708 SMDiagnostic Error;
709
710 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
711 EXPECT_TRUE(ImplModule != nullptr);
712 auto *ImplFunction = ImplModule->getFunction("foo");
713 EXPECT_TRUE(ImplFunction != nullptr);
714 auto *DeclFunction = ImplModule->getFunction("bar");
715 EXPECT_TRUE(DeclFunction != nullptr);
716
717 ValueToValueMapTy VMap;
718 SmallVector<ReturnInst *, 8> Returns;
719 ClonedCodeInfo CCI;
720 CloneFunctionInto(ImplFunction, DeclFunction, VMap,
721 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);
722
723 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
724 EXPECT_FALSE(CCI.ContainsCalls);
725 EXPECT_FALSE(CCI.ContainsDynamicAllocas);
726 }
727
728 TEST(CloneFunction, CloneFunctionWithInalloca) {
729 StringRef ImplAssembly = R"(
730 declare void @a(i32* inalloca(i32))
731 define void @foo() {
732 %a = alloca inalloca i32
733 call void @a(i32* inalloca(i32) %a)
734 ret void
735 }
736 declare void @bar()
737 )";
738
739 LLVMContext Context;
740 SMDiagnostic Error;
741
742 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
743 EXPECT_TRUE(ImplModule != nullptr);
744 auto *ImplFunction = ImplModule->getFunction("foo");
745 EXPECT_TRUE(ImplFunction != nullptr);
746 auto *DeclFunction = ImplModule->getFunction("bar");
747 EXPECT_TRUE(DeclFunction != nullptr);
748
749 ValueToValueMapTy VMap;
750 SmallVector<ReturnInst *, 8> Returns;
751 ClonedCodeInfo CCI;
752 CloneFunctionInto(DeclFunction, ImplFunction, VMap,
753 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);
754
755 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
756 EXPECT_TRUE(CCI.ContainsCalls);
757 EXPECT_TRUE(CCI.ContainsDynamicAllocas);
758 }
759
760 TEST(CloneFunction, CloneFunctionWithSubprograms) {
761 // Tests that the debug info is duplicated correctly when a DISubprogram
762 // happens to be one of the operands of the DISubprogram that is being cloned.
763 // In general, operands of "test" that are distinct should be duplicated,
764 // but in this case "my_operator" should not be duplicated. If it is
765 // duplicated, the metadata in the llvm.dbg.declare could end up with
766 // different duplicates.
767 StringRef ImplAssembly = R"(
768 declare void @llvm.dbg.declare(metadata, metadata, metadata)
769
770 define void @test() !dbg !5 {
771 call void @llvm.dbg.declare(metadata i8* undef, metadata !4, metadata !DIExpression()), !dbg !6
772 ret void
773 }
774
775 declare void @cloned()
776
777 !llvm.dbg.cu = !{!0}
778 !llvm.module.flags = !{!2}
779 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)
780 !1 = !DIFile(filename: "test.cpp", directory: "")
781 !2 = !{i32 1, !"Debug Info Version", i32 3}
782 !3 = distinct !DISubprogram(name: "my_operator", scope: !1, unit: !0, retainedNodes: !{!4})
783 !4 = !DILocalVariable(name: "awaitables", scope: !3)
784 !5 = distinct !DISubprogram(name: "test", scope: !3, unit: !0)
785 !6 = !DILocation(line: 55, column: 15, scope: !3, inlinedAt: !7)
786 !7 = distinct !DILocation(line: 73, column: 14, scope: !5)
787 )";
788
789 LLVMContext Context;
790 SMDiagnostic Error;
791
792 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
793 EXPECT_TRUE(ImplModule != nullptr);
794 auto *OldFunc = ImplModule->getFunction("test");
795 EXPECT_TRUE(OldFunc != nullptr);
796 auto *NewFunc = ImplModule->getFunction("cloned");
797 EXPECT_TRUE(NewFunc != nullptr);
798
799 ValueToValueMapTy VMap;
800 SmallVector<ReturnInst *, 8> Returns;
801 ClonedCodeInfo CCI;
802 CloneFunctionInto(NewFunc, OldFunc, VMap,
803 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);
804
805 // This fails if the scopes in the llvm.dbg.declare variable and location
806 // aren't the same.
807 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
808 }
809
810 TEST(CloneFunction, CloneFunctionWithInlinedSubprograms) {
811 StringRef ImplAssembly = R"(
812 declare void @llvm.dbg.declare(metadata, metadata, metadata)
813
814 define void @test() !dbg !3 {
815 call void @llvm.dbg.declare(metadata i8* undef, metadata !5, metadata !DIExpression()), !dbg !7
816 ret void
817 }
818
819 declare void @cloned()
820
821 !llvm.dbg.cu = !{!0}
822 !llvm.module.flags = !{!2}
823 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)
824 !1 = !DIFile(filename: "test.cpp", directory: "")
825 !2 = !{i32 1, !"Debug Info Version", i32 3}
826 !3 = distinct !DISubprogram(name: "test", scope: !0, unit: !0)
827 !4 = distinct !DISubprogram(name: "inlined", scope: !0, unit: !0, retainedNodes: !{!5})
828 !5 = !DILocalVariable(name: "awaitables", scope: !4)
829 !6 = distinct !DILexicalBlock(scope: !4, file: !1, line: 1)
830 !7 = !DILocation(line: 1, scope: !6, inlinedAt: !8)
831 !8 = !DILocation(line: 10, scope: !3)
832 )";
833
834 LLVMContext Context;
835 SMDiagnostic Error;
836
837 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
838 EXPECT_TRUE(ImplModule != nullptr);
839 auto *Func = ImplModule->getFunction("test");
840 EXPECT_TRUE(Func != nullptr);
841 auto *ClonedFunc = ImplModule->getFunction("cloned");
842 EXPECT_TRUE(ClonedFunc != nullptr);
843
844 ValueToValueMapTy VMap;
845 SmallVector<ReturnInst *, 8> Returns;
846 ClonedCodeInfo CCI;
847 CloneFunctionInto(ClonedFunc, Func, VMap,
848 CloneFunctionChangeType::GlobalChanges, Returns, "", &CCI);
849
850 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
851
852 // Check that DILexicalBlock of inlined function was not cloned.
853 auto DbgDeclareI = Func->begin()->begin()->getDbgRecordRange().begin();
854 auto ClonedDbgDeclareI =
855 ClonedFunc->begin()->begin()->getDbgRecordRange().begin();
856 const DebugLoc &DbgLoc = DbgDeclareI->getDebugLoc();
857 const DebugLoc &ClonedDbgLoc = ClonedDbgDeclareI->getDebugLoc();
858 EXPECT_NE(DbgLoc.get(), ClonedDbgLoc.get());
859 EXPECT_EQ(cast<DILexicalBlock>(DbgLoc.getScope()),
860 cast<DILexicalBlock>(ClonedDbgLoc.getScope()));
861 }
862
863 TEST(CloneFunction, CloneFunctionToDifferentModule) {
864 StringRef ImplAssembly = R"(
865 define void @foo() {
866 ret void, !dbg !5
867 }
868
869 !llvm.module.flags = !{!0}
870 !llvm.dbg.cu = !{!2, !6}
871 !0 = !{i32 1, !"Debug Info Version", i32 3}
872 !1 = distinct !DISubprogram(unit: !2)
873 !2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)
874 !3 = !DIFile(filename: "foo.c", directory: "/tmp")
875 !4 = distinct !DISubprogram(unit: !2)
876 !5 = !DILocation(line: 4, scope: !1)
877 !6 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)
878 )";
879 StringRef DeclAssembly = R"(
880 declare void @foo()
881 )";
882
883 LLVMContext Context;
884 SMDiagnostic Error;
885
886 auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
887 EXPECT_TRUE(ImplModule != nullptr);
888 // DICompileUnits: !2, !6. Only !2 is reachable from @foo().
889 EXPECT_TRUE(GetDICompileUnitCount(*ImplModule) == 2);
890 auto* ImplFunction = ImplModule->getFunction("foo");
891 EXPECT_TRUE(ImplFunction != nullptr);
892
893 auto DeclModule = parseAssemblyString(DeclAssembly, Error, Context);
894 EXPECT_TRUE(DeclModule != nullptr);
895 // No DICompileUnits defined here.
896 EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 0);
897 auto* DeclFunction = DeclModule->getFunction("foo");
898 EXPECT_TRUE(DeclFunction != nullptr);
899
900 ValueToValueMapTy VMap;
901 VMap[ImplFunction] = DeclFunction;
902 // No args to map
903 SmallVector<ReturnInst*, 8> Returns;
904 CloneFunctionInto(DeclFunction, ImplFunction, VMap,
905 CloneFunctionChangeType::DifferentModule, Returns);
906
907 EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
908 EXPECT_FALSE(verifyModule(*DeclModule, &errs()));
909 // DICompileUnit !2 shall be cloned into DeclModule.
910 EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 1);
911 EXPECT_FALSE(haveCompileUnitsInCommon(*ImplModule, *DeclModule));
912 }
913
914 class CloneModule : public ::testing::Test {
915 protected:
916 void SetUp() override {
917 SetupModule();
918 CreateOldModule();
919 CreateNewModule();
920 }
921
922 void SetupModule() { OldM = new Module("", C); }
923
924 void CreateOldModule() {
925 auto *CD = OldM->getOrInsertComdat("comdat");
926 CD->setSelectionKind(Comdat::ExactMatch);
927
928 auto GV = new GlobalVariable(
929 *OldM, Type::getInt32Ty(C), false, GlobalValue::ExternalLinkage,
930 ConstantInt::get(Type::getInt32Ty(C), 1), "gv");
931 GV->addMetadata(LLVMContext::MD_type, *MDNode::get(C, {}));
932 GV->setComdat(CD);
933
934 // Add ifuncs
935 {
936 const unsigned AddrSpace = 123;
937 auto *FuncPtrTy = PointerType::get(C, AddrSpace);
938 auto *FuncTy = FunctionType::get(FuncPtrTy, false);
939
940 auto *ResolverF = Function::Create(FuncTy, GlobalValue::PrivateLinkage,
941 AddrSpace, "resolver", OldM);
942 BasicBlock *ResolverBody = BasicBlock::Create(C, "", ResolverF);
943 ReturnInst::Create(C, ConstantPointerNull::get(FuncPtrTy), ResolverBody);
944
945 GlobalIFunc *GI = GlobalIFunc::create(FuncTy, AddrSpace,
946 GlobalValue::LinkOnceODRLinkage,
947 "an_ifunc", ResolverF, OldM);
948 GI->setVisibility(GlobalValue::ProtectedVisibility);
949 }
950
951 {
952 // Add an empty compile unit first that isn't otherwise referenced, to
953 // confirm that compile units get cloned in the correct order.
954 DIBuilder EmptyBuilder(*OldM);
955 auto *File = EmptyBuilder.createFile("empty.c", "/file/dir/");
956 (void)EmptyBuilder.createCompileUnit(dwarf::DW_LANG_C99, File,
957 "EmptyUnit", false, "", 0);
958 EmptyBuilder.finalize();
959 }
960
961 DIBuilder DBuilder(*OldM);
962 IRBuilder<> IBuilder(C);
963
964 auto *FuncType = FunctionType::get(Type::getVoidTy(C), false);
965 auto *PersFn = Function::Create(FuncType, GlobalValue::ExternalLinkage,
966 "persfn", OldM);
967 auto *F =
968 Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", OldM);
969 F->setPersonalityFn(PersFn);
970 F->setComdat(CD);
971
972 // Create debug info
973 auto *File = DBuilder.createFile("filename.c", "/file/dir/");
974 DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray({});
975 DISubroutineType *DFuncType = DBuilder.createSubroutineType(ParamTypes);
976 auto *CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
977 DBuilder.createFile("filename.c",
978 "/file/dir"),
979 "CloneModule", false, "", 0);
980 // Function DI
981 auto *Subprogram = DBuilder.createFunction(
982 CU, "f", "f", File, 4, DFuncType, 3, DINode::FlagZero,
983 DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
984 F->setSubprogram(Subprogram);
985
986 // Create and assign DIGlobalVariableExpression to gv
987 auto GVExpression = DBuilder.createGlobalVariableExpression(
988 Subprogram, "gv", "gv", File, 1, DBuilder.createNullPtrType(), false);
989 GV->addDebugInfo(GVExpression);
990
991 // DIGlobalVariableExpression not attached to any global variable
992 auto Expr = DBuilder.createExpression(
993 ArrayRef<uint64_t>{dwarf::DW_OP_constu, 42U, dwarf::DW_OP_stack_value});
994
995 DBuilder.createGlobalVariableExpression(
996 Subprogram, "unattached", "unattached", File, 1,
997 DBuilder.createNullPtrType(), false, true, Expr);
998
999 auto *Entry = BasicBlock::Create(C, "", F);
1000 IBuilder.SetInsertPoint(Entry);
1001 IBuilder.CreateRetVoid();
1002
1003 auto *G =
1004 Function::Create(FuncType, GlobalValue::ExternalLinkage, "g", OldM);
1005 G->addMetadata(LLVMContext::MD_type, *MDNode::get(C, {}));
1006
1007 auto *NonEntryBlock = BasicBlock::Create(C, "", F);
1008 IBuilder.SetInsertPoint(NonEntryBlock);
1009 IBuilder.CreateRetVoid();
1010
1011 // Create a global that contains the block address in its initializer.
1012 auto *BlockAddress = BlockAddress::get(NonEntryBlock);
1013 new GlobalVariable(*OldM, BlockAddress->getType(), /*isConstant=*/true,
1014 GlobalVariable::ExternalLinkage, BlockAddress,
1015 "blockaddr");
1016
1017 // Finalize the debug info
1018 DBuilder.finalize();
1019 }
1020
1021 void CreateNewModule() { NewM = llvm::CloneModule(*OldM).release(); }
1022
1023 LLVMContext C;
1024 Module *OldM;
1025 Module *NewM;
1026 };
1027
1028 TEST_F(CloneModule, Verify) {
1029 // Confirm the old module is (still) valid.
1030 EXPECT_FALSE(verifyModule(*OldM, &errs()));
1031
1032 // Check the new module.
1033 EXPECT_FALSE(verifyModule(*NewM, &errs()));
1034 }
1035
1036 TEST_F(CloneModule, OldModuleUnchanged) {
1037 DebugInfoFinder Finder;
1038 Finder.processModule(*OldM);
1039 EXPECT_EQ(1U, Finder.subprogram_count());
1040 }
1041
1042 TEST_F(CloneModule, Subprogram) {
1043 Function *NewF = NewM->getFunction("f");
1044 DISubprogram *SP = NewF->getSubprogram();
1045 EXPECT_TRUE(SP != nullptr);
1046 EXPECT_EQ(SP->getName(), "f");
1047 EXPECT_EQ(SP->getFile()->getFilename(), "filename.c");
1048 EXPECT_EQ(SP->getLine(), (unsigned)4);
1049 }
1050
1051 TEST_F(CloneModule, FunctionDeclarationMetadata) {
1052 Function *NewF = NewM->getFunction("g");
1053 EXPECT_NE(nullptr, NewF->getMetadata(LLVMContext::MD_type));
1054 }
1055
1056 TEST_F(CloneModule, GlobalMetadata) {
1057 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
1058 EXPECT_NE(nullptr, NewGV->getMetadata(LLVMContext::MD_type));
1059 }
1060
1061 TEST_F(CloneModule, GlobalDebugInfo) {
1062 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
1063 EXPECT_TRUE(NewGV != nullptr);
1064
1065 // Find debug info expression assigned to global
1066 SmallVector<DIGlobalVariableExpression *, 1> GVs;
1067 NewGV->getDebugInfo(GVs);
1068 EXPECT_EQ(GVs.size(), 1U);
1069
1070 DIGlobalVariableExpression *GVExpr = GVs[0];
1071 DIGlobalVariable *GV = GVExpr->getVariable();
1072 EXPECT_TRUE(GV != nullptr);
1073
1074 EXPECT_EQ(GV->getName(), "gv");
1075 EXPECT_EQ(GV->getLine(), 1U);
1076
1077 // Assert that the scope of the debug info attached to
1078 // global variable matches the cloned function.
1079 DISubprogram *SP = NewM->getFunction("f")->getSubprogram();
1080 EXPECT_TRUE(SP != nullptr);
1081 EXPECT_EQ(GV->getScope(), SP);
1082 }
1083
1084 TEST_F(CloneModule, CompileUnit) {
1085 // Find DICompileUnit listed in llvm.dbg.cu
1086 auto *NMD = NewM->getNamedMetadata("llvm.dbg.cu");
1087 EXPECT_TRUE(NMD != nullptr);
1088 EXPECT_EQ(NMD->getNumOperands(), 2U);
1089 EXPECT_FALSE(haveCompileUnitsInCommon(*OldM, *NewM));
1090
1091 // Check that the empty CU is first, even though it's not referenced except
1092 // from named metadata.
1093 DICompileUnit *EmptyCU = dyn_cast<llvm::DICompileUnit>(NMD->getOperand(0));
1094 EXPECT_TRUE(EmptyCU != nullptr);
1095 EXPECT_EQ("EmptyUnit", EmptyCU->getProducer());
1096
1097 // Get the interesting CU.
1098 DICompileUnit *CU = dyn_cast<llvm::DICompileUnit>(NMD->getOperand(1));
1099 EXPECT_TRUE(CU != nullptr);
1100 EXPECT_EQ("CloneModule", CU->getProducer());
1101
1102 // Assert this CU is consistent with the cloned function debug info
1103 DISubprogram *SP = NewM->getFunction("f")->getSubprogram();
1104 EXPECT_TRUE(SP != nullptr);
1105 EXPECT_EQ(SP->getUnit(), CU);
1106
1107 // Check globals listed in CU have the correct scope
1108 DIGlobalVariableExpressionArray GlobalArray = CU->getGlobalVariables();
1109 EXPECT_EQ(GlobalArray.size(), 2U);
1110 for (DIGlobalVariableExpression *GVExpr : GlobalArray) {
1111 DIGlobalVariable *GV = GVExpr->getVariable();
1112 EXPECT_EQ(GV->getScope(), SP);
1113 }
1114 }
1115
1116 TEST_F(CloneModule, Comdat) {
1117 GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
1118 auto *CD = NewGV->getComdat();
1119 ASSERT_NE(nullptr, CD);
1120 EXPECT_EQ("comdat", CD->getName());
1121 EXPECT_EQ(Comdat::ExactMatch, CD->getSelectionKind());
1122
1123 Function *NewF = NewM->getFunction("f");
1124 EXPECT_EQ(CD, NewF->getComdat());
1125 }
1126
1127 TEST_F(CloneModule, IFunc) {
1128 ASSERT_EQ(1u, NewM->ifunc_size());
1129
1130 const GlobalIFunc &IFunc = *NewM->ifunc_begin();
1131 EXPECT_EQ("an_ifunc", IFunc.getName());
1132 EXPECT_EQ(GlobalValue::LinkOnceODRLinkage, IFunc.getLinkage());
1133 EXPECT_EQ(GlobalValue::ProtectedVisibility, IFunc.getVisibility());
1134 EXPECT_EQ(123u, IFunc.getAddressSpace());
1135
1136 const Function *Resolver = IFunc.getResolverFunction();
1137 ASSERT_NE(nullptr, Resolver);
1138 EXPECT_EQ("resolver", Resolver->getName());
1139 EXPECT_EQ(GlobalValue::PrivateLinkage, Resolver->getLinkage());
1140 }
1141
1142 TEST_F(CloneModule, CloneDbgLabel) {
1143 LLVMContext Context;
1144
1145 std::unique_ptr<Module> M = parseIR(Context,
1146 R"M(
1147 define void @noop(ptr nocapture noundef writeonly align 4 %dst) local_unnamed_addr !dbg !3 {
1148 entry:
1149 %call = tail call spir_func i64 @foo(i32 noundef 0)
1150 #dbg_label(!11, !12)
1151 store i64 %call, ptr %dst, align 4
1152 ret void
1153 }
1154
1155 declare i64 @foo(i32 noundef) local_unnamed_addr
1156
1157 !llvm.dbg.cu = !{!0}
1158 !llvm.module.flags = !{!2}
1159
1160 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 19.0.0git", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
1161 !1 = !DIFile(filename: "<stdin>", directory: "foo")
1162 !2 = !{i32 2, !"Debug Info Version", i32 3}
1163 !3 = distinct !DISubprogram(name: "noop", scope: !4, file: !4, line: 17, type: !5, scopeLine: 17, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !9)
1164 !4 = !DIFile(filename: "file", directory: "foo")
1165 !5 = !DISubroutineType(types: !6)
1166 !6 = !{null, !7}
1167 !7 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !8, size: 64)
1168 !8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
1169 !9 = !{}
1170 !11 = !DILabel(scope: !3, name: "foo", file: !4, line: 23)
1171 !12 = !DILocation(line: 23, scope: !3)
1172 )M");
1173
1174 ASSERT_FALSE(verifyModule(*M, &errs()));
1175 auto NewM = llvm::CloneModule(*M);
1176 EXPECT_FALSE(verifyModule(*NewM, &errs()));
1177 }
1178
1179 TEST_F(CloneInstruction, cloneKeyInstructions) {
1180 LLVMContext Context;
1181
1182 std::unique_ptr<Module> M = parseIR(Context, R"(
1183 define void @test(ptr align 4 %dst) !dbg !3 {
1184 store i64 1, ptr %dst, align 4, !dbg !6
1185 store i64 2, ptr %dst, align 4, !dbg !7
1186 store i64 3, ptr %dst, align 4, !dbg !8
1187 ret void, !dbg !9
1188 }
1189
1190 !llvm.dbg.cu = !{!0}
1191 !llvm.module.flags = !{!2}
1192 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1)
1193 !1 = !DIFile(filename: "test.cpp", directory: "")
1194 !2 = !{i32 1, !"Debug Info Version", i32 3}
1195 !3 = distinct !DISubprogram(name: "test", scope: !0, unit: !0, keyInstructions: true)
1196 !4 = distinct !DISubprogram(name: "inlined", scope: !0, unit: !0, retainedNodes: !{!5}, keyInstructions: true)
1197 !5 = !DILocalVariable(name: "awaitables", scope: !4)
1198 !6 = !DILocation(line: 1, scope: !4, inlinedAt: !8, atomGroup: 1, atomRank: 1)
1199 !7 = !DILocation(line: 2, scope: !3, atomGroup: 1, atomRank: 1)
1200 !8 = !DILocation(line: 3, scope: !3, atomGroup: 1, atomRank: 1)
1201 !9 = !DILocation(line: 4, scope: !3, atomGroup: 2, atomRank: 1)
1202 )");
1203
1204 ASSERT_FALSE(verifyModule(*M, &errs()));
1205
1206 #ifdef EXPERIMENTAL_KEY_INSTRUCTIONS
1207 #define EXPECT_ATOM(Inst, G) \
1208 EXPECT_TRUE(Inst->getDebugLoc()); \
1209 EXPECT_EQ(Inst->getDebugLoc()->getAtomGroup(), uint64_t(G));
1210 #else
1211 #define EXPECT_ATOM(Inst, G) (void)Inst;
1212 #endif
1213
1214 Function *F = M->getFunction("test");
1215 BasicBlock *BB = &*F->begin();
1216 ASSERT_TRUE(F);
1217 Instruction *Store1 = &*BB->begin();
1218 Instruction *Store2 = Store1->getNextNode();
1219 Instruction *Store3 = Store2->getNextNode();
1220 Instruction *Ret = Store3->getNextNode();
1221
1222 // Test the remapping works as expected outside of cloning.
1223 ValueToValueMapTy VM;
1224 // Store1 and Store2 have the same atomGroup number, but have different
1225 // inlining scopes, so only Store1 should change group.
1226 mapAtomInstance(Store1->getDebugLoc(), VM);
1227 for (Instruction &I : *BB)
1228 RemapSourceAtom(&I, VM);
1229 EXPECT_ATOM(Store1, 3);
1230 EXPECT_ATOM(Store2, 1);
1231 EXPECT_ATOM(Store3, 1);
1232 EXPECT_ATOM(Ret, 2);
1233 VM.clear();
1234
1235 // Store2 and Store3 have the same group number; both should get remapped.
1236 mapAtomInstance(Store2->getDebugLoc(), VM);
1237 for (Instruction &I : *BB)
1238 RemapSourceAtom(&I, VM);
1239 EXPECT_ATOM(Store1, 3);
1240 EXPECT_ATOM(Store2, 4);
1241 EXPECT_ATOM(Store3, 4);
1242 EXPECT_ATOM(Ret, 2);
1243 VM.clear();
1244
1245 // Cloning BB with MapAtoms=false should clone the atom numbers.
1246 BasicBlock *BB2 =
1247 CloneBasicBlock(BB, VM, "", nullptr, nullptr, /*MapAtoms*/ false);
1248 for (Instruction &I : *BB2)
1249 RemapSourceAtom(&I, VM);
1250 Store1 = &*BB2->begin();
1251 Store2 = Store1->getNextNode();
1252 Store3 = Store2->getNextNode();
1253 Ret = Store3->getNextNode();
1254 EXPECT_ATOM(Store1, 3);
1255 EXPECT_ATOM(Store2, 4);
1256 EXPECT_ATOM(Store3, 4);
1257 EXPECT_ATOM(Ret, 2);
1258 VM.clear();
1259 delete BB2;
1260
1261 // Cloning BB with MapAtoms=true should map the atom numbers.
1262 BasicBlock *BB3 =
1263 CloneBasicBlock(BB, VM, "", nullptr, nullptr, /*MapAtoms*/ true);
1264 for (Instruction &I : *BB3)
1265 RemapSourceAtom(&I, VM);
1266 Store1 = &*BB3->begin();
1267 Store2 = Store1->getNextNode();
1268 Store3 = Store2->getNextNode();
1269 Ret = Store3->getNextNode();
1270 EXPECT_ATOM(Store1, 5);
1271 EXPECT_ATOM(Store2, 6);
1272 EXPECT_ATOM(Store3, 6);
1273 EXPECT_ATOM(Ret, 7);
1274 VM.clear();
1275 delete BB3;
1276 #undef EXPECT_ATOM
1277 }
1278
1279 // Checks that block addresses in global initializers are properly cloned.
1280 TEST_F(CloneModule, GlobalWithBlockAddressesInitializer) {
1281 auto *OriginalBa = cast<BlockAddress>(
1282 OldM->getGlobalVariable("blockaddr")->getInitializer());
1283 auto *ClonedBa = cast<BlockAddress>(
1284 NewM->getGlobalVariable("blockaddr")->getInitializer());
1285 ASSERT_NE(OriginalBa->getBasicBlock(), ClonedBa->getBasicBlock());
1286 }
1287
1288 } // namespace