blob: 53cfc6b4a34b681b69e5b12e884a91b3fc17f828 [file] [log] [blame]
Nick Lewyckyc8a15692011-02-20 08:38:20 +00001//===- 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
David Blaikie31b98d22018-06-04 21:23:21 +000010#include "llvm/Transforms/Utils/Local.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000011#include "llvm/Analysis/PostDominators.h"
Reid Kleckner0fe506b2017-09-21 19:52:03 +000012#include "llvm/AsmParser/Parser.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000013#include "llvm/IR/BasicBlock.h"
Reid Kleckner0fe506b2017-09-21 19:52:03 +000014#include "llvm/IR/DIBuilder.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000015#include "llvm/IR/DomTreeUpdater.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/IRBuilder.h"
17#include "llvm/IR/Instructions.h"
Reid Kleckner0fe506b2017-09-21 19:52:03 +000018#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/LLVMContext.h"
Vedant Kumar6379a622018-07-06 17:32:39 +000020#include "llvm/IR/Verifier.h"
Reid Kleckner0fe506b2017-09-21 19:52:03 +000021#include "llvm/Support/SourceMgr.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000022#include "gtest/gtest.h"
23
Nick Lewyckyc8a15692011-02-20 08:38:20 +000024using namespace llvm;
25
26TEST(Local, RecursivelyDeleteDeadPHINodes) {
Mehdi Amini03b42e42016-04-14 21:59:01 +000027 LLVMContext C;
Nick Lewyckyc8a15692011-02-20 08:38:20 +000028
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);
Jay Foad52131342011-03-30 11:28:46 +000036 PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2);
Nick Lewyckyc8a15692011-02-20 08:38:20 +000037 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
Nick Lewycky183c24c2011-02-20 18:05:56 +000052 builder.SetInsertPoint(bb0);
Jay Foad52131342011-03-30 11:28:46 +000053 phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
Nick Lewycky183c24c2011-02-20 18:05:56 +000054
55 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
56
Duncan Sands6dcd49b2011-02-21 16:27:36 +000057 builder.SetInsertPoint(bb0);
Jay Foad52131342011-03-30 11:28:46 +000058 phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
Duncan Sands6dcd49b2011-02-21 16:27:36 +000059 builder.CreateAdd(phi, phi);
60
61 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
62
Nick Lewyckyc8a15692011-02-20 08:38:20 +000063 bb0->dropAllReferences();
64 bb1->dropAllReferences();
65 delete bb0;
66 delete bb1;
67}
Benjamin Kramerf175e042015-09-02 19:52:23 +000068
69TEST(Local, RemoveDuplicatePHINodes) {
Mehdi Amini03b42e42016-04-14 21:59:01 +000070 LLVMContext C;
Benjamin Kramerf175e042015-09-02 19:52:23 +000071 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}
Reid Kleckner0fe506b2017-09-21 19:52:03 +0000105
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000106static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
Reid Kleckner0fe506b2017-09-21 19:52:03 +0000107 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
114TEST(Local, ReplaceDbgDeclare) {
115 LLVMContext C;
116
117 // Original C source to get debug info for a local variable:
118 // void f() { int x; }
Vedant Kumar1425e042018-03-02 21:36:33 +0000119 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}
Shiva Chen2c864552018-05-09 02:40:45 +0000136 !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)
Vedant Kumar1425e042018-03-02 21:36:33 +0000137 !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 )");
Reid Kleckner0fe506b2017-09-21 19:52:03 +0000144 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);
Adrian Prantld1317012017-12-08 21:58:18 +0000157 replaceDbgDeclare(AI, NewBase, DII, DIB, DIExpression::NoDeref, 0,
158 DIExpression::NoDeref);
Reid Kleckner0fe506b2017-09-21 19:52:03 +0000159
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}
Balaram Makam9ee942f2017-10-26 15:04:53 +0000167
168/// Build the dominator tree for the function and run the Test.
169static 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
179TEST(Local, MergeBasicBlockIntoOnlyPred) {
180 LLVMContext C;
Chijun Sima21a8b602018-08-03 05:08:17 +0000181 std::unique_ptr<Module> M;
182 auto resetIR = [&]() {
183 M = parseIR(C,
184 R"(
Vedant Kumar1425e042018-03-02 21:36:33 +0000185 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 )");
Chijun Sima21a8b602018-08-03 05:08:17 +0000201 };
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 if (DTU.hasPostDomTree())
228 EXPECT_TRUE(DTU.getPostDomTree().verify());
229 };
230
231 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
232 // both DT and PDT.
233 resetIR();
234 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
235 PostDominatorTree PDT = PostDominatorTree(F);
236 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
237 Test(F, DTU);
238 });
239
240 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
241 // DT.
242 resetIR();
243 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
244 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
245 Test(F, DTU);
246 });
247
248 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
249 // PDT.
250 resetIR();
251 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
252 PostDominatorTree PDT = PostDominatorTree(F);
253 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager);
254 Test(F, DTU);
255 });
256
257 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
258 // both DT and PDT.
259 resetIR();
260 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
261 PostDominatorTree PDT = PostDominatorTree(F);
262 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
263 Test(F, DTU);
264 });
265
266 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
267 // PDT.
268 resetIR();
269 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
270 PostDominatorTree PDT = PostDominatorTree(F);
271 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy);
272 Test(F, DTU);
273 });
274
275 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT.
276 resetIR();
277 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
278 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
279 Test(F, DTU);
280 });
281
282 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
283 // both DT and PDT.
284 resetIRReplaceEntry();
285 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
286 PostDominatorTree PDT = PostDominatorTree(F);
287 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
288 Test(F, DTU);
289 });
290
291 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
292 // DT.
293 resetIRReplaceEntry();
294 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
295 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
296 Test(F, DTU);
297 });
298
299 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with
300 // PDT.
301 resetIRReplaceEntry();
302 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
303 PostDominatorTree PDT = PostDominatorTree(F);
304 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager);
305 Test(F, DTU);
306 });
307
308 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
309 // both DT and PDT.
310 resetIRReplaceEntry();
311 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
312 PostDominatorTree PDT = PostDominatorTree(F);
313 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
314 Test(F, DTU);
315 });
316
317 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with
318 // PDT.
319 resetIRReplaceEntry();
320 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
321 PostDominatorTree PDT = PostDominatorTree(F);
322 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy);
323 Test(F, DTU);
324 });
325
326 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT.
327 resetIRReplaceEntry();
328 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) {
329 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
330 Test(F, DTU);
331 });
Balaram Makam9ee942f2017-10-26 15:04:53 +0000332}
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000333
334TEST(Local, ConstantFoldTerminator) {
335 LLVMContext C;
336
Vedant Kumar1425e042018-03-02 21:36:33 +0000337 std::unique_ptr<Module> M = parseIR(C,
338 R"(
339 define void @br_same_dest() {
340 entry:
341 br i1 false, label %bb0, label %bb0
342 bb0:
343 ret void
344 }
345
346 define void @br_different_dest() {
347 entry:
348 br i1 true, label %bb0, label %bb1
349 bb0:
350 br label %exit
351 bb1:
352 br label %exit
353 exit:
354 ret void
355 }
356
357 define void @switch_2_different_dest() {
358 entry:
359 switch i32 0, label %default [ i32 0, label %bb0 ]
360 default:
361 ret void
362 bb0:
363 ret void
364 }
365 define void @switch_2_different_dest_default() {
366 entry:
367 switch i32 1, label %default [ i32 0, label %bb0 ]
368 default:
369 ret void
370 bb0:
371 ret void
372 }
373 define void @switch_3_different_dest() {
374 entry:
375 switch i32 0, label %default [ i32 0, label %bb0
376 i32 1, label %bb1 ]
377 default:
378 ret void
379 bb0:
380 ret void
381 bb1:
382 ret void
383 }
384
385 define void @switch_variable_2_default_dest(i32 %arg) {
386 entry:
387 switch i32 %arg, label %default [ i32 0, label %default ]
388 default:
389 ret void
390 }
391
392 define void @switch_constant_2_default_dest() {
393 entry:
394 switch i32 1, label %default [ i32 0, label %default ]
395 default:
396 ret void
397 }
398
399 define void @switch_constant_3_repeated_dest() {
400 entry:
401 switch i32 0, label %default [ i32 0, label %bb0
402 i32 1, label %bb0 ]
403 bb0:
404 ret void
405 default:
406 ret void
407 }
408
409 define void @indirectbr() {
410 entry:
411 indirectbr i8* blockaddress(@indirectbr, %bb0), [label %bb0, label %bb1]
412 bb0:
413 ret void
414 bb1:
415 ret void
416 }
417
418 define void @indirectbr_repeated() {
419 entry:
420 indirectbr i8* blockaddress(@indirectbr_repeated, %bb0), [label %bb0, label %bb0]
421 bb0:
422 ret void
423 }
424
425 define void @indirectbr_unreachable() {
426 entry:
427 indirectbr i8* blockaddress(@indirectbr_unreachable, %bb0), [label %bb1]
428 bb0:
429 ret void
430 bb1:
431 ret void
432 }
433 )");
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000434
Chijun Sima21a8b602018-08-03 05:08:17 +0000435 auto CFAllTerminatorsEager = [&](Function &F, DominatorTree *DT) {
436 PostDominatorTree PDT = PostDominatorTree(F);
437 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000438 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
439 BasicBlock *BB = &*I++;
Chijun Sima21a8b602018-08-03 05:08:17 +0000440 ConstantFoldTerminator(BB, true, nullptr, &DTU);
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000441 }
442
Chijun Sima21a8b602018-08-03 05:08:17 +0000443 EXPECT_TRUE(DTU.getDomTree().verify());
444 EXPECT_TRUE(DTU.getPostDomTree().verify());
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000445 };
446
Chijun Sima21a8b602018-08-03 05:08:17 +0000447 auto CFAllTerminatorsLazy = [&](Function &F, DominatorTree *DT) {
448 PostDominatorTree PDT = PostDominatorTree(F);
449 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
450 for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
451 BasicBlock *BB = &*I++;
452 ConstantFoldTerminator(BB, true, nullptr, &DTU);
453 }
454
455 EXPECT_TRUE(DTU.getDomTree().verify());
456 EXPECT_TRUE(DTU.getPostDomTree().verify());
457 };
458
459 // Test ConstantFoldTerminator under Eager UpdateStrategy.
460 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsEager);
461 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsEager);
462 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsEager);
463 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsEager);
464 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsEager);
465 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsEager);
466 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsEager);
467 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsEager);
468 runWithDomTree(*M, "indirectbr", CFAllTerminatorsEager);
469 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsEager);
470 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsEager);
471
472 // Test ConstantFoldTerminator under Lazy UpdateStrategy.
473 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsLazy);
474 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsLazy);
475 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsLazy);
476 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsLazy);
477 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsLazy);
478 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsLazy);
479 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsLazy);
480 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsLazy);
481 runWithDomTree(*M, "indirectbr", CFAllTerminatorsLazy);
482 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsLazy);
483 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsLazy);
Matt Arsenault0cfebd92018-01-17 16:27:17 +0000484}
Vedant Kumar334fa572018-03-02 21:36:35 +0000485
Vedant Kumarf69baf62018-03-02 22:46:48 +0000486struct SalvageDebugInfoTest : ::testing::Test {
Vedant Kumar334fa572018-03-02 21:36:35 +0000487 LLVMContext C;
Vedant Kumarf69baf62018-03-02 22:46:48 +0000488 std::unique_ptr<Module> M;
489 Function *F = nullptr;
Vedant Kumar334fa572018-03-02 21:36:35 +0000490
Vedant Kumarf69baf62018-03-02 22:46:48 +0000491 void SetUp() {
492 M = parseIR(C,
493 R"(
Vedant Kumar334fa572018-03-02 21:36:35 +0000494 define void @f() !dbg !8 {
495 entry:
496 %x = add i32 0, 1
497 %y = add i32 %x, 2
498 call void @llvm.dbg.value(metadata i32 %x, metadata !11, metadata !DIExpression()), !dbg !13
499 call void @llvm.dbg.value(metadata i32 %y, metadata !11, metadata !DIExpression()), !dbg !13
500 ret void, !dbg !14
501 }
502 declare void @llvm.dbg.value(metadata, metadata, metadata)
503 !llvm.dbg.cu = !{!0}
504 !llvm.module.flags = !{!3, !4}
505 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
506 !1 = !DIFile(filename: "t2.c", directory: "foo")
507 !2 = !{}
508 !3 = !{i32 2, !"Dwarf Version", i32 4}
509 !4 = !{i32 2, !"Debug Info Version", i32 3}
Shiva Chen2c864552018-05-09 02:40:45 +0000510 !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)
Vedant Kumar334fa572018-03-02 21:36:35 +0000511 !9 = !DISubroutineType(types: !10)
512 !10 = !{null}
513 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
514 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
515 !13 = !DILocation(line: 2, column: 7, scope: !8)
516 !14 = !DILocation(line: 3, column: 1, scope: !8)
517 )");
Vedant Kumarf69baf62018-03-02 22:46:48 +0000518
519 auto *GV = M->getNamedValue("f");
520 ASSERT_TRUE(GV);
521 F = dyn_cast<Function>(GV);
522 ASSERT_TRUE(F);
523 }
524
525 bool doesDebugValueDescribeX(const DbgValueInst &DI) {
526 const auto &CI = *cast<ConstantInt>(DI.getValue());
527 if (CI.isZero())
528 return DI.getExpression()->getElements().equals(
529 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value});
530 else if (CI.isOneValue())
531 return DI.getExpression()->getElements().empty();
532 return false;
533 }
534
535 bool doesDebugValueDescribeY(const DbgValueInst &DI) {
536 const auto &CI = *cast<ConstantInt>(DI.getValue());
537 if (CI.isZero())
538 return DI.getExpression()->getElements().equals(
539 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2,
540 dwarf::DW_OP_stack_value});
541 else if (CI.isOneValue())
542 return DI.getExpression()->getElements().equals(
543 {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value});
544 return false;
545 }
546
547 void verifyDebugValuesAreSalvaged() {
548 // Check that the debug values for %x and %y are preserved.
549 bool FoundX = false;
550 bool FoundY = false;
551 for (const Instruction &I : F->front()) {
552 auto DI = dyn_cast<DbgValueInst>(&I);
553 if (!DI) {
554 // The function should only contain debug values and a terminator.
555 ASSERT_TRUE(isa<TerminatorInst>(&I));
556 continue;
557 }
558 EXPECT_EQ(DI->getVariable()->getName(), "x");
559 FoundX |= doesDebugValueDescribeX(*DI);
560 FoundY |= doesDebugValueDescribeY(*DI);
561 }
562 ASSERT_TRUE(FoundX);
563 ASSERT_TRUE(FoundY);
564 }
565};
566
567TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) {
Vedant Kumar334fa572018-03-02 21:36:35 +0000568 Instruction *Inst = &F->front().front();
Vedant Kumarf69baf62018-03-02 22:46:48 +0000569 Inst = Inst->getNextNode(); // Get %y = add ...
Vedant Kumar334fa572018-03-02 21:36:35 +0000570 ASSERT_TRUE(Inst);
571 bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst);
572 ASSERT_TRUE(Deleted);
Vedant Kumarf69baf62018-03-02 22:46:48 +0000573 verifyDebugValuesAreSalvaged();
574}
Vedant Kumar334fa572018-03-02 21:36:35 +0000575
Vedant Kumarf69baf62018-03-02 22:46:48 +0000576TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) {
577 BasicBlock *BB = &F->front();
578 ASSERT_TRUE(BB);
579 bool Deleted = SimplifyInstructionsInBlock(BB);
580 ASSERT_TRUE(Deleted);
581 verifyDebugValuesAreSalvaged();
Vedant Kumar334fa572018-03-02 21:36:35 +0000582}
Vedant Kumar6379a622018-07-06 17:32:39 +0000583
584TEST(Local, ReplaceAllDbgUsesWith) {
585 using namespace llvm::dwarf;
586
587 LLVMContext Ctx;
588
589 // Note: The datalayout simulates Darwin/x86_64.
590 std::unique_ptr<Module> M = parseIR(Ctx,
591 R"(
592 target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128"
593
594 declare i32 @escape(i32)
595
596 define void @f() !dbg !6 {
597 entry:
598 %a = add i32 0, 1, !dbg !15
599 call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15
600
601 %b = add i64 0, 1, !dbg !16
602 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16
603 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16
604 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16
605 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16
606 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
607 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
608
609 %c = inttoptr i64 0 to i64*, !dbg !17
610 call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17
611
612 %d = inttoptr i64 0 to i32*, !dbg !18
613 call void @llvm.dbg.addr(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18
614
615 %e = add <2 x i16> zeroinitializer, zeroinitializer
616 call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18
617
618 %f = call i32 @escape(i32 0)
619 call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15
620
621 %barrier = call i32 @escape(i32 0)
622
623 %g = call i32 @escape(i32 %f)
624 call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15
625
626 ret void, !dbg !19
627 }
628
629 declare void @llvm.dbg.addr(metadata, metadata, metadata)
630 declare void @llvm.dbg.declare(metadata, metadata, metadata)
631 declare void @llvm.dbg.value(metadata, metadata, metadata)
632
633 !llvm.dbg.cu = !{!0}
634 !llvm.module.flags = !{!5}
635
636 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
637 !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/")
638 !2 = !{}
639 !5 = !{i32 2, !"Debug Info Version", i32 3}
640 !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)
641 !7 = !DISubroutineType(types: !2)
642 !8 = !{!9, !11, !13, !14}
643 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
644 !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed)
645 !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12)
646 !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed)
647 !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12)
648 !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10)
649 !15 = !DILocation(line: 1, column: 1, scope: !6)
650 !16 = !DILocation(line: 2, column: 1, scope: !6)
651 !17 = !DILocation(line: 3, column: 1, scope: !6)
652 !18 = !DILocation(line: 4, column: 1, scope: !6)
653 !19 = !DILocation(line: 5, column: 1, scope: !6)
654 !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10)
655 )");
656
657 bool BrokenDebugInfo = true;
658 verifyModule(*M, &errs(), &BrokenDebugInfo);
659 ASSERT_FALSE(BrokenDebugInfo);
660
661 Function &F = *cast<Function>(M->getNamedValue("f"));
662 DominatorTree DT{F};
663
664 BasicBlock &BB = F.front();
665 Instruction &A = BB.front();
666 Instruction &B = *A.getNextNonDebugInstruction();
667 Instruction &C = *B.getNextNonDebugInstruction();
668 Instruction &D = *C.getNextNonDebugInstruction();
669 Instruction &E = *D.getNextNonDebugInstruction();
670 Instruction &F_ = *E.getNextNonDebugInstruction();
671 Instruction &Barrier = *F_.getNextNonDebugInstruction();
672 Instruction &G = *Barrier.getNextNonDebugInstruction();
673
674 // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says
675 // pointers are 64 bits, so the conversion would be lossy.
676 EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT));
677 EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT));
678
679 // Simulate i32 <-> <2 x i16> conversion. This is unsupported.
680 EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT));
681 EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT));
682
683 // Simulate i32* <-> i64* conversion.
684 EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT));
685
686 SmallVector<DbgInfoIntrinsic *, 2> CDbgVals;
687 findDbgUsers(CDbgVals, &C);
688 EXPECT_EQ(2U, CDbgVals.size());
689 EXPECT_TRUE(any_of(CDbgVals, [](DbgInfoIntrinsic *DII) {
690 return isa<DbgAddrIntrinsic>(DII);
691 }));
692 EXPECT_TRUE(any_of(CDbgVals, [](DbgInfoIntrinsic *DII) {
693 return isa<DbgDeclareInst>(DII);
694 }));
695
696 EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT));
697
698 SmallVector<DbgInfoIntrinsic *, 2> DDbgVals;
699 findDbgUsers(DDbgVals, &D);
700 EXPECT_EQ(2U, DDbgVals.size());
701 EXPECT_TRUE(any_of(DDbgVals, [](DbgInfoIntrinsic *DII) {
702 return isa<DbgAddrIntrinsic>(DII);
703 }));
704 EXPECT_TRUE(any_of(DDbgVals, [](DbgInfoIntrinsic *DII) {
705 return isa<DbgDeclareInst>(DII);
706 }));
707
708 // Introduce a use-before-def. Check that the dbg.value for %a is salvaged.
709 EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT));
710
711 auto *ADbgVal = cast<DbgValueInst>(A.getNextNode());
712 EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocation());
713
714 // Introduce a use-before-def. Check that the dbg.values for %f are deleted.
715 EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT));
716
717 SmallVector<DbgValueInst *, 1> FDbgVals;
718 findDbgValues(FDbgVals, &F);
719 EXPECT_EQ(0U, FDbgVals.size());
720
721 // Simulate i32 -> i64 conversion to test sign-extension. Here are some
722 // interesting cases to handle:
723 // 1) debug user has empty DIExpression
724 // 2) debug user has non-empty, non-stack-value'd DIExpression
725 // 3) debug user has non-empty, stack-value'd DIExpression
726 // 4-6) like (1-3), but with a fragment
727 EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT));
728
729 SmallVector<DbgValueInst *, 8> ADbgVals;
730 findDbgValues(ADbgVals, &A);
731 EXPECT_EQ(6U, ADbgVals.size());
732
733 // Check that %a has a dbg.value with a DIExpression matching \p Ops.
734 auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) {
735 return any_of(ADbgVals, [&](DbgValueInst *DVI) {
736 assert(DVI->getVariable()->getName() == "2");
737 return DVI->getExpression()->getElements() == Ops;
738 });
739 };
740
741 // Case 1: The original expr is empty, so no deref is needed.
742 EXPECT_TRUE(hasADbgVal({DW_OP_dup, DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0,
743 DW_OP_not, DW_OP_mul, DW_OP_or, DW_OP_stack_value}));
744
745 // Case 2: Perform an address calculation with the original expr, deref it,
746 // then sign-extend the result.
747 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, DW_OP_dup,
748 DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0, DW_OP_not,
749 DW_OP_mul, DW_OP_or, DW_OP_stack_value}));
750
751 // Case 3: Insert the sign-extension logic before the DW_OP_stack_value.
752 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_dup, DW_OP_constu, 31,
753 DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
754 DW_OP_stack_value}));
755
756 // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end.
757 EXPECT_TRUE(hasADbgVal({DW_OP_dup, DW_OP_constu, 31, DW_OP_shr, DW_OP_lit0,
758 DW_OP_not, DW_OP_mul, DW_OP_or, DW_OP_stack_value,
759 DW_OP_LLVM_fragment, 0, 8}));
760 EXPECT_TRUE(
761 hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, DW_OP_dup, DW_OP_constu,
762 31, DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
763 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
764 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_dup, DW_OP_constu, 31,
765 DW_OP_shr, DW_OP_lit0, DW_OP_not, DW_OP_mul, DW_OP_or,
766 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
767
768 verifyModule(*M, &errs(), &BrokenDebugInfo);
769 ASSERT_FALSE(BrokenDebugInfo);
770}
Chijun Sima21a8b602018-08-03 05:08:17 +0000771
772TEST(Local, RemoveUnreachableBlocks) {
773 LLVMContext C;
774
775 std::unique_ptr<Module> M = parseIR(C,
776 R"(
777 define void @br_simple() {
778 entry:
779 br label %bb0
780 bb0:
781 ret void
782 bb1:
783 ret void
784 }
785
786 define void @br_self_loop() {
787 entry:
788 br label %bb0
789 bb0:
790 br i1 true, label %bb1, label %bb0
791 bb1:
792 br i1 true, label %bb0, label %bb2
793 bb2:
794 br label %bb2
795 }
796
797 define void @br_constant() {
798 entry:
799 br label %bb0
800 bb0:
801 br i1 true, label %bb1, label %bb2
802 bb1:
803 br i1 true, label %bb0, label %bb2
804 bb2:
805 br label %bb2
806 }
807
808 define void @br_loop() {
809 entry:
810 br label %bb0
811 bb0:
812 br label %bb0
813 bb1:
814 br label %bb2
815 bb2:
816 br label %bb1
817 }
818 )");
819
820 auto runEager = [&](Function &F, DominatorTree *DT) {
821 PostDominatorTree PDT = PostDominatorTree(F);
822 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
823 removeUnreachableBlocks(F, nullptr, &DTU);
824 EXPECT_TRUE(DTU.getDomTree().verify());
825 EXPECT_TRUE(DTU.getPostDomTree().verify());
826 };
827
828 auto runLazy = [&](Function &F, DominatorTree *DT) {
829 PostDominatorTree PDT = PostDominatorTree(F);
830 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
831 removeUnreachableBlocks(F, nullptr, &DTU);
832 EXPECT_TRUE(DTU.getDomTree().verify());
833 EXPECT_TRUE(DTU.getPostDomTree().verify());
834 };
835
836 // Test removeUnreachableBlocks under Eager UpdateStrategy.
837 runWithDomTree(*M, "br_simple", runEager);
838 runWithDomTree(*M, "br_self_loop", runEager);
839 runWithDomTree(*M, "br_constant", runEager);
840 runWithDomTree(*M, "br_loop", runEager);
841
842 // Test removeUnreachableBlocks under Lazy UpdateStrategy.
843 runWithDomTree(*M, "br_simple", runLazy);
844 runWithDomTree(*M, "br_self_loop", runLazy);
845 runWithDomTree(*M, "br_constant", runLazy);
846 runWithDomTree(*M, "br_loop", runLazy);
Chijun Sima53048432018-08-03 12:45:29 +0000847
848 M = parseIR(C,
849 R"(
850 define void @f() {
851 entry:
852 ret void
853 bb0:
854 ret void
855 }
856 )");
857
858 auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) {
859 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
860 EXPECT_TRUE(removeUnreachableBlocks(F, nullptr, &DTU));
861 EXPECT_FALSE(removeUnreachableBlocks(F, nullptr, &DTU));
862 EXPECT_TRUE(DTU.getDomTree().verify());
863 };
864
865 runWithDomTree(*M, "f", checkRUBlocksRetVal);
Chijun Sima21a8b602018-08-03 05:08:17 +0000866}