CloningTest.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. #include "llvm/Transforms/Utils/Cloning.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/SmallPtrSet.h"
  11. #include "llvm/Analysis/DomTreeUpdater.h"
  12. #include "llvm/Analysis/LoopInfo.h"
  13. #include "llvm/AsmParser/Parser.h"
  14. #include "llvm/IR/Argument.h"
  15. #include "llvm/IR/Constant.h"
  16. #include "llvm/IR/DIBuilder.h"
  17. #include "llvm/IR/DebugInfo.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/IRBuilder.h"
  20. #include "llvm/IR/InstIterator.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Verifier.h"
  26. #include "gtest/gtest.h"
  27. using namespace llvm;
  28. namespace {
  29. class CloneInstruction : public ::testing::Test {
  30. protected:
  31. void SetUp() override { V = nullptr; }
  32. template <typename T>
  33. T *clone(T *V1) {
  34. Value *V2 = V1->clone();
  35. Orig.insert(V1);
  36. Clones.insert(V2);
  37. return cast<T>(V2);
  38. }
  39. void eraseClones() {
  40. for (Value *V : Clones)
  41. V->deleteValue();
  42. Clones.clear();
  43. }
  44. void TearDown() override {
  45. eraseClones();
  46. for (Value *V : Orig)
  47. V->deleteValue();
  48. Orig.clear();
  49. if (V)
  50. V->deleteValue();
  51. }
  52. SmallPtrSet<Value *, 4> Orig; // Erase on exit
  53. SmallPtrSet<Value *, 4> Clones; // Erase in eraseClones
  54. LLVMContext context;
  55. Value *V;
  56. };
  57. TEST_F(CloneInstruction, OverflowBits) {
  58. V = new Argument(Type::getInt32Ty(context));
  59. BinaryOperator *Add = BinaryOperator::Create(Instruction::Add, V, V);
  60. BinaryOperator *Sub = BinaryOperator::Create(Instruction::Sub, V, V);
  61. BinaryOperator *Mul = BinaryOperator::Create(Instruction::Mul, V, V);
  62. BinaryOperator *AddClone = this->clone(Add);
  63. BinaryOperator *SubClone = this->clone(Sub);
  64. BinaryOperator *MulClone = this->clone(Mul);
  65. EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  66. EXPECT_FALSE(AddClone->hasNoSignedWrap());
  67. EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  68. EXPECT_FALSE(SubClone->hasNoSignedWrap());
  69. EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  70. EXPECT_FALSE(MulClone->hasNoSignedWrap());
  71. eraseClones();
  72. Add->setHasNoUnsignedWrap();
  73. Sub->setHasNoUnsignedWrap();
  74. Mul->setHasNoUnsignedWrap();
  75. AddClone = this->clone(Add);
  76. SubClone = this->clone(Sub);
  77. MulClone = this->clone(Mul);
  78. EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  79. EXPECT_FALSE(AddClone->hasNoSignedWrap());
  80. EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  81. EXPECT_FALSE(SubClone->hasNoSignedWrap());
  82. EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  83. EXPECT_FALSE(MulClone->hasNoSignedWrap());
  84. eraseClones();
  85. Add->setHasNoSignedWrap();
  86. Sub->setHasNoSignedWrap();
  87. Mul->setHasNoSignedWrap();
  88. AddClone = this->clone(Add);
  89. SubClone = this->clone(Sub);
  90. MulClone = this->clone(Mul);
  91. EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  92. EXPECT_TRUE(AddClone->hasNoSignedWrap());
  93. EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  94. EXPECT_TRUE(SubClone->hasNoSignedWrap());
  95. EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  96. EXPECT_TRUE(MulClone->hasNoSignedWrap());
  97. eraseClones();
  98. Add->setHasNoUnsignedWrap(false);
  99. Sub->setHasNoUnsignedWrap(false);
  100. Mul->setHasNoUnsignedWrap(false);
  101. AddClone = this->clone(Add);
  102. SubClone = this->clone(Sub);
  103. MulClone = this->clone(Mul);
  104. EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  105. EXPECT_TRUE(AddClone->hasNoSignedWrap());
  106. EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  107. EXPECT_TRUE(SubClone->hasNoSignedWrap());
  108. EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  109. EXPECT_TRUE(MulClone->hasNoSignedWrap());
  110. }
  111. TEST_F(CloneInstruction, Inbounds) {
  112. V = new Argument(Type::getInt32PtrTy(context));
  113. Constant *Z = Constant::getNullValue(Type::getInt32Ty(context));
  114. std::vector<Value *> ops;
  115. ops.push_back(Z);
  116. GetElementPtrInst *GEP =
  117. GetElementPtrInst::Create(Type::getInt32Ty(context), V, ops);
  118. EXPECT_FALSE(this->clone(GEP)->isInBounds());
  119. GEP->setIsInBounds();
  120. EXPECT_TRUE(this->clone(GEP)->isInBounds());
  121. }
  122. TEST_F(CloneInstruction, Exact) {
  123. V = new Argument(Type::getInt32Ty(context));
  124. BinaryOperator *SDiv = BinaryOperator::Create(Instruction::SDiv, V, V);
  125. EXPECT_FALSE(this->clone(SDiv)->isExact());
  126. SDiv->setIsExact(true);
  127. EXPECT_TRUE(this->clone(SDiv)->isExact());
  128. }
  129. TEST_F(CloneInstruction, Attributes) {
  130. Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  131. FunctionType *FT1 = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
  132. Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  133. BasicBlock *BB = BasicBlock::Create(context, "", F1);
  134. IRBuilder<> Builder(BB);
  135. Builder.CreateRetVoid();
  136. Function *F2 = Function::Create(FT1, Function::ExternalLinkage);
  137. Argument *A = &*F1->arg_begin();
  138. A->addAttr(Attribute::NoCapture);
  139. SmallVector<ReturnInst*, 4> Returns;
  140. ValueToValueMapTy VMap;
  141. VMap[A] = UndefValue::get(A->getType());
  142. CloneFunctionInto(F2, F1, VMap, false, Returns);
  143. EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr());
  144. delete F1;
  145. delete F2;
  146. }
  147. TEST_F(CloneInstruction, CallingConvention) {
  148. Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  149. FunctionType *FT1 = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
  150. Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  151. F1->setCallingConv(CallingConv::Cold);
  152. BasicBlock *BB = BasicBlock::Create(context, "", F1);
  153. IRBuilder<> Builder(BB);
  154. Builder.CreateRetVoid();
  155. Function *F2 = Function::Create(FT1, Function::ExternalLinkage);
  156. SmallVector<ReturnInst*, 4> Returns;
  157. ValueToValueMapTy VMap;
  158. VMap[&*F1->arg_begin()] = &*F2->arg_begin();
  159. CloneFunctionInto(F2, F1, VMap, false, Returns);
  160. EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());
  161. delete F1;
  162. delete F2;
  163. }
  164. TEST_F(CloneInstruction, DuplicateInstructionsToSplit) {
  165. Type *ArgTy1[] = {Type::getInt32PtrTy(context)};
  166. FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
  167. V = new Argument(Type::getInt32Ty(context));
  168. Function *F = Function::Create(FT, Function::ExternalLinkage);
  169. BasicBlock *BB1 = BasicBlock::Create(context, "", F);
  170. IRBuilder<> Builder1(BB1);
  171. BasicBlock *BB2 = BasicBlock::Create(context, "", F);
  172. IRBuilder<> Builder2(BB2);
  173. Builder1.CreateBr(BB2);
  174. Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
  175. Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
  176. Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
  177. Builder2.CreateRetVoid();
  178. // Dummy DTU.
  179. ValueToValueMapTy Mapping;
  180. DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
  181. auto Split =
  182. DuplicateInstructionsInSplitBetween(BB2, BB1, SubInst, Mapping, DTU);
  183. EXPECT_TRUE(Split);
  184. EXPECT_EQ(Mapping.size(), 2u);
  185. EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
  186. EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
  187. auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
  188. EXPECT_TRUE(AddSplit);
  189. EXPECT_EQ(AddSplit->getOperand(0), V);
  190. EXPECT_EQ(AddSplit->getOperand(1), V);
  191. EXPECT_EQ(AddSplit->getParent(), Split);
  192. auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
  193. EXPECT_TRUE(MulSplit);
  194. EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
  195. EXPECT_EQ(MulSplit->getOperand(1), V);
  196. EXPECT_EQ(MulSplit->getParent(), Split);
  197. EXPECT_EQ(AddSplit->getNextNode(), MulSplit);
  198. EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());
  199. delete F;
  200. }
  201. TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq1) {
  202. Type *ArgTy1[] = {Type::getInt32PtrTy(context)};
  203. FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
  204. V = new Argument(Type::getInt32Ty(context));
  205. Function *F = Function::Create(FT, Function::ExternalLinkage);
  206. BasicBlock *BB1 = BasicBlock::Create(context, "", F);
  207. IRBuilder<> Builder1(BB1);
  208. BasicBlock *BB2 = BasicBlock::Create(context, "", F);
  209. IRBuilder<> Builder2(BB2);
  210. Builder1.CreateBr(BB2);
  211. Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
  212. Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
  213. Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
  214. Builder2.CreateBr(BB2);
  215. // Dummy DTU.
  216. DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
  217. ValueToValueMapTy Mapping;
  218. auto Split = DuplicateInstructionsInSplitBetween(
  219. BB2, BB2, BB2->getTerminator(), Mapping, DTU);
  220. EXPECT_TRUE(Split);
  221. EXPECT_EQ(Mapping.size(), 3u);
  222. EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
  223. EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
  224. EXPECT_TRUE(Mapping.find(SubInst) != Mapping.end());
  225. auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
  226. EXPECT_TRUE(AddSplit);
  227. EXPECT_EQ(AddSplit->getOperand(0), V);
  228. EXPECT_EQ(AddSplit->getOperand(1), V);
  229. EXPECT_EQ(AddSplit->getParent(), Split);
  230. auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
  231. EXPECT_TRUE(MulSplit);
  232. EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
  233. EXPECT_EQ(MulSplit->getOperand(1), V);
  234. EXPECT_EQ(MulSplit->getParent(), Split);
  235. auto SubSplit = dyn_cast<Instruction>(Mapping[SubInst]);
  236. EXPECT_EQ(MulSplit->getNextNode(), SubSplit);
  237. EXPECT_EQ(SubSplit->getNextNode(), Split->getTerminator());
  238. EXPECT_EQ(Split->getSingleSuccessor(), BB2);
  239. EXPECT_EQ(BB2->getSingleSuccessor(), Split);
  240. delete F;
  241. }
  242. TEST_F(CloneInstruction, DuplicateInstructionsToSplitBlocksEq2) {
  243. Type *ArgTy1[] = {Type::getInt32PtrTy(context)};
  244. FunctionType *FT = FunctionType::get(Type::getVoidTy(context), ArgTy1, false);
  245. V = new Argument(Type::getInt32Ty(context));
  246. Function *F = Function::Create(FT, Function::ExternalLinkage);
  247. BasicBlock *BB1 = BasicBlock::Create(context, "", F);
  248. IRBuilder<> Builder1(BB1);
  249. BasicBlock *BB2 = BasicBlock::Create(context, "", F);
  250. IRBuilder<> Builder2(BB2);
  251. Builder1.CreateBr(BB2);
  252. Instruction *AddInst = cast<Instruction>(Builder2.CreateAdd(V, V));
  253. Instruction *MulInst = cast<Instruction>(Builder2.CreateMul(AddInst, V));
  254. Instruction *SubInst = cast<Instruction>(Builder2.CreateSub(MulInst, V));
  255. Builder2.CreateBr(BB2);
  256. // Dummy DTU.
  257. DomTreeUpdater DTU(DomTreeUpdater::UpdateStrategy::Lazy);
  258. ValueToValueMapTy Mapping;
  259. auto Split =
  260. DuplicateInstructionsInSplitBetween(BB2, BB2, SubInst, Mapping, DTU);
  261. EXPECT_TRUE(Split);
  262. EXPECT_EQ(Mapping.size(), 2u);
  263. EXPECT_TRUE(Mapping.find(AddInst) != Mapping.end());
  264. EXPECT_TRUE(Mapping.find(MulInst) != Mapping.end());
  265. auto AddSplit = dyn_cast<Instruction>(Mapping[AddInst]);
  266. EXPECT_TRUE(AddSplit);
  267. EXPECT_EQ(AddSplit->getOperand(0), V);
  268. EXPECT_EQ(AddSplit->getOperand(1), V);
  269. EXPECT_EQ(AddSplit->getParent(), Split);
  270. auto MulSplit = dyn_cast<Instruction>(Mapping[MulInst]);
  271. EXPECT_TRUE(MulSplit);
  272. EXPECT_EQ(MulSplit->getOperand(0), AddSplit);
  273. EXPECT_EQ(MulSplit->getOperand(1), V);
  274. EXPECT_EQ(MulSplit->getParent(), Split);
  275. EXPECT_EQ(MulSplit->getNextNode(), Split->getTerminator());
  276. EXPECT_EQ(Split->getSingleSuccessor(), BB2);
  277. EXPECT_EQ(BB2->getSingleSuccessor(), Split);
  278. delete F;
  279. }
  280. static void runWithLoopInfoAndDominatorTree(
  281. Module &M, StringRef FuncName,
  282. function_ref<void(Function &F, LoopInfo &LI, DominatorTree &DT)> Test) {
  283. auto *F = M.getFunction(FuncName);
  284. ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
  285. DominatorTree DT(*F);
  286. LoopInfo LI(DT);
  287. Test(*F, LI, DT);
  288. }
  289. static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
  290. SMDiagnostic Err;
  291. std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
  292. if (!Mod)
  293. Err.print("CloneLoop", errs());
  294. return Mod;
  295. }
  296. TEST(CloneLoop, CloneLoopNest) {
  297. // Parse the module.
  298. LLVMContext Context;
  299. std::unique_ptr<Module> M = parseIR(
  300. Context,
  301. R"(define void @foo(i32* %A, i32 %ub) {
  302. entry:
  303. %guardcmp = icmp slt i32 0, %ub
  304. br i1 %guardcmp, label %for.outer.preheader, label %for.end
  305. for.outer.preheader:
  306. br label %for.outer
  307. for.outer:
  308. %j = phi i32 [ 0, %for.outer.preheader ], [ %inc.outer, %for.outer.latch ]
  309. br i1 %guardcmp, label %for.inner.preheader, label %for.outer.latch
  310. for.inner.preheader:
  311. br label %for.inner
  312. for.inner:
  313. %i = phi i32 [ 0, %for.inner.preheader ], [ %inc, %for.inner ]
  314. %idxprom = sext i32 %i to i64
  315. %arrayidx = getelementptr inbounds i32, i32* %A, i64 %idxprom
  316. store i32 %i, i32* %arrayidx, align 4
  317. %inc = add nsw i32 %i, 1
  318. %cmp = icmp slt i32 %inc, %ub
  319. br i1 %cmp, label %for.inner, label %for.inner.exit
  320. for.inner.exit:
  321. br label %for.outer.latch
  322. for.outer.latch:
  323. %inc.outer = add nsw i32 %j, 1
  324. %cmp.outer = icmp slt i32 %inc.outer, %ub
  325. br i1 %cmp.outer, label %for.outer, label %for.outer.exit
  326. for.outer.exit:
  327. br label %for.end
  328. for.end:
  329. ret void
  330. })"
  331. );
  332. runWithLoopInfoAndDominatorTree(
  333. *M, "foo", [&](Function &F, LoopInfo &LI, DominatorTree &DT) {
  334. Function::iterator FI = F.begin();
  335. // First basic block is entry - skip it.
  336. BasicBlock *Preheader = &*(++FI);
  337. BasicBlock *Header = &*(++FI);
  338. assert(Header->getName() == "for.outer");
  339. Loop *L = LI.getLoopFor(Header);
  340. EXPECT_NE(L, nullptr);
  341. EXPECT_EQ(Header, L->getHeader());
  342. EXPECT_EQ(Preheader, L->getLoopPreheader());
  343. ValueToValueMapTy VMap;
  344. SmallVector<BasicBlock *, 4> ClonedLoopBlocks;
  345. Loop *NewLoop = cloneLoopWithPreheader(Preheader, Preheader, L, VMap,
  346. "", &LI, &DT, ClonedLoopBlocks);
  347. EXPECT_NE(NewLoop, nullptr);
  348. EXPECT_EQ(NewLoop->getSubLoops().size(), 1u);
  349. Loop::block_iterator BI = NewLoop->block_begin();
  350. EXPECT_TRUE((*BI)->getName().startswith("for.outer"));
  351. EXPECT_TRUE((*(++BI))->getName().startswith("for.inner.preheader"));
  352. EXPECT_TRUE((*(++BI))->getName().startswith("for.inner"));
  353. EXPECT_TRUE((*(++BI))->getName().startswith("for.inner.exit"));
  354. EXPECT_TRUE((*(++BI))->getName().startswith("for.outer.latch"));
  355. });
  356. }
  357. class CloneFunc : public ::testing::Test {
  358. protected:
  359. void SetUp() override {
  360. SetupModule();
  361. CreateOldFunc();
  362. CreateNewFunc();
  363. SetupFinder();
  364. }
  365. void TearDown() override { delete Finder; }
  366. void SetupModule() {
  367. M = new Module("", C);
  368. }
  369. void CreateOldFunc() {
  370. FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false);
  371. OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M);
  372. CreateOldFunctionBodyAndDI();
  373. }
  374. void CreateOldFunctionBodyAndDI() {
  375. DIBuilder DBuilder(*M);
  376. IRBuilder<> IBuilder(C);
  377. // Function DI
  378. auto *File = DBuilder.createFile("filename.c", "/file/dir/");
  379. DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray(None);
  380. DISubroutineType *FuncType =
  381. DBuilder.createSubroutineType(ParamTypes);
  382. auto *CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
  383. DBuilder.createFile("filename.c",
  384. "/file/dir"),
  385. "CloneFunc", false, "", 0);
  386. auto *Subprogram = DBuilder.createFunction(
  387. CU, "f", "f", File, 4, FuncType, 3, DINode::FlagZero,
  388. DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
  389. OldFunc->setSubprogram(Subprogram);
  390. // Function body
  391. BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc);
  392. IBuilder.SetInsertPoint(Entry);
  393. DebugLoc Loc = DebugLoc::get(3, 2, Subprogram);
  394. IBuilder.SetCurrentDebugLocation(Loc);
  395. AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C));
  396. IBuilder.SetCurrentDebugLocation(DebugLoc::get(4, 2, Subprogram));
  397. Value* AllocaContent = IBuilder.getInt32(1);
  398. Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca);
  399. IBuilder.SetCurrentDebugLocation(DebugLoc::get(5, 2, Subprogram));
  400. // Create a local variable around the alloca
  401. auto *IntType = DBuilder.createBasicType("int", 32, dwarf::DW_ATE_signed);
  402. auto *E = DBuilder.createExpression();
  403. auto *Variable =
  404. DBuilder.createAutoVariable(Subprogram, "x", File, 5, IntType, true);
  405. auto *DL = DILocation::get(Subprogram->getContext(), 5, 0, Subprogram);
  406. DBuilder.insertDeclare(Alloca, Variable, E, DL, Store);
  407. DBuilder.insertDbgValueIntrinsic(AllocaContent, Variable, E, DL, Entry);
  408. // Also create an inlined variable.
  409. // Create a distinct struct type that we should not duplicate during
  410. // cloning).
  411. auto *StructType = DICompositeType::getDistinct(
  412. C, dwarf::DW_TAG_structure_type, "some_struct", nullptr, 0, nullptr,
  413. nullptr, 32, 32, 0, DINode::FlagZero, nullptr, 0, nullptr, nullptr);
  414. auto *InlinedSP = DBuilder.createFunction(
  415. CU, "inlined", "inlined", File, 8, FuncType, 9, DINode::FlagZero,
  416. DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
  417. auto *InlinedVar =
  418. DBuilder.createAutoVariable(InlinedSP, "inlined", File, 5, StructType, true);
  419. auto *Scope = DBuilder.createLexicalBlock(
  420. DBuilder.createLexicalBlockFile(InlinedSP, File), File, 1, 1);
  421. auto InlinedDL =
  422. DebugLoc::get(9, 4, Scope, DebugLoc::get(5, 2, Subprogram));
  423. IBuilder.SetCurrentDebugLocation(InlinedDL);
  424. DBuilder.insertDeclare(Alloca, InlinedVar, E, InlinedDL, Store);
  425. IBuilder.CreateStore(IBuilder.getInt32(2), Alloca);
  426. // Finalize the debug info.
  427. DBuilder.finalize();
  428. IBuilder.CreateRetVoid();
  429. // Create another, empty, compile unit.
  430. DIBuilder DBuilder2(*M);
  431. DBuilder2.createCompileUnit(dwarf::DW_LANG_C99,
  432. DBuilder.createFile("extra.c", "/file/dir"),
  433. "CloneFunc", false, "", 0);
  434. DBuilder2.finalize();
  435. }
  436. void CreateNewFunc() {
  437. ValueToValueMapTy VMap;
  438. NewFunc = CloneFunction(OldFunc, VMap, nullptr);
  439. }
  440. void SetupFinder() {
  441. Finder = new DebugInfoFinder();
  442. Finder->processModule(*M);
  443. }
  444. LLVMContext C;
  445. Function* OldFunc;
  446. Function* NewFunc;
  447. Module* M;
  448. DebugInfoFinder* Finder;
  449. };
  450. // Test that a new, distinct function was created.
  451. TEST_F(CloneFunc, NewFunctionCreated) {
  452. EXPECT_NE(OldFunc, NewFunc);
  453. }
  454. // Test that a new subprogram entry was added and is pointing to the new
  455. // function, while the original subprogram still points to the old one.
  456. TEST_F(CloneFunc, Subprogram) {
  457. EXPECT_FALSE(verifyModule(*M, &errs()));
  458. EXPECT_EQ(3U, Finder->subprogram_count());
  459. EXPECT_NE(NewFunc->getSubprogram(), OldFunc->getSubprogram());
  460. }
  461. // Test that instructions in the old function still belong to it in the
  462. // metadata, while instruction in the new function belong to the new one.
  463. TEST_F(CloneFunc, InstructionOwnership) {
  464. EXPECT_FALSE(verifyModule(*M));
  465. inst_iterator OldIter = inst_begin(OldFunc);
  466. inst_iterator OldEnd = inst_end(OldFunc);
  467. inst_iterator NewIter = inst_begin(NewFunc);
  468. inst_iterator NewEnd = inst_end(NewFunc);
  469. while (OldIter != OldEnd && NewIter != NewEnd) {
  470. Instruction& OldI = *OldIter;
  471. Instruction& NewI = *NewIter;
  472. EXPECT_NE(&OldI, &NewI);
  473. EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata());
  474. if (OldI.hasMetadata()) {
  475. const DebugLoc& OldDL = OldI.getDebugLoc();
  476. const DebugLoc& NewDL = NewI.getDebugLoc();
  477. // Verify that the debug location data is the same
  478. EXPECT_EQ(OldDL.getLine(), NewDL.getLine());
  479. EXPECT_EQ(OldDL.getCol(), NewDL.getCol());
  480. // But that they belong to different functions
  481. auto *OldSubprogram = cast<DISubprogram>(OldDL.getInlinedAtScope());
  482. auto *NewSubprogram = cast<DISubprogram>(NewDL.getInlinedAtScope());
  483. EXPECT_EQ(OldFunc->getSubprogram(), OldSubprogram);
  484. EXPECT_EQ(NewFunc->getSubprogram(), NewSubprogram);
  485. }
  486. ++OldIter;
  487. ++NewIter;
  488. }
  489. EXPECT_EQ(OldEnd, OldIter);
  490. EXPECT_EQ(NewEnd, NewIter);
  491. }
  492. // Test that the arguments for debug intrinsics in the new function were
  493. // properly cloned
  494. TEST_F(CloneFunc, DebugIntrinsics) {
  495. EXPECT_FALSE(verifyModule(*M));
  496. inst_iterator OldIter = inst_begin(OldFunc);
  497. inst_iterator OldEnd = inst_end(OldFunc);
  498. inst_iterator NewIter = inst_begin(NewFunc);
  499. inst_iterator NewEnd = inst_end(NewFunc);
  500. while (OldIter != OldEnd && NewIter != NewEnd) {
  501. Instruction& OldI = *OldIter;
  502. Instruction& NewI = *NewIter;
  503. if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) {
  504. DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI);
  505. EXPECT_TRUE(NewIntrin);
  506. // Old address must belong to the old function
  507. EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())->
  508. getParent()->getParent());
  509. // New address must belong to the new function
  510. EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())->
  511. getParent()->getParent());
  512. if (OldIntrin->getDebugLoc()->getInlinedAt()) {
  513. // Inlined variable should refer to the same DILocalVariable as in the
  514. // Old Function
  515. EXPECT_EQ(OldIntrin->getVariable(), NewIntrin->getVariable());
  516. } else {
  517. // Old variable must belong to the old function.
  518. EXPECT_EQ(OldFunc->getSubprogram(),
  519. cast<DISubprogram>(OldIntrin->getVariable()->getScope()));
  520. // New variable must belong to the new function.
  521. EXPECT_EQ(NewFunc->getSubprogram(),
  522. cast<DISubprogram>(NewIntrin->getVariable()->getScope()));
  523. }
  524. } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) {
  525. DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI);
  526. EXPECT_TRUE(NewIntrin);
  527. if (!OldIntrin->getDebugLoc()->getInlinedAt()) {
  528. // Old variable must belong to the old function.
  529. EXPECT_EQ(OldFunc->getSubprogram(),
  530. cast<DISubprogram>(OldIntrin->getVariable()->getScope()));
  531. // New variable must belong to the new function.
  532. EXPECT_EQ(NewFunc->getSubprogram(),
  533. cast<DISubprogram>(NewIntrin->getVariable()->getScope()));
  534. }
  535. }
  536. ++OldIter;
  537. ++NewIter;
  538. }
  539. }
  540. static int GetDICompileUnitCount(const Module& M) {
  541. if (const auto* LLVM_DBG_CU = M.getNamedMetadata("llvm.dbg.cu")) {
  542. return LLVM_DBG_CU->getNumOperands();
  543. }
  544. return 0;
  545. }
  546. TEST(CloneFunction, CloneFunctionToDifferentModule) {
  547. StringRef ImplAssembly = R"(
  548. define void @foo() {
  549. ret void, !dbg !5
  550. }
  551. !llvm.module.flags = !{!0}
  552. !llvm.dbg.cu = !{!2, !6}
  553. !0 = !{i32 1, !"Debug Info Version", i32 3}
  554. !1 = distinct !DISubprogram(unit: !2)
  555. !2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)
  556. !3 = !DIFile(filename: "foo.c", directory: "/tmp")
  557. !4 = distinct !DISubprogram(unit: !2)
  558. !5 = !DILocation(line: 4, scope: !1)
  559. !6 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3)
  560. )";
  561. StringRef DeclAssembly = R"(
  562. declare void @foo()
  563. )";
  564. LLVMContext Context;
  565. SMDiagnostic Error;
  566. auto ImplModule = parseAssemblyString(ImplAssembly, Error, Context);
  567. EXPECT_TRUE(ImplModule != nullptr);
  568. // DICompileUnits: !2, !6. Only !2 is reachable from @foo().
  569. EXPECT_TRUE(GetDICompileUnitCount(*ImplModule) == 2);
  570. auto* ImplFunction = ImplModule->getFunction("foo");
  571. EXPECT_TRUE(ImplFunction != nullptr);
  572. auto DeclModule = parseAssemblyString(DeclAssembly, Error, Context);
  573. EXPECT_TRUE(DeclModule != nullptr);
  574. // No DICompileUnits defined here.
  575. EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 0);
  576. auto* DeclFunction = DeclModule->getFunction("foo");
  577. EXPECT_TRUE(DeclFunction != nullptr);
  578. ValueToValueMapTy VMap;
  579. VMap[ImplFunction] = DeclFunction;
  580. // No args to map
  581. SmallVector<ReturnInst*, 8> Returns;
  582. CloneFunctionInto(DeclFunction, ImplFunction, VMap, true, Returns);
  583. EXPECT_FALSE(verifyModule(*ImplModule, &errs()));
  584. EXPECT_FALSE(verifyModule(*DeclModule, &errs()));
  585. // DICompileUnit !2 shall be inserted into DeclModule.
  586. EXPECT_TRUE(GetDICompileUnitCount(*DeclModule) == 1);
  587. }
  588. class CloneModule : public ::testing::Test {
  589. protected:
  590. void SetUp() override {
  591. SetupModule();
  592. CreateOldModule();
  593. CreateNewModule();
  594. }
  595. void SetupModule() { OldM = new Module("", C); }
  596. void CreateOldModule() {
  597. auto *CD = OldM->getOrInsertComdat("comdat");
  598. CD->setSelectionKind(Comdat::ExactMatch);
  599. auto GV = new GlobalVariable(
  600. *OldM, Type::getInt32Ty(C), false, GlobalValue::ExternalLinkage,
  601. ConstantInt::get(Type::getInt32Ty(C), 1), "gv");
  602. GV->addMetadata(LLVMContext::MD_type, *MDNode::get(C, {}));
  603. GV->setComdat(CD);
  604. DIBuilder DBuilder(*OldM);
  605. IRBuilder<> IBuilder(C);
  606. auto *FuncType = FunctionType::get(Type::getVoidTy(C), false);
  607. auto *PersFn = Function::Create(FuncType, GlobalValue::ExternalLinkage,
  608. "persfn", OldM);
  609. auto *F =
  610. Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", OldM);
  611. F->setPersonalityFn(PersFn);
  612. F->setComdat(CD);
  613. // Create debug info
  614. auto *File = DBuilder.createFile("filename.c", "/file/dir/");
  615. DITypeRefArray ParamTypes = DBuilder.getOrCreateTypeArray(None);
  616. DISubroutineType *DFuncType = DBuilder.createSubroutineType(ParamTypes);
  617. auto *CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
  618. DBuilder.createFile("filename.c",
  619. "/file/dir"),
  620. "CloneModule", false, "", 0);
  621. // Function DI
  622. auto *Subprogram = DBuilder.createFunction(
  623. CU, "f", "f", File, 4, DFuncType, 3, DINode::FlagZero,
  624. DISubprogram::SPFlagLocalToUnit | DISubprogram::SPFlagDefinition);
  625. F->setSubprogram(Subprogram);
  626. // Create and assign DIGlobalVariableExpression to gv
  627. auto GVExpression = DBuilder.createGlobalVariableExpression(
  628. Subprogram, "gv", "gv", File, 1, DBuilder.createNullPtrType(), false);
  629. GV->addDebugInfo(GVExpression);
  630. // DIGlobalVariableExpression not attached to any global variable
  631. auto Expr = DBuilder.createExpression(
  632. ArrayRef<uint64_t>{dwarf::DW_OP_constu, 42U, dwarf::DW_OP_stack_value});
  633. DBuilder.createGlobalVariableExpression(
  634. Subprogram, "unattached", "unattached", File, 1,
  635. DBuilder.createNullPtrType(), false, Expr);
  636. auto *Entry = BasicBlock::Create(C, "", F);
  637. IBuilder.SetInsertPoint(Entry);
  638. IBuilder.CreateRetVoid();
  639. // Finalize the debug info
  640. DBuilder.finalize();
  641. }
  642. void CreateNewModule() { NewM = llvm::CloneModule(*OldM).release(); }
  643. LLVMContext C;
  644. Module *OldM;
  645. Module *NewM;
  646. };
  647. TEST_F(CloneModule, Verify) {
  648. EXPECT_FALSE(verifyModule(*NewM));
  649. }
  650. TEST_F(CloneModule, OldModuleUnchanged) {
  651. DebugInfoFinder Finder;
  652. Finder.processModule(*OldM);
  653. EXPECT_EQ(1U, Finder.subprogram_count());
  654. }
  655. TEST_F(CloneModule, Subprogram) {
  656. Function *NewF = NewM->getFunction("f");
  657. DISubprogram *SP = NewF->getSubprogram();
  658. EXPECT_TRUE(SP != nullptr);
  659. EXPECT_EQ(SP->getName(), "f");
  660. EXPECT_EQ(SP->getFile()->getFilename(), "filename.c");
  661. EXPECT_EQ(SP->getLine(), (unsigned)4);
  662. }
  663. TEST_F(CloneModule, GlobalMetadata) {
  664. GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
  665. EXPECT_NE(nullptr, NewGV->getMetadata(LLVMContext::MD_type));
  666. }
  667. TEST_F(CloneModule, GlobalDebugInfo) {
  668. GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
  669. EXPECT_TRUE(NewGV != nullptr);
  670. // Find debug info expression assigned to global
  671. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  672. NewGV->getDebugInfo(GVs);
  673. EXPECT_EQ(GVs.size(), 1U);
  674. DIGlobalVariableExpression *GVExpr = GVs[0];
  675. DIGlobalVariable *GV = GVExpr->getVariable();
  676. EXPECT_TRUE(GV != nullptr);
  677. EXPECT_EQ(GV->getName(), "gv");
  678. EXPECT_EQ(GV->getLine(), 1U);
  679. // Assert that the scope of the debug info attached to
  680. // global variable matches the cloned function.
  681. DISubprogram *SP = NewM->getFunction("f")->getSubprogram();
  682. EXPECT_TRUE(SP != nullptr);
  683. EXPECT_EQ(GV->getScope(), SP);
  684. }
  685. TEST_F(CloneModule, CompileUnit) {
  686. // Find DICompileUnit listed in llvm.dbg.cu
  687. auto *NMD = NewM->getNamedMetadata("llvm.dbg.cu");
  688. EXPECT_TRUE(NMD != nullptr);
  689. EXPECT_EQ(NMD->getNumOperands(), 1U);
  690. DICompileUnit *CU = dyn_cast<llvm::DICompileUnit>(NMD->getOperand(0));
  691. EXPECT_TRUE(CU != nullptr);
  692. // Assert this CU is consistent with the cloned function debug info
  693. DISubprogram *SP = NewM->getFunction("f")->getSubprogram();
  694. EXPECT_TRUE(SP != nullptr);
  695. EXPECT_EQ(SP->getUnit(), CU);
  696. // Check globals listed in CU have the correct scope
  697. DIGlobalVariableExpressionArray GlobalArray = CU->getGlobalVariables();
  698. EXPECT_EQ(GlobalArray.size(), 2U);
  699. for (DIGlobalVariableExpression *GVExpr : GlobalArray) {
  700. DIGlobalVariable *GV = GVExpr->getVariable();
  701. EXPECT_EQ(GV->getScope(), SP);
  702. }
  703. }
  704. TEST_F(CloneModule, Comdat) {
  705. GlobalVariable *NewGV = NewM->getGlobalVariable("gv");
  706. auto *CD = NewGV->getComdat();
  707. ASSERT_NE(nullptr, CD);
  708. EXPECT_EQ("comdat", CD->getName());
  709. EXPECT_EQ(Comdat::ExactMatch, CD->getSelectionKind());
  710. Function *NewF = NewM->getFunction("f");
  711. EXPECT_EQ(CD, NewF->getComdat());
  712. }
  713. }