1 //===- Local.cpp - Unit tests for Local -----------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Transforms/Utils/Local.h" 10 #include "llvm/ADT/ScopeExit.h" 11 #include "llvm/Analysis/DomTreeUpdater.h" 12 #include "llvm/Analysis/InstructionSimplify.h" 13 #include "llvm/Analysis/PostDominators.h" 14 #include "llvm/Analysis/TargetTransformInfo.h" 15 #include "llvm/AsmParser/Parser.h" 16 #include "llvm/IR/BasicBlock.h" 17 #include "llvm/IR/DIBuilder.h" 18 #include "llvm/IR/DebugInfo.h" 19 #include "llvm/IR/DebugProgramInstruction.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/Verifier.h" 25 #include "llvm/Support/SourceMgr.h" 26 #include "gtest/gtest.h" 27 28 using namespace llvm; 29 30 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 31 extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat; 32 extern bool WriteNewDbgInfoFormatToBitcode; 33 extern cl::opt<bool> WriteNewDbgInfoFormat; 34 35 // Backup all of the existing settings that may be modified when 36 // PreserveInputDbgFormat=true, so that when the test is finished we return them 37 // (and the "preserve" setting) to their original values. 38 static auto SaveDbgInfoFormat() { 39 return make_scope_exit( 40 [OldPreserveInputDbgFormat = PreserveInputDbgFormat.getValue(), 41 OldUseNewDbgInfoFormat = UseNewDbgInfoFormat.getValue(), 42 OldWriteNewDbgInfoFormatToBitcode = WriteNewDbgInfoFormatToBitcode, 43 OldWriteNewDbgInfoFormat = WriteNewDbgInfoFormat.getValue()] { 44 PreserveInputDbgFormat = OldPreserveInputDbgFormat; 45 UseNewDbgInfoFormat = OldUseNewDbgInfoFormat; 46 WriteNewDbgInfoFormatToBitcode = OldWriteNewDbgInfoFormatToBitcode; 47 WriteNewDbgInfoFormat = OldWriteNewDbgInfoFormat; 48 }); 49 } 50 51 TEST(Local, RecursivelyDeleteDeadPHINodes) { 52 LLVMContext C; 53 54 IRBuilder<> builder(C); 55 56 // Make blocks 57 BasicBlock *bb0 = BasicBlock::Create(C); 58 BasicBlock *bb1 = BasicBlock::Create(C); 59 60 builder.SetInsertPoint(bb0); 61 PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2); 62 BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1); 63 64 builder.SetInsertPoint(bb1); 65 BranchInst *br1 = builder.CreateBr(bb0); 66 67 phi->addIncoming(phi, bb0); 68 phi->addIncoming(phi, bb1); 69 70 // The PHI will be removed 71 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 72 73 // Make sure the blocks only contain the branches 74 EXPECT_EQ(&bb0->front(), br0); 75 EXPECT_EQ(&bb1->front(), br1); 76 77 builder.SetInsertPoint(bb0); 78 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 79 80 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 81 82 builder.SetInsertPoint(bb0); 83 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 84 builder.CreateAdd(phi, phi); 85 86 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 87 88 bb0->dropAllReferences(); 89 bb1->dropAllReferences(); 90 delete bb0; 91 delete bb1; 92 } 93 94 TEST(Local, RemoveDuplicatePHINodes) { 95 LLVMContext C; 96 IRBuilder<> B(C); 97 98 std::unique_ptr<Function> F( 99 Function::Create(FunctionType::get(B.getVoidTy(), false), 100 GlobalValue::ExternalLinkage, "F")); 101 BasicBlock *Entry(BasicBlock::Create(C, "", F.get())); 102 BasicBlock *BB(BasicBlock::Create(C, "", F.get())); 103 BranchInst::Create(BB, Entry); 104 105 B.SetInsertPoint(BB); 106 107 AssertingVH<PHINode> P1 = B.CreatePHI(Type::getInt32Ty(C), 2); 108 P1->addIncoming(B.getInt32(42), Entry); 109 110 PHINode *P2 = B.CreatePHI(Type::getInt32Ty(C), 2); 111 P2->addIncoming(B.getInt32(42), Entry); 112 113 AssertingVH<PHINode> P3 = B.CreatePHI(Type::getInt32Ty(C), 2); 114 P3->addIncoming(B.getInt32(42), Entry); 115 P3->addIncoming(B.getInt32(23), BB); 116 117 PHINode *P4 = B.CreatePHI(Type::getInt32Ty(C), 2); 118 P4->addIncoming(B.getInt32(42), Entry); 119 P4->addIncoming(B.getInt32(23), BB); 120 121 P1->addIncoming(P3, BB); 122 P2->addIncoming(P4, BB); 123 BranchInst::Create(BB, BB); 124 125 // Verify that we can eliminate PHIs that become duplicates after chaning PHIs 126 // downstream. 127 EXPECT_TRUE(EliminateDuplicatePHINodes(BB)); 128 EXPECT_EQ(3U, BB->size()); 129 } 130 131 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) { 132 SMDiagnostic Err; 133 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C); 134 if (!Mod) 135 Err.print("UtilsTests", errs()); 136 return Mod; 137 } 138 139 TEST(Local, ReplaceDbgDeclare) { 140 LLVMContext C; 141 // FIXME: PreserveInputDbgFormat is set to true because this test has 142 // been written to expect debug intrinsics rather than debug records; use the 143 // intrinsic format until we update the test checks. 144 auto SettingGuard = SaveDbgInfoFormat(); 145 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 146 147 // Original C source to get debug info for a local variable: 148 // void f() { int x; } 149 std::unique_ptr<Module> M = parseIR(C, 150 R"( 151 define void @f() !dbg !8 { 152 entry: 153 %x = alloca i32, align 4 154 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 155 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 156 ret void, !dbg !14 157 } 158 declare void @llvm.dbg.declare(metadata, metadata, metadata) 159 !llvm.dbg.cu = !{!0} 160 !llvm.module.flags = !{!3, !4} 161 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 162 !1 = !DIFile(filename: "t2.c", directory: "foo") 163 !2 = !{} 164 !3 = !{i32 2, !"Dwarf Version", i32 4} 165 !4 = !{i32 2, !"Debug Info Version", i32 3} 166 !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) 167 !9 = !DISubroutineType(types: !10) 168 !10 = !{null} 169 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 170 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 171 !13 = !DILocation(line: 2, column: 7, scope: !8) 172 !14 = !DILocation(line: 3, column: 1, scope: !8) 173 )"); 174 auto *GV = M->getNamedValue("f"); 175 ASSERT_TRUE(GV); 176 auto *F = dyn_cast<Function>(GV); 177 ASSERT_TRUE(F); 178 Instruction *Inst = &F->front().front(); 179 auto *AI = dyn_cast<AllocaInst>(Inst); 180 ASSERT_TRUE(AI); 181 Inst = Inst->getNextNode()->getNextNode(); 182 ASSERT_TRUE(Inst); 183 auto *DII = dyn_cast<DbgDeclareInst>(Inst); 184 ASSERT_TRUE(DII); 185 Value *NewBase = Constant::getNullValue(PointerType::getUnqual(C)); 186 DIBuilder DIB(*M); 187 replaceDbgDeclare(AI, NewBase, DIB, DIExpression::ApplyOffset, 0); 188 189 // There should be exactly two dbg.declares. 190 int Declares = 0; 191 for (const Instruction &I : F->front()) 192 if (isa<DbgDeclareInst>(I)) 193 Declares++; 194 EXPECT_EQ(2, Declares); 195 } 196 197 /// Build the dominator tree for the function and run the Test. 198 static void runWithDomTree( 199 Module &M, StringRef FuncName, 200 function_ref<void(Function &F, DominatorTree *DT)> Test) { 201 auto *F = M.getFunction(FuncName); 202 ASSERT_NE(F, nullptr) << "Could not find " << FuncName; 203 // Compute the dominator tree for the function. 204 DominatorTree DT(*F); 205 Test(*F, &DT); 206 } 207 208 TEST(Local, MergeBasicBlockIntoOnlyPred) { 209 LLVMContext C; 210 std::unique_ptr<Module> M; 211 auto resetIR = [&]() { 212 M = parseIR(C, 213 R"( 214 define i32 @f(i8* %str) { 215 entry: 216 br label %bb2.i 217 bb2.i: ; preds = %bb4.i, %entry 218 br i1 false, label %bb4.i, label %base2flt.exit204 219 bb4.i: ; preds = %bb2.i 220 br i1 false, label %base2flt.exit204, label %bb2.i 221 bb10.i196.bb7.i197_crit_edge: ; No predecessors! 222 br label %bb7.i197 223 bb7.i197: ; preds = %bb10.i196.bb7.i197_crit_edge 224 %.reg2mem.0 = phi i32 [ %.reg2mem.0, %bb10.i196.bb7.i197_crit_edge ] 225 br i1 undef, label %base2flt.exit204, label %base2flt.exit204 226 base2flt.exit204: ; preds = %bb7.i197, %bb7.i197, %bb2.i, %bb4.i 227 ret i32 0 228 } 229 )"); 230 }; 231 232 auto resetIRReplaceEntry = [&]() { 233 M = parseIR(C, 234 R"( 235 define i32 @f() { 236 entry: 237 br label %bb2.i 238 bb2.i: ; preds = %entry 239 ret i32 0 240 } 241 )"); 242 }; 243 244 auto Test = [&](Function &F, DomTreeUpdater &DTU) { 245 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 246 BasicBlock *BB = &*I++; 247 BasicBlock *SinglePred = BB->getSinglePredecessor(); 248 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) 249 continue; 250 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); 251 if (Term && !Term->isConditional()) 252 MergeBasicBlockIntoOnlyPred(BB, &DTU); 253 } 254 if (DTU.hasDomTree()) { 255 EXPECT_TRUE(DTU.getDomTree().verify()); 256 } 257 if (DTU.hasPostDomTree()) { 258 EXPECT_TRUE(DTU.getPostDomTree().verify()); 259 } 260 }; 261 262 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 263 // both DT and PDT. 264 resetIR(); 265 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 266 PostDominatorTree PDT = PostDominatorTree(F); 267 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 268 Test(F, DTU); 269 }); 270 271 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 272 // DT. 273 resetIR(); 274 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 275 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 276 Test(F, DTU); 277 }); 278 279 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 280 // PDT. 281 resetIR(); 282 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 283 PostDominatorTree PDT = PostDominatorTree(F); 284 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 285 Test(F, DTU); 286 }); 287 288 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 289 // both DT and PDT. 290 resetIR(); 291 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 292 PostDominatorTree PDT = PostDominatorTree(F); 293 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 294 Test(F, DTU); 295 }); 296 297 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 298 // PDT. 299 resetIR(); 300 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 301 PostDominatorTree PDT = PostDominatorTree(F); 302 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 303 Test(F, DTU); 304 }); 305 306 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 307 resetIR(); 308 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 309 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 310 Test(F, DTU); 311 }); 312 313 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 314 // both DT and PDT. 315 resetIRReplaceEntry(); 316 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 317 PostDominatorTree PDT = PostDominatorTree(F); 318 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 319 Test(F, DTU); 320 }); 321 322 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 323 // DT. 324 resetIRReplaceEntry(); 325 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 326 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 327 Test(F, DTU); 328 }); 329 330 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 331 // PDT. 332 resetIRReplaceEntry(); 333 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 334 PostDominatorTree PDT = PostDominatorTree(F); 335 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 336 Test(F, DTU); 337 }); 338 339 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 340 // both DT and PDT. 341 resetIRReplaceEntry(); 342 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 343 PostDominatorTree PDT = PostDominatorTree(F); 344 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 345 Test(F, DTU); 346 }); 347 348 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 349 // PDT. 350 resetIRReplaceEntry(); 351 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 352 PostDominatorTree PDT = PostDominatorTree(F); 353 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 354 Test(F, DTU); 355 }); 356 357 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 358 resetIRReplaceEntry(); 359 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 360 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 361 Test(F, DTU); 362 }); 363 } 364 365 TEST(Local, ConstantFoldTerminator) { 366 LLVMContext C; 367 368 std::unique_ptr<Module> M = parseIR(C, 369 R"( 370 define void @br_same_dest() { 371 entry: 372 br i1 false, label %bb0, label %bb0 373 bb0: 374 ret void 375 } 376 377 define void @br_different_dest() { 378 entry: 379 br i1 true, label %bb0, label %bb1 380 bb0: 381 br label %exit 382 bb1: 383 br label %exit 384 exit: 385 ret void 386 } 387 388 define void @switch_2_different_dest() { 389 entry: 390 switch i32 0, label %default [ i32 0, label %bb0 ] 391 default: 392 ret void 393 bb0: 394 ret void 395 } 396 define void @switch_2_different_dest_default() { 397 entry: 398 switch i32 1, label %default [ i32 0, label %bb0 ] 399 default: 400 ret void 401 bb0: 402 ret void 403 } 404 define void @switch_3_different_dest() { 405 entry: 406 switch i32 0, label %default [ i32 0, label %bb0 407 i32 1, label %bb1 ] 408 default: 409 ret void 410 bb0: 411 ret void 412 bb1: 413 ret void 414 } 415 416 define void @switch_variable_2_default_dest(i32 %arg) { 417 entry: 418 switch i32 %arg, label %default [ i32 0, label %default ] 419 default: 420 ret void 421 } 422 423 define void @switch_constant_2_default_dest() { 424 entry: 425 switch i32 1, label %default [ i32 0, label %default ] 426 default: 427 ret void 428 } 429 430 define void @switch_constant_3_repeated_dest() { 431 entry: 432 switch i32 0, label %default [ i32 0, label %bb0 433 i32 1, label %bb0 ] 434 bb0: 435 ret void 436 default: 437 ret void 438 } 439 440 define void @indirectbr() { 441 entry: 442 indirectbr i8* blockaddress(@indirectbr, %bb0), [label %bb0, label %bb1] 443 bb0: 444 ret void 445 bb1: 446 ret void 447 } 448 449 define void @indirectbr_repeated() { 450 entry: 451 indirectbr i8* blockaddress(@indirectbr_repeated, %bb0), [label %bb0, label %bb0] 452 bb0: 453 ret void 454 } 455 456 define void @indirectbr_unreachable() { 457 entry: 458 indirectbr i8* blockaddress(@indirectbr_unreachable, %bb0), [label %bb1] 459 bb0: 460 ret void 461 bb1: 462 ret void 463 } 464 )"); 465 466 auto CFAllTerminatorsEager = [&](Function &F, DominatorTree *DT) { 467 PostDominatorTree PDT = PostDominatorTree(F); 468 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 469 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 470 BasicBlock *BB = &*I++; 471 ConstantFoldTerminator(BB, true, nullptr, &DTU); 472 } 473 474 EXPECT_TRUE(DTU.getDomTree().verify()); 475 EXPECT_TRUE(DTU.getPostDomTree().verify()); 476 }; 477 478 auto CFAllTerminatorsLazy = [&](Function &F, DominatorTree *DT) { 479 PostDominatorTree PDT = PostDominatorTree(F); 480 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 481 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 482 BasicBlock *BB = &*I++; 483 ConstantFoldTerminator(BB, true, nullptr, &DTU); 484 } 485 486 EXPECT_TRUE(DTU.getDomTree().verify()); 487 EXPECT_TRUE(DTU.getPostDomTree().verify()); 488 }; 489 490 // Test ConstantFoldTerminator under Eager UpdateStrategy. 491 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsEager); 492 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsEager); 493 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsEager); 494 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsEager); 495 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsEager); 496 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsEager); 497 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsEager); 498 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsEager); 499 runWithDomTree(*M, "indirectbr", CFAllTerminatorsEager); 500 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsEager); 501 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsEager); 502 503 // Test ConstantFoldTerminator under Lazy UpdateStrategy. 504 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsLazy); 505 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsLazy); 506 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsLazy); 507 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsLazy); 508 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsLazy); 509 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsLazy); 510 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsLazy); 511 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsLazy); 512 runWithDomTree(*M, "indirectbr", CFAllTerminatorsLazy); 513 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsLazy); 514 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsLazy); 515 } 516 517 struct SalvageDebugInfoTest : ::testing::Test { 518 LLVMContext C; 519 std::unique_ptr<Module> M; 520 Function *F = nullptr; 521 522 void SetUp() override { 523 // FIXME: PreserveInputDbgFormat is set to true because this test has 524 // been written to expect debug intrinsics rather than debug records; use 525 // the intrinsic format until we update the test checks. Note that the 526 // temporary setting of this flag only needs to cover the parsing step, not 527 // the test body itself. 528 auto SettingGuard = SaveDbgInfoFormat(); 529 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 530 531 M = parseIR(C, 532 R"( 533 define void @f() !dbg !8 { 534 entry: 535 %x = add i32 0, 1 536 %y = add i32 %x, 2 537 call void @llvm.dbg.value(metadata i32 %x, metadata !11, metadata !DIExpression()), !dbg !13 538 call void @llvm.dbg.value(metadata i32 %y, metadata !11, metadata !DIExpression()), !dbg !13 539 ret void, !dbg !14 540 } 541 declare void @llvm.dbg.value(metadata, metadata, metadata) 542 !llvm.dbg.cu = !{!0} 543 !llvm.module.flags = !{!3, !4} 544 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 545 !1 = !DIFile(filename: "t2.c", directory: "foo") 546 !2 = !{} 547 !3 = !{i32 2, !"Dwarf Version", i32 4} 548 !4 = !{i32 2, !"Debug Info Version", i32 3} 549 !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) 550 !9 = !DISubroutineType(types: !10) 551 !10 = !{null} 552 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 553 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 554 !13 = !DILocation(line: 2, column: 7, scope: !8) 555 !14 = !DILocation(line: 3, column: 1, scope: !8) 556 )"); 557 558 auto *GV = M->getNamedValue("f"); 559 ASSERT_TRUE(GV); 560 F = dyn_cast<Function>(GV); 561 ASSERT_TRUE(F); 562 } 563 564 bool doesDebugValueDescribeX(const DbgValueInst &DI) { 565 if (DI.getNumVariableLocationOps() != 1u) 566 return false; 567 const auto &CI = *cast<ConstantInt>(DI.getValue(0)); 568 if (CI.isZero()) 569 return DI.getExpression()->getElements().equals( 570 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value}); 571 else if (CI.isOneValue()) 572 return DI.getExpression()->getElements().empty(); 573 return false; 574 } 575 576 bool doesDebugValueDescribeY(const DbgValueInst &DI) { 577 if (DI.getNumVariableLocationOps() != 1u) 578 return false; 579 const auto &CI = *cast<ConstantInt>(DI.getVariableLocationOp(0)); 580 if (CI.isZero()) 581 return DI.getExpression()->getElements().equals( 582 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2, 583 dwarf::DW_OP_stack_value}); 584 else if (CI.isOneValue()) 585 return DI.getExpression()->getElements().equals( 586 {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value}); 587 return false; 588 } 589 590 void verifyDebugValuesAreSalvaged() { 591 // Check that the debug values for %x and %y are preserved. 592 bool FoundX = false; 593 bool FoundY = false; 594 for (const Instruction &I : F->front()) { 595 auto DI = dyn_cast<DbgValueInst>(&I); 596 if (!DI) { 597 // The function should only contain debug values and a terminator. 598 ASSERT_TRUE(I.isTerminator()); 599 continue; 600 } 601 EXPECT_EQ(DI->getVariable()->getName(), "x"); 602 FoundX |= doesDebugValueDescribeX(*DI); 603 FoundY |= doesDebugValueDescribeY(*DI); 604 } 605 ASSERT_TRUE(FoundX); 606 ASSERT_TRUE(FoundY); 607 } 608 }; 609 610 TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) { 611 Instruction *Inst = &F->front().front(); 612 Inst = Inst->getNextNode(); // Get %y = add ... 613 ASSERT_TRUE(Inst); 614 bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst); 615 ASSERT_TRUE(Deleted); 616 verifyDebugValuesAreSalvaged(); 617 } 618 619 TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) { 620 BasicBlock *BB = &F->front(); 621 ASSERT_TRUE(BB); 622 bool Deleted = SimplifyInstructionsInBlock(BB); 623 ASSERT_TRUE(Deleted); 624 verifyDebugValuesAreSalvaged(); 625 } 626 627 TEST(Local, wouldInstructionBeTriviallyDead) { 628 LLVMContext Ctx; 629 // FIXME: PreserveInputDbgFormat is set to true because this test has 630 // been written to expect debug intrinsics rather than debug records. 631 // TODO: This test doesn't have a DbgRecord equivalent form so delete 632 // it when debug intrinsics are removed. 633 auto SettingGuard = SaveDbgInfoFormat(); 634 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 635 std::unique_ptr<Module> M = parseIR(Ctx, 636 R"( 637 define dso_local void @fun() local_unnamed_addr #0 !dbg !9 { 638 entry: 639 call void @llvm.dbg.declare(metadata !{}, metadata !13, metadata !DIExpression()), !dbg !16 640 ret void, !dbg !16 641 } 642 643 declare void @llvm.dbg.declare(metadata, metadata, metadata) 644 645 !llvm.dbg.cu = !{!0} 646 !llvm.module.flags = !{!2, !3} 647 !llvm.ident = !{!8} 648 649 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 16.0.0", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 650 !1 = !DIFile(filename: "test.c", directory: "/") 651 !2 = !{i32 7, !"Dwarf Version", i32 5} 652 !3 = !{i32 2, !"Debug Info Version", i32 3} 653 !8 = !{!"clang version 16.0.0"} 654 !9 = distinct !DISubprogram(name: "fun", scope: !1, file: !1, line: 1, type: !10, scopeLine: 1, flags: DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !12) 655 !10 = !DISubroutineType(types: !11) 656 !11 = !{null} 657 !12 = !{!13} 658 !13 = !DILocalVariable(name: "a", scope: !9, file: !1, line: 1, type: !14) 659 !14 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 660 !16 = !DILocation(line: 1, column: 21, scope: !9) 661 )"); 662 bool BrokenDebugInfo = true; 663 verifyModule(*M, &errs(), &BrokenDebugInfo); 664 ASSERT_FALSE(BrokenDebugInfo); 665 666 // Get the dbg.declare. 667 Function &F = *cast<Function>(M->getNamedValue("fun")); 668 Instruction *DbgDeclare = &F.front().front(); 669 ASSERT_TRUE(isa<DbgDeclareInst>(DbgDeclare)); 670 // Debug intrinsics with empty metadata arguments are not dead. 671 EXPECT_FALSE(wouldInstructionBeTriviallyDead(DbgDeclare)); 672 } 673 674 TEST(Local, ChangeToUnreachable) { 675 LLVMContext Ctx; 676 677 std::unique_ptr<Module> M = parseIR(Ctx, 678 R"( 679 define internal void @foo() !dbg !6 { 680 entry: 681 ret void, !dbg !8 682 } 683 684 !llvm.dbg.cu = !{!0} 685 !llvm.debugify = !{!3, !4} 686 !llvm.module.flags = !{!5} 687 688 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 689 !1 = !DIFile(filename: "test.ll", directory: "/") 690 !2 = !{} 691 !3 = !{i32 1} 692 !4 = !{i32 0} 693 !5 = !{i32 2, !"Debug Info Version", i32 3} 694 !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) 695 !7 = !DISubroutineType(types: !2) 696 !8 = !DILocation(line: 1, column: 1, scope: !6) 697 )"); 698 699 bool BrokenDebugInfo = true; 700 verifyModule(*M, &errs(), &BrokenDebugInfo); 701 ASSERT_FALSE(BrokenDebugInfo); 702 703 Function &F = *cast<Function>(M->getNamedValue("foo")); 704 705 BasicBlock &BB = F.front(); 706 Instruction &A = BB.front(); 707 DebugLoc DLA = A.getDebugLoc(); 708 709 ASSERT_TRUE(isa<ReturnInst>(&A)); 710 // One instruction should be affected. 711 EXPECT_EQ(changeToUnreachable(&A), 1U); 712 713 Instruction &B = BB.front(); 714 715 // There should be an uncreachable instruction. 716 ASSERT_TRUE(isa<UnreachableInst>(&B)); 717 718 DebugLoc DLB = B.getDebugLoc(); 719 EXPECT_EQ(DLA, DLB); 720 } 721 722 TEST(Local, FindDbgUsers) { 723 LLVMContext Ctx; 724 // FIXME: PreserveInputDbgFormat is set to true because this test has 725 // been written to expect debug intrinsics rather than debug records; use the 726 // intrinsic format until we update the test checks. 727 auto SettingGuard = SaveDbgInfoFormat(); 728 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 729 std::unique_ptr<Module> M = parseIR(Ctx, 730 R"( 731 define dso_local void @fun(ptr %a) #0 !dbg !11 { 732 entry: 733 call void @llvm.dbg.assign(metadata ptr %a, metadata !16, metadata !DIExpression(), metadata !15, metadata ptr %a, metadata !DIExpression()), !dbg !19 734 ret void 735 } 736 737 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata) 738 739 !llvm.dbg.cu = !{!0} 740 !llvm.module.flags = !{!2, !3, !9} 741 !llvm.ident = !{!10} 742 743 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 17.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 744 !1 = !DIFile(filename: "test.cpp", directory: "/") 745 !2 = !{i32 7, !"Dwarf Version", i32 5} 746 !3 = !{i32 2, !"Debug Info Version", i32 3} 747 !4 = !{i32 1, !"wchar_size", i32 4} 748 !9 = !{i32 7, !"debug-info-assignment-tracking", i1 true} 749 !10 = !{!"clang version 17.0.0"} 750 !11 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 1, type: !12, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !14) 751 !12 = !DISubroutineType(types: !13) 752 !13 = !{null} 753 !14 = !{} 754 !15 = distinct !DIAssignID() 755 !16 = !DILocalVariable(name: "x", scope: !11, file: !1, line: 2, type: !17) 756 !17 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !18, size: 64) 757 !18 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 758 !19 = !DILocation(line: 0, scope: !11) 759 )"); 760 761 bool BrokenDebugInfo = true; 762 verifyModule(*M, &errs(), &BrokenDebugInfo); 763 ASSERT_FALSE(BrokenDebugInfo); 764 765 Function &Fun = *cast<Function>(M->getNamedValue("fun")); 766 Value *Arg = Fun.getArg(0); 767 768 SmallVector<DbgVariableIntrinsic *> Users; 769 // Arg (%a) is used twice by a single dbg.assign. Check findDbgUsers returns 770 // only 1 pointer to it rather than 2. 771 findDbgUsers(Users, Arg); 772 EXPECT_EQ(Users.size(), 1u); 773 774 SmallVector<DbgValueInst *> Vals; 775 // Arg (%a) is used twice by a single dbg.assign. Check findDbgValues returns 776 // only 1 pointer to it rather than 2. 777 findDbgValues(Vals, Arg); 778 EXPECT_EQ(Vals.size(), 1u); 779 } 780 781 TEST(Local, FindDbgRecords) { 782 // DbgRecord copy of the FindDbgUsers test above. 783 LLVMContext Ctx; 784 std::unique_ptr<Module> M = parseIR(Ctx, 785 R"( 786 define dso_local void @fun(ptr %a) #0 !dbg !11 { 787 entry: 788 call void @llvm.dbg.assign(metadata ptr %a, metadata !16, metadata !DIExpression(), metadata !15, metadata ptr %a, metadata !DIExpression()), !dbg !19 789 ret void 790 } 791 792 !llvm.dbg.cu = !{!0} 793 !llvm.module.flags = !{!2, !3, !9} 794 !llvm.ident = !{!10} 795 796 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 17.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 797 !1 = !DIFile(filename: "test.cpp", directory: "/") 798 !2 = !{i32 7, !"Dwarf Version", i32 5} 799 !3 = !{i32 2, !"Debug Info Version", i32 3} 800 !4 = !{i32 1, !"wchar_size", i32 4} 801 !9 = !{i32 7, !"debug-info-assignment-tracking", i1 true} 802 !10 = !{!"clang version 17.0.0"} 803 !11 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 1, type: !12, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !14) 804 !12 = !DISubroutineType(types: !13) 805 !13 = !{null} 806 !14 = !{} 807 !15 = distinct !DIAssignID() 808 !16 = !DILocalVariable(name: "x", scope: !11, file: !1, line: 2, type: !17) 809 !17 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !18, size: 64) 810 !18 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 811 !19 = !DILocation(line: 0, scope: !11) 812 )"); 813 814 bool BrokenDebugInfo = true; 815 verifyModule(*M, &errs(), &BrokenDebugInfo); 816 ASSERT_FALSE(BrokenDebugInfo); 817 bool NewDbgInfoFormat = UseNewDbgInfoFormat; 818 UseNewDbgInfoFormat = true; 819 M->convertToNewDbgValues(); 820 821 Function &Fun = *cast<Function>(M->getNamedValue("fun")); 822 Value *Arg = Fun.getArg(0); 823 824 SmallVector<DbgVariableIntrinsic *> Users; 825 SmallVector<DbgVariableRecord *> Records; 826 // Arg (%a) is used twice by a single dbg_assign. Check findDbgUsers returns 827 // only 1 pointer to it rather than 2. 828 findDbgUsers(Users, Arg, &Records); 829 EXPECT_EQ(Users.size(), 0u); 830 EXPECT_EQ(Records.size(), 1u); 831 832 SmallVector<DbgValueInst *> Vals; 833 Records.clear(); 834 // Arg (%a) is used twice by a single dbg_assign. Check findDbgValues returns 835 // only 1 pointer to it rather than 2. 836 findDbgValues(Vals, Arg, &Records); 837 EXPECT_EQ(Vals.size(), 0u); 838 EXPECT_EQ(Records.size(), 1u); 839 UseNewDbgInfoFormat = NewDbgInfoFormat; 840 } 841 842 TEST(Local, ReplaceAllDbgUsesWith) { 843 using namespace llvm::dwarf; 844 845 LLVMContext Ctx; 846 // FIXME: PreserveInputDbgFormat is set to true because this test has 847 // been written to expect debug intrinsics rather than debug records; use the 848 // intrinsic format until we update the test checks. 849 auto SettingGuard = SaveDbgInfoFormat(); 850 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 851 852 // Note: The datalayout simulates Darwin/x86_64. 853 std::unique_ptr<Module> M = parseIR(Ctx, 854 R"( 855 target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128" 856 857 declare i32 @escape(i32) 858 859 define void @f() !dbg !6 { 860 entry: 861 %a = add i32 0, 1, !dbg !15 862 call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15 863 864 %b = add i64 0, 1, !dbg !16 865 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16 866 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16 867 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16 868 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16 869 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 870 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 871 872 %c = inttoptr i64 0 to i64*, !dbg !17 873 call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17 874 875 %d = inttoptr i64 0 to i32*, !dbg !18 876 call void @llvm.dbg.declare(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18 877 878 %e = add <2 x i16> zeroinitializer, zeroinitializer 879 call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18 880 881 %f = call i32 @escape(i32 0) 882 call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15 883 884 %barrier = call i32 @escape(i32 0) 885 886 %g = call i32 @escape(i32 %f) 887 call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15 888 889 ret void, !dbg !19 890 } 891 892 declare void @llvm.dbg.declare(metadata, metadata, metadata) 893 declare void @llvm.dbg.value(metadata, metadata, metadata) 894 895 !llvm.dbg.cu = !{!0} 896 !llvm.module.flags = !{!5} 897 898 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 899 !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/") 900 !2 = !{} 901 !5 = !{i32 2, !"Debug Info Version", i32 3} 902 !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) 903 !7 = !DISubroutineType(types: !2) 904 !8 = !{!9, !11, !13, !14} 905 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10) 906 !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed) 907 !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12) 908 !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed) 909 !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12) 910 !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10) 911 !15 = !DILocation(line: 1, column: 1, scope: !6) 912 !16 = !DILocation(line: 2, column: 1, scope: !6) 913 !17 = !DILocation(line: 3, column: 1, scope: !6) 914 !18 = !DILocation(line: 4, column: 1, scope: !6) 915 !19 = !DILocation(line: 5, column: 1, scope: !6) 916 !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10) 917 )"); 918 919 bool BrokenDebugInfo = true; 920 verifyModule(*M, &errs(), &BrokenDebugInfo); 921 ASSERT_FALSE(BrokenDebugInfo); 922 923 Function &F = *cast<Function>(M->getNamedValue("f")); 924 DominatorTree DT{F}; 925 926 BasicBlock &BB = F.front(); 927 Instruction &A = BB.front(); 928 Instruction &B = *A.getNextNonDebugInstruction(); 929 Instruction &C = *B.getNextNonDebugInstruction(); 930 Instruction &D = *C.getNextNonDebugInstruction(); 931 Instruction &E = *D.getNextNonDebugInstruction(); 932 Instruction &F_ = *E.getNextNonDebugInstruction(); 933 Instruction &Barrier = *F_.getNextNonDebugInstruction(); 934 Instruction &G = *Barrier.getNextNonDebugInstruction(); 935 936 // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says 937 // pointers are 64 bits, so the conversion would be lossy. 938 EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT)); 939 EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT)); 940 941 // Simulate i32 <-> <2 x i16> conversion. This is unsupported. 942 EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT)); 943 EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT)); 944 945 // Simulate i32* <-> i64* conversion. 946 EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT)); 947 948 SmallVector<DbgVariableIntrinsic *, 2> CDbgVals; 949 findDbgUsers(CDbgVals, &C); 950 EXPECT_EQ(2U, CDbgVals.size()); 951 EXPECT_TRUE(all_of(CDbgVals, [](DbgVariableIntrinsic *DII) { 952 return isa<DbgDeclareInst>(DII); 953 })); 954 955 EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT)); 956 957 SmallVector<DbgVariableIntrinsic *, 2> DDbgVals; 958 findDbgUsers(DDbgVals, &D); 959 EXPECT_EQ(2U, DDbgVals.size()); 960 EXPECT_TRUE(all_of(DDbgVals, [](DbgVariableIntrinsic *DII) { 961 return isa<DbgDeclareInst>(DII); 962 })); 963 964 // Introduce a use-before-def. Check that the dbg.value for %a is salvaged. 965 EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT)); 966 967 auto *ADbgVal = cast<DbgValueInst>(A.getNextNode()); 968 EXPECT_EQ(ADbgVal->getNumVariableLocationOps(), 1u); 969 EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocationOp(0)); 970 971 // Introduce a use-before-def. Check that the dbg.values for %f become undef. 972 EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT)); 973 974 auto *FDbgVal = cast<DbgValueInst>(F_.getNextNode()); 975 EXPECT_EQ(FDbgVal->getNumVariableLocationOps(), 1u); 976 EXPECT_TRUE(FDbgVal->isKillLocation()); 977 978 SmallVector<DbgValueInst *, 1> FDbgVals; 979 findDbgValues(FDbgVals, &F_); 980 EXPECT_EQ(0U, FDbgVals.size()); 981 982 // Simulate i32 -> i64 conversion to test sign-extension. Here are some 983 // interesting cases to handle: 984 // 1) debug user has empty DIExpression 985 // 2) debug user has non-empty, non-stack-value'd DIExpression 986 // 3) debug user has non-empty, stack-value'd DIExpression 987 // 4-6) like (1-3), but with a fragment 988 EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT)); 989 990 SmallVector<DbgValueInst *, 8> ADbgVals; 991 findDbgValues(ADbgVals, &A); 992 EXPECT_EQ(6U, ADbgVals.size()); 993 994 // Check that %a has a dbg.value with a DIExpression matching \p Ops. 995 auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) { 996 return any_of(ADbgVals, [&](DbgValueInst *DVI) { 997 assert(DVI->getVariable()->getName() == "2"); 998 return DVI->getExpression()->getElements() == Ops; 999 }); 1000 }; 1001 1002 // Case 1: The original expr is empty, so no deref is needed. 1003 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 1004 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1005 DW_OP_stack_value})); 1006 1007 // Case 2: Perform an address calculation with the original expr, deref it, 1008 // then sign-extend the result. 1009 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 1010 DW_OP_LLVM_convert, 32, DW_ATE_signed, 1011 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1012 DW_OP_stack_value})); 1013 1014 // Case 3: Insert the sign-extension logic before the DW_OP_stack_value. 1015 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 1016 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 1017 DW_OP_stack_value})); 1018 1019 // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end. 1020 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 1021 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1022 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1023 1024 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 1025 DW_OP_LLVM_convert, 32, DW_ATE_signed, 1026 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1027 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1028 1029 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 1030 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 1031 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1032 1033 verifyModule(*M, &errs(), &BrokenDebugInfo); 1034 ASSERT_FALSE(BrokenDebugInfo); 1035 } 1036 1037 TEST(Local, RemoveUnreachableBlocks) { 1038 LLVMContext C; 1039 1040 std::unique_ptr<Module> M = parseIR(C, 1041 R"( 1042 define void @br_simple() { 1043 entry: 1044 br label %bb0 1045 bb0: 1046 ret void 1047 bb1: 1048 ret void 1049 } 1050 1051 define void @br_self_loop() { 1052 entry: 1053 br label %bb0 1054 bb0: 1055 br i1 true, label %bb1, label %bb0 1056 bb1: 1057 br i1 true, label %bb0, label %bb2 1058 bb2: 1059 br label %bb2 1060 } 1061 1062 define void @br_constant() { 1063 entry: 1064 br label %bb0 1065 bb0: 1066 br i1 true, label %bb1, label %bb2 1067 bb1: 1068 br i1 true, label %bb0, label %bb2 1069 bb2: 1070 br label %bb2 1071 } 1072 1073 define void @br_loop() { 1074 entry: 1075 br label %bb0 1076 bb0: 1077 br label %bb0 1078 bb1: 1079 br label %bb2 1080 bb2: 1081 br label %bb1 1082 } 1083 1084 declare i32 @__gxx_personality_v0(...) 1085 1086 define void @invoke_terminator() personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) { 1087 entry: 1088 br i1 undef, label %invoke.block, label %exit 1089 1090 invoke.block: 1091 %cond = invoke zeroext i1 @invokable() 1092 to label %continue.block unwind label %lpad.block 1093 1094 continue.block: 1095 br i1 %cond, label %if.then, label %if.end 1096 1097 if.then: 1098 unreachable 1099 1100 if.end: 1101 unreachable 1102 1103 lpad.block: 1104 %lp = landingpad { i8*, i32 } 1105 catch i8* null 1106 br label %exit 1107 1108 exit: 1109 ret void 1110 } 1111 1112 declare i1 @invokable() 1113 )"); 1114 1115 auto runEager = [&](Function &F, DominatorTree *DT) { 1116 PostDominatorTree PDT = PostDominatorTree(F); 1117 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 1118 removeUnreachableBlocks(F, &DTU); 1119 EXPECT_TRUE(DTU.getDomTree().verify()); 1120 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1121 }; 1122 1123 auto runLazy = [&](Function &F, DominatorTree *DT) { 1124 PostDominatorTree PDT = PostDominatorTree(F); 1125 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 1126 removeUnreachableBlocks(F, &DTU); 1127 EXPECT_TRUE(DTU.getDomTree().verify()); 1128 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1129 }; 1130 1131 // Test removeUnreachableBlocks under Eager UpdateStrategy. 1132 runWithDomTree(*M, "br_simple", runEager); 1133 runWithDomTree(*M, "br_self_loop", runEager); 1134 runWithDomTree(*M, "br_constant", runEager); 1135 runWithDomTree(*M, "br_loop", runEager); 1136 runWithDomTree(*M, "invoke_terminator", runEager); 1137 1138 // Test removeUnreachableBlocks under Lazy UpdateStrategy. 1139 runWithDomTree(*M, "br_simple", runLazy); 1140 runWithDomTree(*M, "br_self_loop", runLazy); 1141 runWithDomTree(*M, "br_constant", runLazy); 1142 runWithDomTree(*M, "br_loop", runLazy); 1143 runWithDomTree(*M, "invoke_terminator", runLazy); 1144 1145 M = parseIR(C, 1146 R"( 1147 define void @f() { 1148 entry: 1149 ret void 1150 bb0: 1151 ret void 1152 } 1153 )"); 1154 1155 auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) { 1156 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 1157 EXPECT_TRUE(removeUnreachableBlocks(F, &DTU)); 1158 EXPECT_FALSE(removeUnreachableBlocks(F, &DTU)); 1159 EXPECT_TRUE(DTU.getDomTree().verify()); 1160 }; 1161 1162 runWithDomTree(*M, "f", checkRUBlocksRetVal); 1163 } 1164 1165 TEST(Local, SimplifyCFGWithNullAC) { 1166 LLVMContext Ctx; 1167 1168 std::unique_ptr<Module> M = parseIR(Ctx, R"( 1169 declare void @true_path() 1170 declare void @false_path() 1171 declare void @llvm.assume(i1 %cond); 1172 1173 define i32 @foo(i1, i32) { 1174 entry: 1175 %cmp = icmp sgt i32 %1, 0 1176 br i1 %cmp, label %if.bb1, label %then.bb1 1177 if.bb1: 1178 call void @true_path() 1179 br label %test.bb 1180 then.bb1: 1181 call void @false_path() 1182 br label %test.bb 1183 test.bb: 1184 %phi = phi i1 [1, %if.bb1], [%0, %then.bb1] 1185 call void @llvm.assume(i1 %0) 1186 br i1 %phi, label %if.bb2, label %then.bb2 1187 if.bb2: 1188 ret i32 %1 1189 then.bb2: 1190 ret i32 0 1191 } 1192 )"); 1193 1194 Function &F = *cast<Function>(M->getNamedValue("foo")); 1195 TargetTransformInfo TTI(M->getDataLayout()); 1196 1197 SimplifyCFGOptions Options{}; 1198 Options.setAssumptionCache(nullptr); 1199 1200 // Obtain BasicBlock of interest to this test, %test.bb. 1201 BasicBlock *TestBB = nullptr; 1202 for (BasicBlock &BB : F) { 1203 if (BB.getName().equals("test.bb")) { 1204 TestBB = &BB; 1205 break; 1206 } 1207 } 1208 ASSERT_TRUE(TestBB); 1209 1210 DominatorTree DT(F); 1211 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 1212 1213 // %test.bb is expected to be simplified by FoldCondBranchOnPHI. 1214 EXPECT_TRUE(simplifyCFG(TestBB, TTI, 1215 RequireAndPreserveDomTree ? &DTU : nullptr, Options)); 1216 } 1217 1218 TEST(Local, CanReplaceOperandWithVariable) { 1219 LLVMContext Ctx; 1220 Module M("test_module", Ctx); 1221 IRBuilder<> B(Ctx); 1222 1223 FunctionType *FnType = 1224 FunctionType::get(Type::getVoidTy(Ctx), {}, false); 1225 1226 FunctionType *VarArgFnType = 1227 FunctionType::get(Type::getVoidTy(Ctx), {B.getInt32Ty()}, true); 1228 1229 Function *TestBody = Function::Create(FnType, GlobalValue::ExternalLinkage, 1230 0, "", &M); 1231 1232 BasicBlock *BB0 = BasicBlock::Create(Ctx, "", TestBody); 1233 B.SetInsertPoint(BB0); 1234 1235 FunctionCallee Intrin = M.getOrInsertFunction("llvm.foo", FnType); 1236 FunctionCallee Func = M.getOrInsertFunction("foo", FnType); 1237 FunctionCallee VarArgFunc 1238 = M.getOrInsertFunction("foo.vararg", VarArgFnType); 1239 FunctionCallee VarArgIntrin 1240 = M.getOrInsertFunction("llvm.foo.vararg", VarArgFnType); 1241 1242 auto *CallToIntrin = B.CreateCall(Intrin); 1243 auto *CallToFunc = B.CreateCall(Func); 1244 1245 // Test if it's valid to replace the callee operand. 1246 EXPECT_FALSE(canReplaceOperandWithVariable(CallToIntrin, 0)); 1247 EXPECT_TRUE(canReplaceOperandWithVariable(CallToFunc, 0)); 1248 1249 // That it's invalid to replace an argument in the variadic argument list for 1250 // an intrinsic, but OK for a normal function. 1251 auto *CallToVarArgFunc = B.CreateCall( 1252 VarArgFunc, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1253 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 0)); 1254 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 1)); 1255 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 2)); 1256 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 3)); 1257 1258 auto *CallToVarArgIntrin = B.CreateCall( 1259 VarArgIntrin, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1260 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgIntrin, 0)); 1261 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 1)); 1262 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 2)); 1263 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 3)); 1264 1265 // Test that it's invalid to replace gcroot operands, even though it can't use 1266 // immarg. 1267 Type *PtrPtr = B.getPtrTy(0); 1268 Value *Alloca = B.CreateAlloca(PtrPtr, (unsigned)0); 1269 CallInst *GCRoot = B.CreateIntrinsic(Intrinsic::gcroot, {}, 1270 {Alloca, Constant::getNullValue(PtrPtr)}); 1271 EXPECT_TRUE(canReplaceOperandWithVariable(GCRoot, 0)); // Alloca 1272 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 1)); 1273 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 2)); 1274 1275 BB0->dropAllReferences(); 1276 } 1277 1278 TEST(Local, ExpressionForConstant) { 1279 LLVMContext Context; 1280 Module M("test_module", Context); 1281 DIBuilder DIB(M); 1282 DIExpression *Expr = nullptr; 1283 1284 auto createExpression = [&](Constant *C, Type *Ty) -> DIExpression * { 1285 EXPECT_NE(C, nullptr); 1286 EXPECT_NE(Ty, nullptr); 1287 EXPECT_EQ(C->getType(), Ty); 1288 std::unique_ptr<GlobalVariable> GV = std::make_unique<GlobalVariable>( 1289 Ty, false, GlobalValue::ExternalLinkage, C, "GV"); 1290 EXPECT_NE(GV, nullptr); 1291 1292 DIExpression *Expr = getExpressionForConstant(DIB, *GV->getInitializer(), 1293 *GV->getValueType()); 1294 if (Expr) { 1295 EXPECT_EQ(Expr->getNumElements(), 3u); 1296 EXPECT_EQ(Expr->getElement(0), dwarf::DW_OP_constu); 1297 EXPECT_EQ(Expr->getElement(2), dwarf::DW_OP_stack_value); 1298 } 1299 return Expr; 1300 }; 1301 1302 // Integer. 1303 IntegerType *Int1Ty = Type::getInt1Ty(Context); 1304 Expr = createExpression(ConstantInt::getTrue(Context), Int1Ty); 1305 EXPECT_NE(Expr, nullptr); 1306 EXPECT_EQ(Expr->getElement(1), 18446744073709551615U); 1307 1308 Expr = createExpression(ConstantInt::getFalse(Context), Int1Ty); 1309 EXPECT_NE(Expr, nullptr); 1310 EXPECT_EQ(Expr->getElement(1), 0U); 1311 1312 IntegerType *Int8Ty = Type::getInt8Ty(Context); 1313 Expr = createExpression(ConstantInt::get(Int8Ty, 100), Int8Ty); 1314 EXPECT_NE(Expr, nullptr); 1315 EXPECT_EQ(Expr->getElement(1), 100U); 1316 1317 IntegerType *Int16Ty = Type::getInt16Ty(Context); 1318 Expr = createExpression(ConstantInt::getSigned(Int16Ty, -50), Int16Ty); 1319 EXPECT_NE(Expr, nullptr); 1320 EXPECT_EQ(Expr->getElement(1), -50ULL); 1321 1322 IntegerType *Int32Ty = Type::getInt32Ty(Context); 1323 Expr = createExpression(ConstantInt::get(Int32Ty, 0x7FFFFFFF), Int32Ty); 1324 EXPECT_NE(Expr, nullptr); 1325 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFU); 1326 1327 IntegerType *Int64Ty = Type::getInt64Ty(Context); 1328 Expr = 1329 createExpression(ConstantInt::get(Int64Ty, 0x7FFFFFFFFFFFFFFF), Int64Ty); 1330 EXPECT_NE(Expr, nullptr); 1331 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFFFFFFFFFU); 1332 1333 IntegerType *Int128Ty = Type::getInt128Ty(Context); 1334 Expr = createExpression(ConstantInt::get(Int128Ty, 0x7FFFFFFFFFFFFFFF), 1335 Int128Ty); 1336 EXPECT_NE(Expr, nullptr); 1337 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFFFFFFFFFU); 1338 1339 GlobalVariable *String = 1340 IRBuilder<>(Context).CreateGlobalString("hello", "hello", 0, &M); 1341 Expr = createExpression(ConstantExpr::getPtrToInt(String, Int32Ty), Int32Ty); 1342 EXPECT_EQ(Expr, nullptr); 1343 1344 // Float. 1345 Type *FloatTy = Type::getFloatTy(Context); 1346 Expr = createExpression(ConstantFP::get(FloatTy, 5.55), FloatTy); 1347 EXPECT_NE(Expr, nullptr); 1348 EXPECT_EQ(Expr->getElement(1), 1085381018U); 1349 1350 // Double. 1351 Type *DoubleTy = Type::getDoubleTy(Context); 1352 Expr = createExpression(ConstantFP::get(DoubleTy, -5.55), DoubleTy); 1353 EXPECT_NE(Expr, nullptr); 1354 EXPECT_EQ(Expr->getElement(1), 13841306799765140275U); 1355 1356 // Half. 1357 Type *HalfTy = Type::getHalfTy(Context); 1358 Expr = createExpression(ConstantFP::get(HalfTy, 5.55), HalfTy); 1359 EXPECT_NE(Expr, nullptr); 1360 EXPECT_EQ(Expr->getElement(1), 17805U); 1361 1362 // BFloat. 1363 Type *BFloatTy = Type::getBFloatTy(Context); 1364 Expr = createExpression(ConstantFP::get(BFloatTy, -5.55), BFloatTy); 1365 EXPECT_NE(Expr, nullptr); 1366 EXPECT_EQ(Expr->getElement(1), 49330U); 1367 1368 // Pointer. 1369 PointerType *PtrTy = PointerType::get(Context, 0); 1370 Expr = createExpression(ConstantPointerNull::get(PtrTy), PtrTy); 1371 EXPECT_NE(Expr, nullptr); 1372 EXPECT_EQ(Expr->getElement(1), 0U); 1373 1374 ConstantInt *K1 = ConstantInt::get(Type::getInt32Ty(Context), 1234); 1375 Expr = createExpression(ConstantExpr::getIntToPtr(K1, PtrTy), PtrTy); 1376 EXPECT_NE(Expr, nullptr); 1377 EXPECT_EQ(Expr->getElement(1), 1234U); 1378 1379 ConstantInt *K2 = ConstantInt::get(Type::getInt64Ty(Context), 5678); 1380 Expr = createExpression(ConstantExpr::getIntToPtr(K2, PtrTy), PtrTy); 1381 EXPECT_NE(Expr, nullptr); 1382 EXPECT_EQ(Expr->getElement(1), 5678U); 1383 1384 Type *FP128Ty = Type::getFP128Ty(Context); 1385 Expr = createExpression(ConstantFP::get(FP128Ty, 32), FP128Ty); 1386 EXPECT_EQ(Expr, nullptr); 1387 1388 Type *X86_FP80Ty = Type::getX86_FP80Ty(Context); 1389 Expr = createExpression(ConstantFP::get(X86_FP80Ty, 32), X86_FP80Ty); 1390 EXPECT_EQ(Expr, nullptr); 1391 1392 Type *PPC_FP128Ty = Type::getPPC_FP128Ty(Context); 1393 Expr = createExpression(ConstantFP::get(PPC_FP128Ty, 32), PPC_FP128Ty); 1394 EXPECT_EQ(Expr, nullptr); 1395 } 1396 1397 TEST(Local, ReplaceDbgVariableRecord) { 1398 LLVMContext C; 1399 // FIXME: PreserveInputDbgFormat is set to true because this test has 1400 // been written to expect debug intrinsics rather than debug records; use the 1401 // intrinsic format until we update the test checks. 1402 auto SettingGuard = SaveDbgInfoFormat(); 1403 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 1404 1405 // Test that RAUW also replaces the operands of DbgVariableRecord objects, 1406 // i.e. non-instruction stored debugging information. 1407 std::unique_ptr<Module> M = parseIR(C, 1408 R"( 1409 declare void @llvm.dbg.value(metadata, metadata, metadata) 1410 define void @f(i32 %a) !dbg !8 { 1411 entry: 1412 %foo = add i32 %a, 1, !dbg !13 1413 %bar = add i32 %foo, 0, !dbg !13 1414 call void @llvm.dbg.value(metadata i32 %bar, metadata !11, metadata !DIExpression()), !dbg !13 1415 ret void, !dbg !14 1416 } 1417 !llvm.dbg.cu = !{!0} 1418 !llvm.module.flags = !{!3, !4} 1419 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 1420 !1 = !DIFile(filename: "t2.c", directory: "foo") 1421 !2 = !{} 1422 !3 = !{i32 2, !"Dwarf Version", i32 4} 1423 !4 = !{i32 2, !"Debug Info Version", i32 3} 1424 !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) 1425 !9 = !DISubroutineType(types: !10) 1426 !10 = !{null} 1427 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 1428 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 1429 !13 = !DILocation(line: 2, column: 7, scope: !8) 1430 !14 = !DILocation(line: 3, column: 1, scope: !8) 1431 )"); 1432 auto *GV = M->getNamedValue("f"); 1433 ASSERT_TRUE(GV); 1434 auto *F = dyn_cast<Function>(GV); 1435 ASSERT_TRUE(F); 1436 BasicBlock::iterator It = F->front().begin(); 1437 Instruction *FooInst = &*It; 1438 It = std::next(It); 1439 Instruction *BarInst = &*It; 1440 It = std::next(It); 1441 DbgValueInst *DVI = dyn_cast<DbgValueInst>(It); 1442 ASSERT_TRUE(DVI); 1443 It = std::next(It); 1444 Instruction *RetInst = &*It; 1445 1446 // Convert DVI into a DbgVariableRecord. 1447 RetInst->DebugMarker = new DbgMarker(); 1448 RetInst->DebugMarker->MarkedInstr = RetInst; 1449 DbgVariableRecord *DVR = new DbgVariableRecord(DVI); 1450 RetInst->DebugMarker->insertDbgRecord(DVR, false); 1451 // ... and erase the dbg.value. 1452 DVI->eraseFromParent(); 1453 1454 // DVR should originally refer to %bar, 1455 EXPECT_EQ(DVR->getVariableLocationOp(0), BarInst); 1456 1457 // Now try to replace the computation of %bar with %foo -- this should cause 1458 // the DbgVariableRecord's to have it's operand updated beneath it. 1459 BarInst->replaceAllUsesWith(FooInst); 1460 // Check DVR now points at %foo. 1461 EXPECT_EQ(DVR->getVariableLocationOp(0), FooInst); 1462 1463 // Teardown. 1464 RetInst->DebugMarker->eraseFromParent(); 1465 } 1466