xref: /llvm-project/llvm/unittests/Transforms/Utils/LocalTest.cpp (revision 5ea1b32631cc82b4ea07e59502f5daf2f2353689)
1 //===- Local.cpp - Unit tests for Local -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Transforms/Utils/Local.h"
11 #include "llvm/Analysis/PostDominators.h"
12 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/IR/BasicBlock.h"
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/IR/DomTreeUpdater.h"
16 #include "llvm/IR/IRBuilder.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Verifier.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "gtest/gtest.h"
23 
24 using namespace llvm;
25 
26 TEST(Local, RecursivelyDeleteDeadPHINodes) {
27   LLVMContext C;
28 
29   IRBuilder<> builder(C);
30 
31   // Make blocks
32   BasicBlock *bb0 = BasicBlock::Create(C);
33   BasicBlock *bb1 = BasicBlock::Create(C);
34 
35   builder.SetInsertPoint(bb0);
36   PHINode    *phi = builder.CreatePHI(Type::getInt32Ty(C), 2);
37   BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1);
38 
39   builder.SetInsertPoint(bb1);
40   BranchInst *br1 = builder.CreateBr(bb0);
41 
42   phi->addIncoming(phi, bb0);
43   phi->addIncoming(phi, bb1);
44 
45   // The PHI will be removed
46   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
47 
48   // Make sure the blocks only contain the branches
49   EXPECT_EQ(&bb0->front(), br0);
50   EXPECT_EQ(&bb1->front(), br1);
51 
52   builder.SetInsertPoint(bb0);
53   phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
54 
55   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
56 
57   builder.SetInsertPoint(bb0);
58   phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
59   builder.CreateAdd(phi, phi);
60 
61   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
62 
63   bb0->dropAllReferences();
64   bb1->dropAllReferences();
65   delete bb0;
66   delete bb1;
67 }
68 
69 TEST(Local, RemoveDuplicatePHINodes) {
70   LLVMContext C;
71   IRBuilder<> B(C);
72 
73   std::unique_ptr<Function> F(
74       Function::Create(FunctionType::get(B.getVoidTy(), false),
75                        GlobalValue::ExternalLinkage, "F"));
76   BasicBlock *Entry(BasicBlock::Create(C, "", F.get()));
77   BasicBlock *BB(BasicBlock::Create(C, "", F.get()));
78   BranchInst::Create(BB, Entry);
79 
80   B.SetInsertPoint(BB);
81 
82   AssertingVH<PHINode> P1 = B.CreatePHI(Type::getInt32Ty(C), 2);
83   P1->addIncoming(B.getInt32(42), Entry);
84 
85   PHINode *P2 = B.CreatePHI(Type::getInt32Ty(C), 2);
86   P2->addIncoming(B.getInt32(42), Entry);
87 
88   AssertingVH<PHINode> P3 = B.CreatePHI(Type::getInt32Ty(C), 2);
89   P3->addIncoming(B.getInt32(42), Entry);
90   P3->addIncoming(B.getInt32(23), BB);
91 
92   PHINode *P4 = B.CreatePHI(Type::getInt32Ty(C), 2);
93   P4->addIncoming(B.getInt32(42), Entry);
94   P4->addIncoming(B.getInt32(23), BB);
95 
96   P1->addIncoming(P3, BB);
97   P2->addIncoming(P4, BB);
98   BranchInst::Create(BB, BB);
99 
100   // Verify that we can eliminate PHIs that become duplicates after chaning PHIs
101   // downstream.
102   EXPECT_TRUE(EliminateDuplicatePHINodes(BB));
103   EXPECT_EQ(3U, BB->size());
104 }
105 
106 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
107   SMDiagnostic Err;
108   std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
109   if (!Mod)
110     Err.print("UtilsTests", errs());
111   return Mod;
112 }
113 
114 TEST(Local, ReplaceDbgDeclare) {
115   LLVMContext C;
116 
117   // Original C source to get debug info for a local variable:
118   // void f() { int x; }
119   std::unique_ptr<Module> M = parseIR(C,
120                                       R"(
121       define void @f() !dbg !8 {
122       entry:
123         %x = alloca i32, align 4
124         call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13
125         call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13
126         ret void, !dbg !14
127       }
128       declare void @llvm.dbg.declare(metadata, metadata, metadata)
129       !llvm.dbg.cu = !{!0}
130       !llvm.module.flags = !{!3, !4}
131       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
132       !1 = !DIFile(filename: "t2.c", directory: "foo")
133       !2 = !{}
134       !3 = !{i32 2, !"Dwarf Version", i32 4}
135       !4 = !{i32 2, !"Debug Info Version", i32 3}
136       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
137       !9 = !DISubroutineType(types: !10)
138       !10 = !{null}
139       !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
140       !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
141       !13 = !DILocation(line: 2, column: 7, scope: !8)
142       !14 = !DILocation(line: 3, column: 1, scope: !8)
143       )");
144   auto *GV = M->getNamedValue("f");
145   ASSERT_TRUE(GV);
146   auto *F = dyn_cast<Function>(GV);
147   ASSERT_TRUE(F);
148   Instruction *Inst = &F->front().front();
149   auto *AI = dyn_cast<AllocaInst>(Inst);
150   ASSERT_TRUE(AI);
151   Inst = Inst->getNextNode()->getNextNode();
152   ASSERT_TRUE(Inst);
153   auto *DII = dyn_cast<DbgDeclareInst>(Inst);
154   ASSERT_TRUE(DII);
155   Value *NewBase = Constant::getNullValue(Type::getInt32PtrTy(C));
156   DIBuilder DIB(*M);
157   replaceDbgDeclare(AI, NewBase, DII, DIB, DIExpression::NoDeref, 0,
158                     DIExpression::NoDeref);
159 
160   // There should be exactly two dbg.declares.
161   int Declares = 0;
162   for (const Instruction &I : F->front())
163     if (isa<DbgDeclareInst>(I))
164       Declares++;
165   EXPECT_EQ(2, Declares);
166 }
167 
168 /// Build the dominator tree for the function and run the Test.
169 static void runWithDomTree(
170     Module &M, StringRef FuncName,
171     function_ref<void(Function &F, DominatorTree *DT)> Test) {
172   auto *F = M.getFunction(FuncName);
173   ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
174   // Compute the dominator tree for the function.
175   DominatorTree DT(*F);
176   Test(*F, &DT);
177 }
178 
179 TEST(Local, MergeBasicBlockIntoOnlyPred) {
180   LLVMContext C;
181   std::unique_ptr<Module> M;
182   auto resetIR = [&]() {
183     M = parseIR(C,
184                 R"(
185       define i32 @f(i8* %str) {
186       entry:
187         br label %bb2.i
188       bb2.i:                                            ; preds = %bb4.i, %entry
189         br i1 false, label %bb4.i, label %base2flt.exit204
190       bb4.i:                                            ; preds = %bb2.i
191         br i1 false, label %base2flt.exit204, label %bb2.i
192       bb10.i196.bb7.i197_crit_edge:                     ; No predecessors!
193         br label %bb7.i197
194       bb7.i197:                                         ; preds = %bb10.i196.bb7.i197_crit_edge
195         %.reg2mem.0 = phi i32 [ %.reg2mem.0, %bb10.i196.bb7.i197_crit_edge ]
196         br i1 undef, label %base2flt.exit204, label %base2flt.exit204
197       base2flt.exit204:                                 ; preds = %bb7.i197, %bb7.i197, %bb2.i, %bb4.i
198         ret i32 0
199       }
200       )");
201   };
202 
203   auto resetIRReplaceEntry = [&]() {
204     M = parseIR(C,
205                 R"(
206       define i32 @f() {
207       entry:
208         br label %bb2.i
209       bb2.i:                                            ; preds = %entry
210         ret i32 0
211       }
212       )");
213   };
214 
215   auto Test = [&](Function &F, DomTreeUpdater &DTU) {
216     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
217       BasicBlock *BB = &*I++;
218       BasicBlock *SinglePred = BB->getSinglePredecessor();
219       if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
220         continue;
221       BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
222       if (Term && !Term->isConditional())
223         MergeBasicBlockIntoOnlyPred(BB, &DTU);
224     }
225     if (DTU.hasDomTree()) {
226       EXPECT_TRUE(DTU.getDomTree().verify());
227     }
228     if (DTU.hasPostDomTree()) {
229       EXPECT_TRUE(DTU.getPostDomTree().verify());
230     }
231   };
232 
233   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
234   // both DT and PDT.
235   resetIR();
236   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
237     PostDominatorTree PDT = PostDominatorTree(F);
238     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
239     Test(F, DTU);
240   });
241 
242   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
243   // DT.
244   resetIR();
245   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
246     DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
247     Test(F, DTU);
248   });
249 
250   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
251   // PDT.
252   resetIR();
253   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
254     PostDominatorTree PDT = PostDominatorTree(F);
255     DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager);
256     Test(F, DTU);
257   });
258 
259   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
260   // both DT and PDT.
261   resetIR();
262   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
263     PostDominatorTree PDT = PostDominatorTree(F);
264     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
265     Test(F, DTU);
266   });
267 
268   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
269   // PDT.
270   resetIR();
271   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
272     PostDominatorTree PDT = PostDominatorTree(F);
273     DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy);
274     Test(F, DTU);
275   });
276 
277   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT.
278   resetIR();
279   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
280     DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
281     Test(F, DTU);
282   });
283 
284   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
285   // both DT and PDT.
286   resetIRReplaceEntry();
287   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
288     PostDominatorTree PDT = PostDominatorTree(F);
289     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
290     Test(F, DTU);
291   });
292 
293   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
294   // DT.
295   resetIRReplaceEntry();
296   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
297     DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
298     Test(F, DTU);
299   });
300 
301   // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
302   // PDT.
303   resetIRReplaceEntry();
304   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
305     PostDominatorTree PDT = PostDominatorTree(F);
306     DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager);
307     Test(F, DTU);
308   });
309 
310   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
311   // both DT and PDT.
312   resetIRReplaceEntry();
313   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
314     PostDominatorTree PDT = PostDominatorTree(F);
315     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
316     Test(F, DTU);
317   });
318 
319   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
320   // PDT.
321   resetIRReplaceEntry();
322   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
323     PostDominatorTree PDT = PostDominatorTree(F);
324     DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy);
325     Test(F, DTU);
326   });
327 
328   // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT.
329   resetIRReplaceEntry();
330   runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
331     DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
332     Test(F, DTU);
333   });
334 }
335 
336 TEST(Local, ConstantFoldTerminator) {
337   LLVMContext C;
338 
339   std::unique_ptr<Module> M = parseIR(C,
340                                       R"(
341       define void @br_same_dest() {
342       entry:
343         br i1 false, label %bb0, label %bb0
344       bb0:
345         ret void
346       }
347 
348       define void @br_different_dest() {
349       entry:
350         br i1 true, label %bb0, label %bb1
351       bb0:
352         br label %exit
353       bb1:
354         br label %exit
355       exit:
356         ret void
357       }
358 
359       define void @switch_2_different_dest() {
360       entry:
361         switch i32 0, label %default [ i32 0, label %bb0 ]
362       default:
363         ret void
364       bb0:
365         ret void
366       }
367       define void @switch_2_different_dest_default() {
368       entry:
369         switch i32 1, label %default [ i32 0, label %bb0 ]
370       default:
371         ret void
372       bb0:
373         ret void
374       }
375       define void @switch_3_different_dest() {
376       entry:
377         switch i32 0, label %default [ i32 0, label %bb0
378                                        i32 1, label %bb1 ]
379       default:
380         ret void
381       bb0:
382         ret void
383       bb1:
384         ret void
385       }
386 
387       define void @switch_variable_2_default_dest(i32 %arg) {
388       entry:
389         switch i32 %arg, label %default [ i32 0, label %default ]
390       default:
391         ret void
392       }
393 
394       define void @switch_constant_2_default_dest() {
395       entry:
396         switch i32 1, label %default [ i32 0, label %default ]
397       default:
398         ret void
399       }
400 
401       define void @switch_constant_3_repeated_dest() {
402       entry:
403         switch i32 0, label %default [ i32 0, label %bb0
404                                        i32 1, label %bb0 ]
405        bb0:
406          ret void
407       default:
408         ret void
409       }
410 
411       define void @indirectbr() {
412       entry:
413         indirectbr i8* blockaddress(@indirectbr, %bb0), [label %bb0, label %bb1]
414       bb0:
415         ret void
416       bb1:
417         ret void
418       }
419 
420       define void @indirectbr_repeated() {
421       entry:
422         indirectbr i8* blockaddress(@indirectbr_repeated, %bb0), [label %bb0, label %bb0]
423       bb0:
424         ret void
425       }
426 
427       define void @indirectbr_unreachable() {
428       entry:
429         indirectbr i8* blockaddress(@indirectbr_unreachable, %bb0), [label %bb1]
430       bb0:
431         ret void
432       bb1:
433         ret void
434       }
435         )");
436 
437   auto CFAllTerminatorsEager = [&](Function &F, DominatorTree *DT) {
438     PostDominatorTree PDT = PostDominatorTree(F);
439     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
440     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
441       BasicBlock *BB = &*I++;
442       ConstantFoldTerminator(BB, true, nullptr, &DTU);
443     }
444 
445     EXPECT_TRUE(DTU.getDomTree().verify());
446     EXPECT_TRUE(DTU.getPostDomTree().verify());
447   };
448 
449   auto CFAllTerminatorsLazy = [&](Function &F, DominatorTree *DT) {
450     PostDominatorTree PDT = PostDominatorTree(F);
451     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
452     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
453       BasicBlock *BB = &*I++;
454       ConstantFoldTerminator(BB, true, nullptr, &DTU);
455     }
456 
457     EXPECT_TRUE(DTU.getDomTree().verify());
458     EXPECT_TRUE(DTU.getPostDomTree().verify());
459   };
460 
461   // Test ConstantFoldTerminator under Eager UpdateStrategy.
462   runWithDomTree(*M, "br_same_dest", CFAllTerminatorsEager);
463   runWithDomTree(*M, "br_different_dest", CFAllTerminatorsEager);
464   runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsEager);
465   runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsEager);
466   runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsEager);
467   runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsEager);
468   runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsEager);
469   runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsEager);
470   runWithDomTree(*M, "indirectbr", CFAllTerminatorsEager);
471   runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsEager);
472   runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsEager);
473 
474   // Test ConstantFoldTerminator under Lazy UpdateStrategy.
475   runWithDomTree(*M, "br_same_dest", CFAllTerminatorsLazy);
476   runWithDomTree(*M, "br_different_dest", CFAllTerminatorsLazy);
477   runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsLazy);
478   runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsLazy);
479   runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsLazy);
480   runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsLazy);
481   runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsLazy);
482   runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsLazy);
483   runWithDomTree(*M, "indirectbr", CFAllTerminatorsLazy);
484   runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsLazy);
485   runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsLazy);
486 }
487 
488 struct SalvageDebugInfoTest : ::testing::Test {
489   LLVMContext C;
490   std::unique_ptr<Module> M;
491   Function *F = nullptr;
492 
493   void SetUp() {
494     M = parseIR(C,
495                 R"(
496       define void @f() !dbg !8 {
497       entry:
498         %x = add i32 0, 1
499         %y = add i32 %x, 2
500         call void @llvm.dbg.value(metadata i32 %x, metadata !11, metadata !DIExpression()), !dbg !13
501         call void @llvm.dbg.value(metadata i32 %y, metadata !11, metadata !DIExpression()), !dbg !13
502         ret void, !dbg !14
503       }
504       declare void @llvm.dbg.value(metadata, metadata, metadata)
505       !llvm.dbg.cu = !{!0}
506       !llvm.module.flags = !{!3, !4}
507       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
508       !1 = !DIFile(filename: "t2.c", directory: "foo")
509       !2 = !{}
510       !3 = !{i32 2, !"Dwarf Version", i32 4}
511       !4 = !{i32 2, !"Debug Info Version", i32 3}
512       !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2)
513       !9 = !DISubroutineType(types: !10)
514       !10 = !{null}
515       !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
516       !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
517       !13 = !DILocation(line: 2, column: 7, scope: !8)
518       !14 = !DILocation(line: 3, column: 1, scope: !8)
519       )");
520 
521     auto *GV = M->getNamedValue("f");
522     ASSERT_TRUE(GV);
523     F = dyn_cast<Function>(GV);
524     ASSERT_TRUE(F);
525   }
526 
527   bool doesDebugValueDescribeX(const DbgValueInst &DI) {
528     const auto &CI = *cast<ConstantInt>(DI.getValue());
529     if (CI.isZero())
530       return DI.getExpression()->getElements().equals(
531           {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value});
532     else if (CI.isOneValue())
533       return DI.getExpression()->getElements().empty();
534     return false;
535   }
536 
537   bool doesDebugValueDescribeY(const DbgValueInst &DI) {
538     const auto &CI = *cast<ConstantInt>(DI.getValue());
539     if (CI.isZero())
540       return DI.getExpression()->getElements().equals(
541           {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2,
542            dwarf::DW_OP_stack_value});
543     else if (CI.isOneValue())
544       return DI.getExpression()->getElements().equals(
545           {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value});
546     return false;
547   }
548 
549   void verifyDebugValuesAreSalvaged() {
550     // Check that the debug values for %x and %y are preserved.
551     bool FoundX = false;
552     bool FoundY = false;
553     for (const Instruction &I : F->front()) {
554       auto DI = dyn_cast<DbgValueInst>(&I);
555       if (!DI) {
556         // The function should only contain debug values and a terminator.
557         ASSERT_TRUE(I.isTerminator());
558         continue;
559       }
560       EXPECT_EQ(DI->getVariable()->getName(), "x");
561       FoundX |= doesDebugValueDescribeX(*DI);
562       FoundY |= doesDebugValueDescribeY(*DI);
563     }
564     ASSERT_TRUE(FoundX);
565     ASSERT_TRUE(FoundY);
566   }
567 };
568 
569 TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) {
570   Instruction *Inst = &F->front().front();
571   Inst = Inst->getNextNode(); // Get %y = add ...
572   ASSERT_TRUE(Inst);
573   bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst);
574   ASSERT_TRUE(Deleted);
575   verifyDebugValuesAreSalvaged();
576 }
577 
578 TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) {
579   BasicBlock *BB = &F->front();
580   ASSERT_TRUE(BB);
581   bool Deleted = SimplifyInstructionsInBlock(BB);
582   ASSERT_TRUE(Deleted);
583   verifyDebugValuesAreSalvaged();
584 }
585 
586 TEST(Local, ChangeToUnreachable) {
587   LLVMContext Ctx;
588 
589   std::unique_ptr<Module> M = parseIR(Ctx,
590                                       R"(
591     define internal void @foo() !dbg !6 {
592     entry:
593       ret void, !dbg !8
594     }
595 
596     !llvm.dbg.cu = !{!0}
597     !llvm.debugify = !{!3, !4}
598     !llvm.module.flags = !{!5}
599 
600     !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
601     !1 = !DIFile(filename: "test.ll", directory: "/")
602     !2 = !{}
603     !3 = !{i32 1}
604     !4 = !{i32 0}
605     !5 = !{i32 2, !"Debug Info Version", i32 3}
606     !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, isLocal: true, isDefinition: true, scopeLine: 1, isOptimized: true, unit: !0, retainedNodes: !2)
607     !7 = !DISubroutineType(types: !2)
608     !8 = !DILocation(line: 1, column: 1, scope: !6)
609   )");
610 
611   bool BrokenDebugInfo = true;
612   verifyModule(*M, &errs(), &BrokenDebugInfo);
613   ASSERT_FALSE(BrokenDebugInfo);
614 
615   Function &F = *cast<Function>(M->getNamedValue("foo"));
616 
617   BasicBlock &BB = F.front();
618   Instruction &A = BB.front();
619   DebugLoc DLA = A.getDebugLoc();
620 
621   ASSERT_TRUE(isa<ReturnInst>(&A));
622   // One instruction should be affected.
623   EXPECT_EQ(changeToUnreachable(&A, /*UseLLVMTrap*/false), 1U);
624 
625   Instruction &B = BB.front();
626 
627   // There should be an uncreachable instruction.
628   ASSERT_TRUE(isa<UnreachableInst>(&B));
629 
630   DebugLoc DLB = B.getDebugLoc();
631   EXPECT_EQ(DLA, DLB);
632 }
633 
634 TEST(Local, ReplaceAllDbgUsesWith) {
635   using namespace llvm::dwarf;
636 
637   LLVMContext Ctx;
638 
639   // Note: The datalayout simulates Darwin/x86_64.
640   std::unique_ptr<Module> M = parseIR(Ctx,
641                                       R"(
642     target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128"
643 
644     declare i32 @escape(i32)
645 
646     define void @f() !dbg !6 {
647     entry:
648       %a = add i32 0, 1, !dbg !15
649       call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15
650 
651       %b = add i64 0, 1, !dbg !16
652       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16
653       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16
654       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16
655       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16
656       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_fragment, 0, 8)), !dbg !16
657       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8)), !dbg !16
658 
659       %c = inttoptr i64 0 to i64*, !dbg !17
660       call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17
661 
662       %d = inttoptr i64 0 to i32*, !dbg !18
663       call void @llvm.dbg.addr(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18
664 
665       %e = add <2 x i16> zeroinitializer, zeroinitializer
666       call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18
667 
668       %f = call i32 @escape(i32 0)
669       call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15
670 
671       %barrier = call i32 @escape(i32 0)
672 
673       %g = call i32 @escape(i32 %f)
674       call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15
675 
676       ret void, !dbg !19
677     }
678 
679     declare void @llvm.dbg.addr(metadata, metadata, metadata)
680     declare void @llvm.dbg.declare(metadata, metadata, metadata)
681     declare void @llvm.dbg.value(metadata, metadata, metadata)
682 
683     !llvm.dbg.cu = !{!0}
684     !llvm.module.flags = !{!5}
685 
686     !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
687     !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/")
688     !2 = !{}
689     !5 = !{i32 2, !"Debug Info Version", i32 3}
690     !6 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !1, line: 1, type: !7, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: true, unit: !0, retainedNodes: !8)
691     !7 = !DISubroutineType(types: !2)
692     !8 = !{!9, !11, !13, !14}
693     !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
694     !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed)
695     !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12)
696     !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed)
697     !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12)
698     !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10)
699     !15 = !DILocation(line: 1, column: 1, scope: !6)
700     !16 = !DILocation(line: 2, column: 1, scope: !6)
701     !17 = !DILocation(line: 3, column: 1, scope: !6)
702     !18 = !DILocation(line: 4, column: 1, scope: !6)
703     !19 = !DILocation(line: 5, column: 1, scope: !6)
704     !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10)
705   )");
706 
707   bool BrokenDebugInfo = true;
708   verifyModule(*M, &errs(), &BrokenDebugInfo);
709   ASSERT_FALSE(BrokenDebugInfo);
710 
711   Function &F = *cast<Function>(M->getNamedValue("f"));
712   DominatorTree DT{F};
713 
714   BasicBlock &BB = F.front();
715   Instruction &A = BB.front();
716   Instruction &B = *A.getNextNonDebugInstruction();
717   Instruction &C = *B.getNextNonDebugInstruction();
718   Instruction &D = *C.getNextNonDebugInstruction();
719   Instruction &E = *D.getNextNonDebugInstruction();
720   Instruction &F_ = *E.getNextNonDebugInstruction();
721   Instruction &Barrier = *F_.getNextNonDebugInstruction();
722   Instruction &G = *Barrier.getNextNonDebugInstruction();
723 
724   // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says
725   // pointers are 64 bits, so the conversion would be lossy.
726   EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT));
727   EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT));
728 
729   // Simulate i32 <-> <2 x i16> conversion. This is unsupported.
730   EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT));
731   EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT));
732 
733   // Simulate i32* <-> i64* conversion.
734   EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT));
735 
736   SmallVector<DbgVariableIntrinsic *, 2> CDbgVals;
737   findDbgUsers(CDbgVals, &C);
738   EXPECT_EQ(2U, CDbgVals.size());
739   EXPECT_TRUE(any_of(CDbgVals, [](DbgVariableIntrinsic *DII) {
740     return isa<DbgAddrIntrinsic>(DII);
741   }));
742   EXPECT_TRUE(any_of(CDbgVals, [](DbgVariableIntrinsic *DII) {
743     return isa<DbgDeclareInst>(DII);
744   }));
745 
746   EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT));
747 
748   SmallVector<DbgVariableIntrinsic *, 2> DDbgVals;
749   findDbgUsers(DDbgVals, &D);
750   EXPECT_EQ(2U, DDbgVals.size());
751   EXPECT_TRUE(any_of(DDbgVals, [](DbgVariableIntrinsic *DII) {
752     return isa<DbgAddrIntrinsic>(DII);
753   }));
754   EXPECT_TRUE(any_of(DDbgVals, [](DbgVariableIntrinsic *DII) {
755     return isa<DbgDeclareInst>(DII);
756   }));
757 
758   // Introduce a use-before-def. Check that the dbg.value for %a is salvaged.
759   EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT));
760 
761   auto *ADbgVal = cast<DbgValueInst>(A.getNextNode());
762   EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocation());
763 
764   // Introduce a use-before-def. Check that the dbg.values for %f are deleted.
765   EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT));
766 
767   SmallVector<DbgValueInst *, 1> FDbgVals;
768   findDbgValues(FDbgVals, &F);
769   EXPECT_EQ(0U, FDbgVals.size());
770 
771   // Simulate i32 -> i64 conversion to test sign-extension. Here are some
772   // interesting cases to handle:
773   //  1) debug user has empty DIExpression
774   //  2) debug user has non-empty, non-stack-value'd DIExpression
775   //  3) debug user has non-empty, stack-value'd DIExpression
776   //  4-6) like (1-3), but with a fragment
777   EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT));
778 
779   SmallVector<DbgValueInst *, 8> ADbgVals;
780   findDbgValues(ADbgVals, &A);
781   EXPECT_EQ(6U, ADbgVals.size());
782 
783   // Check that %a has a dbg.value with a DIExpression matching \p Ops.
784   auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) {
785     return any_of(ADbgVals, [&](DbgValueInst *DVI) {
786       assert(DVI->getVariable()->getName() == "2");
787       return DVI->getExpression()->getElements() == Ops;
788     });
789   };
790 
791   // Case 1: The original expr is empty, so no deref is needed.
792   EXPECT_TRUE(hasADbgVal({DW_OP_dup, DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0,
793                           DW_OP_not, DW_OP_mul, DW_OP_or, DW_OP_stack_value}));
794 
795   // Case 2: Perform an address calculation with the original expr, deref it,
796   // then sign-extend the result.
797   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, DW_OP_dup,
798                           DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0, DW_OP_not,
799                           DW_OP_mul, DW_OP_or, DW_OP_stack_value}));
800 
801   // Case 3: Insert the sign-extension logic before the DW_OP_stack_value.
802   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_dup, DW_OP_constu, 31,
803                           DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
804                           DW_OP_stack_value}));
805 
806   // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end.
807   EXPECT_TRUE(hasADbgVal({DW_OP_dup, DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0,
808                           DW_OP_not, DW_OP_mul, DW_OP_or, DW_OP_stack_value,
809                           DW_OP_LLVM_fragment, 0, 8}));
810   EXPECT_TRUE(
811       hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, DW_OP_dup, DW_OP_constu,
812                   31, DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
813                   DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
814   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_dup, DW_OP_constu, 31,
815                           DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
816                           DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
817 
818   verifyModule(*M, &errs(), &BrokenDebugInfo);
819   ASSERT_FALSE(BrokenDebugInfo);
820 }
821 
822 TEST(Local, RemoveUnreachableBlocks) {
823   LLVMContext C;
824 
825   std::unique_ptr<Module> M = parseIR(C,
826                                       R"(
827       define void @br_simple() {
828       entry:
829         br label %bb0
830       bb0:
831         ret void
832       bb1:
833         ret void
834       }
835 
836       define void @br_self_loop() {
837       entry:
838         br label %bb0
839       bb0:
840         br i1 true, label %bb1, label %bb0
841       bb1:
842         br i1 true, label %bb0, label %bb2
843       bb2:
844         br label %bb2
845       }
846 
847       define void @br_constant() {
848       entry:
849         br label %bb0
850       bb0:
851         br i1 true, label %bb1, label %bb2
852       bb1:
853         br i1 true, label %bb0, label %bb2
854       bb2:
855         br label %bb2
856       }
857 
858       define void @br_loop() {
859       entry:
860         br label %bb0
861       bb0:
862         br label %bb0
863       bb1:
864         br label %bb2
865       bb2:
866         br label %bb1
867       }
868       )");
869 
870   auto runEager = [&](Function &F, DominatorTree *DT) {
871     PostDominatorTree PDT = PostDominatorTree(F);
872     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
873     removeUnreachableBlocks(F, nullptr, &DTU);
874     EXPECT_TRUE(DTU.getDomTree().verify());
875     EXPECT_TRUE(DTU.getPostDomTree().verify());
876   };
877 
878   auto runLazy = [&](Function &F, DominatorTree *DT) {
879     PostDominatorTree PDT = PostDominatorTree(F);
880     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
881     removeUnreachableBlocks(F, nullptr, &DTU);
882     EXPECT_TRUE(DTU.getDomTree().verify());
883     EXPECT_TRUE(DTU.getPostDomTree().verify());
884   };
885 
886   // Test removeUnreachableBlocks under Eager UpdateStrategy.
887   runWithDomTree(*M, "br_simple", runEager);
888   runWithDomTree(*M, "br_self_loop", runEager);
889   runWithDomTree(*M, "br_constant", runEager);
890   runWithDomTree(*M, "br_loop", runEager);
891 
892   // Test removeUnreachableBlocks under Lazy UpdateStrategy.
893   runWithDomTree(*M, "br_simple", runLazy);
894   runWithDomTree(*M, "br_self_loop", runLazy);
895   runWithDomTree(*M, "br_constant", runLazy);
896   runWithDomTree(*M, "br_loop", runLazy);
897 
898   M = parseIR(C,
899               R"(
900       define void @f() {
901       entry:
902         ret void
903       bb0:
904         ret void
905       }
906         )");
907 
908   auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) {
909     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
910     EXPECT_TRUE(removeUnreachableBlocks(F, nullptr, &DTU));
911     EXPECT_FALSE(removeUnreachableBlocks(F, nullptr, &DTU));
912     EXPECT_TRUE(DTU.getDomTree().verify());
913   };
914 
915   runWithDomTree(*M, "f", checkRUBlocksRetVal);
916 }
917