xref: /llvm-project/llvm/unittests/Transforms/Utils/LocalTest.cpp (revision 84a4caeb84d31550790d6922903714b6563469c9)
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/Analysis/DomTreeUpdater.h"
11 #include "llvm/Analysis/InstructionSimplify.h"
12 #include "llvm/Analysis/PostDominators.h"
13 #include "llvm/Analysis/TargetTransformInfo.h"
14 #include "llvm/AsmParser/Parser.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/DIBuilder.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "gtest/gtest.h"
24 
25 using namespace llvm;
26 
27 TEST(Local, RecursivelyDeleteDeadPHINodes) {
28   LLVMContext C;
29 
30   IRBuilder<> builder(C);
31 
32   // Make blocks
33   BasicBlock *bb0 = BasicBlock::Create(C);
34   BasicBlock *bb1 = BasicBlock::Create(C);
35 
36   builder.SetInsertPoint(bb0);
37   PHINode    *phi = builder.CreatePHI(Type::getInt32Ty(C), 2);
38   BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1);
39 
40   builder.SetInsertPoint(bb1);
41   BranchInst *br1 = builder.CreateBr(bb0);
42 
43   phi->addIncoming(phi, bb0);
44   phi->addIncoming(phi, bb1);
45 
46   // The PHI will be removed
47   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
48 
49   // Make sure the blocks only contain the branches
50   EXPECT_EQ(&bb0->front(), br0);
51   EXPECT_EQ(&bb1->front(), br1);
52 
53   builder.SetInsertPoint(bb0);
54   phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
55 
56   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
57 
58   builder.SetInsertPoint(bb0);
59   phi = builder.CreatePHI(Type::getInt32Ty(C), 0);
60   builder.CreateAdd(phi, phi);
61 
62   EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi));
63 
64   bb0->dropAllReferences();
65   bb1->dropAllReferences();
66   delete bb0;
67   delete bb1;
68 }
69 
70 TEST(Local, RemoveDuplicatePHINodes) {
71   LLVMContext C;
72   IRBuilder<> B(C);
73 
74   std::unique_ptr<Function> F(
75       Function::Create(FunctionType::get(B.getVoidTy(), false),
76                        GlobalValue::ExternalLinkage, "F"));
77   BasicBlock *Entry(BasicBlock::Create(C, "", F.get()));
78   BasicBlock *BB(BasicBlock::Create(C, "", F.get()));
79   BranchInst::Create(BB, Entry);
80 
81   B.SetInsertPoint(BB);
82 
83   AssertingVH<PHINode> P1 = B.CreatePHI(Type::getInt32Ty(C), 2);
84   P1->addIncoming(B.getInt32(42), Entry);
85 
86   PHINode *P2 = B.CreatePHI(Type::getInt32Ty(C), 2);
87   P2->addIncoming(B.getInt32(42), Entry);
88 
89   AssertingVH<PHINode> P3 = B.CreatePHI(Type::getInt32Ty(C), 2);
90   P3->addIncoming(B.getInt32(42), Entry);
91   P3->addIncoming(B.getInt32(23), BB);
92 
93   PHINode *P4 = B.CreatePHI(Type::getInt32Ty(C), 2);
94   P4->addIncoming(B.getInt32(42), Entry);
95   P4->addIncoming(B.getInt32(23), BB);
96 
97   P1->addIncoming(P3, BB);
98   P2->addIncoming(P4, BB);
99   BranchInst::Create(BB, BB);
100 
101   // Verify that we can eliminate PHIs that become duplicates after chaning PHIs
102   // downstream.
103   EXPECT_TRUE(EliminateDuplicatePHINodes(BB));
104   EXPECT_EQ(3U, BB->size());
105 }
106 
107 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
108   SMDiagnostic Err;
109   std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
110   if (!Mod)
111     Err.print("UtilsTests", errs());
112   return Mod;
113 }
114 
115 TEST(Local, ReplaceDbgDeclare) {
116   LLVMContext C;
117 
118   // Original C source to get debug info for a local variable:
119   // void f() { int x; }
120   std::unique_ptr<Module> M = parseIR(C,
121                                       R"(
122       define void @f() !dbg !8 {
123       entry:
124         %x = alloca i32, align 4
125         call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13
126         call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13
127         ret void, !dbg !14
128       }
129       declare void @llvm.dbg.declare(metadata, metadata, metadata)
130       !llvm.dbg.cu = !{!0}
131       !llvm.module.flags = !{!3, !4}
132       !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
133       !1 = !DIFile(filename: "t2.c", directory: "foo")
134       !2 = !{}
135       !3 = !{i32 2, !"Dwarf Version", i32 4}
136       !4 = !{i32 2, !"Debug Info Version", i32 3}
137       !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)
138       !9 = !DISubroutineType(types: !10)
139       !10 = !{null}
140       !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12)
141       !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
142       !13 = !DILocation(line: 2, column: 7, scope: !8)
143       !14 = !DILocation(line: 3, column: 1, scope: !8)
144       )");
145   auto *GV = M->getNamedValue("f");
146   ASSERT_TRUE(GV);
147   auto *F = dyn_cast<Function>(GV);
148   ASSERT_TRUE(F);
149   Instruction *Inst = &F->front().front();
150   auto *AI = dyn_cast<AllocaInst>(Inst);
151   ASSERT_TRUE(AI);
152   Inst = Inst->getNextNode()->getNextNode();
153   ASSERT_TRUE(Inst);
154   auto *DII = dyn_cast<DbgDeclareInst>(Inst);
155   ASSERT_TRUE(DII);
156   Value *NewBase = Constant::getNullValue(Type::getInt32PtrTy(C));
157   DIBuilder DIB(*M);
158   replaceDbgDeclare(AI, NewBase, DIB, DIExpression::ApplyOffset, 0);
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() override {
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     if (DI.getNumVariableLocationOps() != 1u)
529       return false;
530     const auto &CI = *cast<ConstantInt>(DI.getValue(0));
531     if (CI.isZero())
532       return DI.getExpression()->getElements().equals(
533           {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value});
534     else if (CI.isOneValue())
535       return DI.getExpression()->getElements().empty();
536     return false;
537   }
538 
539   bool doesDebugValueDescribeY(const DbgValueInst &DI) {
540     if (DI.getNumVariableLocationOps() != 1u)
541       return false;
542     const auto &CI = *cast<ConstantInt>(DI.getVariableLocationOp(0));
543     if (CI.isZero())
544       return DI.getExpression()->getElements().equals(
545           {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2,
546            dwarf::DW_OP_stack_value});
547     else if (CI.isOneValue())
548       return DI.getExpression()->getElements().equals(
549           {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value});
550     return false;
551   }
552 
553   void verifyDebugValuesAreSalvaged() {
554     // Check that the debug values for %x and %y are preserved.
555     bool FoundX = false;
556     bool FoundY = false;
557     for (const Instruction &I : F->front()) {
558       auto DI = dyn_cast<DbgValueInst>(&I);
559       if (!DI) {
560         // The function should only contain debug values and a terminator.
561         ASSERT_TRUE(I.isTerminator());
562         continue;
563       }
564       EXPECT_EQ(DI->getVariable()->getName(), "x");
565       FoundX |= doesDebugValueDescribeX(*DI);
566       FoundY |= doesDebugValueDescribeY(*DI);
567     }
568     ASSERT_TRUE(FoundX);
569     ASSERT_TRUE(FoundY);
570   }
571 };
572 
573 TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) {
574   Instruction *Inst = &F->front().front();
575   Inst = Inst->getNextNode(); // Get %y = add ...
576   ASSERT_TRUE(Inst);
577   bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst);
578   ASSERT_TRUE(Deleted);
579   verifyDebugValuesAreSalvaged();
580 }
581 
582 TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) {
583   BasicBlock *BB = &F->front();
584   ASSERT_TRUE(BB);
585   bool Deleted = SimplifyInstructionsInBlock(BB);
586   ASSERT_TRUE(Deleted);
587   verifyDebugValuesAreSalvaged();
588 }
589 
590 TEST(Local, SimplifyVScaleWithRange) {
591   LLVMContext C;
592   Module M("Module", C);
593 
594   IntegerType *Ty = Type::getInt32Ty(C);
595   Function *VScale = Intrinsic::getDeclaration(&M, Intrinsic::vscale, {Ty});
596   auto *CI = CallInst::Create(VScale, {}, "vscale");
597 
598   // Test that SimplifyCall won't try to query it's parent function for
599   // vscale_range attributes in order to simplify llvm.vscale -> constant.
600   EXPECT_EQ(SimplifyCall(CI, SimplifyQuery(M.getDataLayout())), nullptr);
601   delete CI;
602 }
603 
604 TEST(Local, ChangeToUnreachable) {
605   LLVMContext Ctx;
606 
607   std::unique_ptr<Module> M = parseIR(Ctx,
608                                       R"(
609     define internal void @foo() !dbg !6 {
610     entry:
611       ret void, !dbg !8
612     }
613 
614     !llvm.dbg.cu = !{!0}
615     !llvm.debugify = !{!3, !4}
616     !llvm.module.flags = !{!5}
617 
618     !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
619     !1 = !DIFile(filename: "test.ll", directory: "/")
620     !2 = !{}
621     !3 = !{i32 1}
622     !4 = !{i32 0}
623     !5 = !{i32 2, !"Debug Info Version", i32 3}
624     !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)
625     !7 = !DISubroutineType(types: !2)
626     !8 = !DILocation(line: 1, column: 1, scope: !6)
627   )");
628 
629   bool BrokenDebugInfo = true;
630   verifyModule(*M, &errs(), &BrokenDebugInfo);
631   ASSERT_FALSE(BrokenDebugInfo);
632 
633   Function &F = *cast<Function>(M->getNamedValue("foo"));
634 
635   BasicBlock &BB = F.front();
636   Instruction &A = BB.front();
637   DebugLoc DLA = A.getDebugLoc();
638 
639   ASSERT_TRUE(isa<ReturnInst>(&A));
640   // One instruction should be affected.
641   EXPECT_EQ(changeToUnreachable(&A), 1U);
642 
643   Instruction &B = BB.front();
644 
645   // There should be an uncreachable instruction.
646   ASSERT_TRUE(isa<UnreachableInst>(&B));
647 
648   DebugLoc DLB = B.getDebugLoc();
649   EXPECT_EQ(DLA, DLB);
650 }
651 
652 TEST(Local, ReplaceAllDbgUsesWith) {
653   using namespace llvm::dwarf;
654 
655   LLVMContext Ctx;
656 
657   // Note: The datalayout simulates Darwin/x86_64.
658   std::unique_ptr<Module> M = parseIR(Ctx,
659                                       R"(
660     target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128"
661 
662     declare i32 @escape(i32)
663 
664     define void @f() !dbg !6 {
665     entry:
666       %a = add i32 0, 1, !dbg !15
667       call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15
668 
669       %b = add i64 0, 1, !dbg !16
670       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16
671       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16
672       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16
673       call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16
674       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
675       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
676 
677       %c = inttoptr i64 0 to i64*, !dbg !17
678       call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17
679 
680       %d = inttoptr i64 0 to i32*, !dbg !18
681       call void @llvm.dbg.addr(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18
682 
683       %e = add <2 x i16> zeroinitializer, zeroinitializer
684       call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18
685 
686       %f = call i32 @escape(i32 0)
687       call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15
688 
689       %barrier = call i32 @escape(i32 0)
690 
691       %g = call i32 @escape(i32 %f)
692       call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15
693 
694       ret void, !dbg !19
695     }
696 
697     declare void @llvm.dbg.addr(metadata, metadata, metadata)
698     declare void @llvm.dbg.declare(metadata, metadata, metadata)
699     declare void @llvm.dbg.value(metadata, metadata, metadata)
700 
701     !llvm.dbg.cu = !{!0}
702     !llvm.module.flags = !{!5}
703 
704     !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
705     !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/")
706     !2 = !{}
707     !5 = !{i32 2, !"Debug Info Version", i32 3}
708     !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)
709     !7 = !DISubroutineType(types: !2)
710     !8 = !{!9, !11, !13, !14}
711     !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
712     !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed)
713     !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12)
714     !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed)
715     !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12)
716     !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10)
717     !15 = !DILocation(line: 1, column: 1, scope: !6)
718     !16 = !DILocation(line: 2, column: 1, scope: !6)
719     !17 = !DILocation(line: 3, column: 1, scope: !6)
720     !18 = !DILocation(line: 4, column: 1, scope: !6)
721     !19 = !DILocation(line: 5, column: 1, scope: !6)
722     !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10)
723   )");
724 
725   bool BrokenDebugInfo = true;
726   verifyModule(*M, &errs(), &BrokenDebugInfo);
727   ASSERT_FALSE(BrokenDebugInfo);
728 
729   Function &F = *cast<Function>(M->getNamedValue("f"));
730   DominatorTree DT{F};
731 
732   BasicBlock &BB = F.front();
733   Instruction &A = BB.front();
734   Instruction &B = *A.getNextNonDebugInstruction();
735   Instruction &C = *B.getNextNonDebugInstruction();
736   Instruction &D = *C.getNextNonDebugInstruction();
737   Instruction &E = *D.getNextNonDebugInstruction();
738   Instruction &F_ = *E.getNextNonDebugInstruction();
739   Instruction &Barrier = *F_.getNextNonDebugInstruction();
740   Instruction &G = *Barrier.getNextNonDebugInstruction();
741 
742   // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says
743   // pointers are 64 bits, so the conversion would be lossy.
744   EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT));
745   EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT));
746 
747   // Simulate i32 <-> <2 x i16> conversion. This is unsupported.
748   EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT));
749   EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT));
750 
751   // Simulate i32* <-> i64* conversion.
752   EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT));
753 
754   SmallVector<DbgVariableIntrinsic *, 2> CDbgVals;
755   findDbgUsers(CDbgVals, &C);
756   EXPECT_EQ(2U, CDbgVals.size());
757   EXPECT_TRUE(any_of(CDbgVals, [](DbgVariableIntrinsic *DII) {
758     return isa<DbgAddrIntrinsic>(DII);
759   }));
760   EXPECT_TRUE(any_of(CDbgVals, [](DbgVariableIntrinsic *DII) {
761     return isa<DbgDeclareInst>(DII);
762   }));
763 
764   EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT));
765 
766   SmallVector<DbgVariableIntrinsic *, 2> DDbgVals;
767   findDbgUsers(DDbgVals, &D);
768   EXPECT_EQ(2U, DDbgVals.size());
769   EXPECT_TRUE(any_of(DDbgVals, [](DbgVariableIntrinsic *DII) {
770     return isa<DbgAddrIntrinsic>(DII);
771   }));
772   EXPECT_TRUE(any_of(DDbgVals, [](DbgVariableIntrinsic *DII) {
773     return isa<DbgDeclareInst>(DII);
774   }));
775 
776   // Introduce a use-before-def. Check that the dbg.value for %a is salvaged.
777   EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT));
778 
779   auto *ADbgVal = cast<DbgValueInst>(A.getNextNode());
780   EXPECT_EQ(ADbgVal->getNumVariableLocationOps(), 1u);
781   EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocationOp(0));
782 
783   // Introduce a use-before-def. Check that the dbg.values for %f become undef.
784   EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT));
785 
786   auto *FDbgVal = cast<DbgValueInst>(F_.getNextNode());
787   EXPECT_EQ(FDbgVal->getNumVariableLocationOps(), 1u);
788   EXPECT_TRUE(FDbgVal->isUndef());
789 
790   SmallVector<DbgValueInst *, 1> FDbgVals;
791   findDbgValues(FDbgVals, &F_);
792   EXPECT_EQ(0U, FDbgVals.size());
793 
794   // Simulate i32 -> i64 conversion to test sign-extension. Here are some
795   // interesting cases to handle:
796   //  1) debug user has empty DIExpression
797   //  2) debug user has non-empty, non-stack-value'd DIExpression
798   //  3) debug user has non-empty, stack-value'd DIExpression
799   //  4-6) like (1-3), but with a fragment
800   EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT));
801 
802   SmallVector<DbgValueInst *, 8> ADbgVals;
803   findDbgValues(ADbgVals, &A);
804   EXPECT_EQ(6U, ADbgVals.size());
805 
806   // Check that %a has a dbg.value with a DIExpression matching \p Ops.
807   auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) {
808     return any_of(ADbgVals, [&](DbgValueInst *DVI) {
809       assert(DVI->getVariable()->getName() == "2");
810       return DVI->getExpression()->getElements() == Ops;
811     });
812   };
813 
814   // Case 1: The original expr is empty, so no deref is needed.
815   EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed,
816                          DW_OP_LLVM_convert, 64, DW_ATE_signed,
817                          DW_OP_stack_value}));
818 
819   // Case 2: Perform an address calculation with the original expr, deref it,
820   // then sign-extend the result.
821   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref,
822                          DW_OP_LLVM_convert, 32, DW_ATE_signed,
823                          DW_OP_LLVM_convert, 64, DW_ATE_signed,
824                          DW_OP_stack_value}));
825 
826   // Case 3: Insert the sign-extension logic before the DW_OP_stack_value.
827   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32,
828                          DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed,
829                          DW_OP_stack_value}));
830 
831   // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end.
832   EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed,
833                          DW_OP_LLVM_convert, 64, DW_ATE_signed,
834                          DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
835 
836   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref,
837                          DW_OP_LLVM_convert, 32, DW_ATE_signed,
838                          DW_OP_LLVM_convert, 64, DW_ATE_signed,
839                          DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
840 
841   EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32,
842                          DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed,
843                          DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8}));
844 
845   verifyModule(*M, &errs(), &BrokenDebugInfo);
846   ASSERT_FALSE(BrokenDebugInfo);
847 }
848 
849 TEST(Local, RemoveUnreachableBlocks) {
850   LLVMContext C;
851 
852   std::unique_ptr<Module> M = parseIR(C,
853                                       R"(
854       define void @br_simple() {
855       entry:
856         br label %bb0
857       bb0:
858         ret void
859       bb1:
860         ret void
861       }
862 
863       define void @br_self_loop() {
864       entry:
865         br label %bb0
866       bb0:
867         br i1 true, label %bb1, label %bb0
868       bb1:
869         br i1 true, label %bb0, label %bb2
870       bb2:
871         br label %bb2
872       }
873 
874       define void @br_constant() {
875       entry:
876         br label %bb0
877       bb0:
878         br i1 true, label %bb1, label %bb2
879       bb1:
880         br i1 true, label %bb0, label %bb2
881       bb2:
882         br label %bb2
883       }
884 
885       define void @br_loop() {
886       entry:
887         br label %bb0
888       bb0:
889         br label %bb0
890       bb1:
891         br label %bb2
892       bb2:
893         br label %bb1
894       }
895 
896       declare i32 @__gxx_personality_v0(...)
897 
898       define void @invoke_terminator() personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) {
899       entry:
900         br i1 undef, label %invoke.block, label %exit
901 
902       invoke.block:
903         %cond = invoke zeroext i1 @invokable()
904                 to label %continue.block unwind label %lpad.block
905 
906       continue.block:
907         br i1 %cond, label %if.then, label %if.end
908 
909       if.then:
910         unreachable
911 
912       if.end:
913         unreachable
914 
915       lpad.block:
916         %lp = landingpad { i8*, i32 }
917                 catch i8* null
918         br label %exit
919 
920       exit:
921         ret void
922       }
923 
924       declare i1 @invokable()
925       )");
926 
927   auto runEager = [&](Function &F, DominatorTree *DT) {
928     PostDominatorTree PDT = PostDominatorTree(F);
929     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
930     removeUnreachableBlocks(F, &DTU);
931     EXPECT_TRUE(DTU.getDomTree().verify());
932     EXPECT_TRUE(DTU.getPostDomTree().verify());
933   };
934 
935   auto runLazy = [&](Function &F, DominatorTree *DT) {
936     PostDominatorTree PDT = PostDominatorTree(F);
937     DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
938     removeUnreachableBlocks(F, &DTU);
939     EXPECT_TRUE(DTU.getDomTree().verify());
940     EXPECT_TRUE(DTU.getPostDomTree().verify());
941   };
942 
943   // Test removeUnreachableBlocks under Eager UpdateStrategy.
944   runWithDomTree(*M, "br_simple", runEager);
945   runWithDomTree(*M, "br_self_loop", runEager);
946   runWithDomTree(*M, "br_constant", runEager);
947   runWithDomTree(*M, "br_loop", runEager);
948   runWithDomTree(*M, "invoke_terminator", runEager);
949 
950   // Test removeUnreachableBlocks under Lazy UpdateStrategy.
951   runWithDomTree(*M, "br_simple", runLazy);
952   runWithDomTree(*M, "br_self_loop", runLazy);
953   runWithDomTree(*M, "br_constant", runLazy);
954   runWithDomTree(*M, "br_loop", runLazy);
955   runWithDomTree(*M, "invoke_terminator", runLazy);
956 
957   M = parseIR(C,
958               R"(
959       define void @f() {
960       entry:
961         ret void
962       bb0:
963         ret void
964       }
965         )");
966 
967   auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) {
968     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
969     EXPECT_TRUE(removeUnreachableBlocks(F, &DTU));
970     EXPECT_FALSE(removeUnreachableBlocks(F, &DTU));
971     EXPECT_TRUE(DTU.getDomTree().verify());
972   };
973 
974   runWithDomTree(*M, "f", checkRUBlocksRetVal);
975 }
976 
977 TEST(Local, SimplifyCFGWithNullAC) {
978   LLVMContext Ctx;
979 
980   std::unique_ptr<Module> M = parseIR(Ctx, R"(
981     declare void @true_path()
982     declare void @false_path()
983     declare void @llvm.assume(i1 %cond);
984 
985     define i32 @foo(i1, i32) {
986     entry:
987       %cmp = icmp sgt i32 %1, 0
988       br i1 %cmp, label %if.bb1, label %then.bb1
989     if.bb1:
990       call void @true_path()
991       br label %test.bb
992     then.bb1:
993       call void @false_path()
994       br label %test.bb
995     test.bb:
996       %phi = phi i1 [1, %if.bb1], [%0, %then.bb1]
997       call void @llvm.assume(i1 %0)
998       br i1 %phi, label %if.bb2, label %then.bb2
999     if.bb2:
1000       ret i32 %1
1001     then.bb2:
1002       ret i32 0
1003     }
1004   )");
1005 
1006   Function &F = *cast<Function>(M->getNamedValue("foo"));
1007   TargetTransformInfo TTI(M->getDataLayout());
1008 
1009   SimplifyCFGOptions Options{};
1010   Options.setAssumptionCache(nullptr);
1011 
1012   // Obtain BasicBlock of interest to this test, %test.bb.
1013   BasicBlock *TestBB = nullptr;
1014   for (BasicBlock &BB : F) {
1015     if (BB.getName().equals("test.bb")) {
1016       TestBB = &BB;
1017       break;
1018     }
1019   }
1020   ASSERT_TRUE(TestBB);
1021 
1022   DominatorTree DT(F);
1023   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1024 
1025   // %test.bb is expected to be simplified by FoldCondBranchOnPHI.
1026   EXPECT_TRUE(simplifyCFG(TestBB, TTI,
1027                           RequireAndPreserveDomTree ? &DTU : nullptr, Options));
1028 }
1029 
1030 TEST(Local, CanReplaceOperandWithVariable) {
1031   LLVMContext Ctx;
1032   Module M("test_module", Ctx);
1033   IRBuilder<> B(Ctx);
1034 
1035   FunctionType *FnType =
1036     FunctionType::get(Type::getVoidTy(Ctx), {}, false);
1037 
1038   FunctionType *VarArgFnType =
1039     FunctionType::get(Type::getVoidTy(Ctx), {B.getInt32Ty()}, true);
1040 
1041   Function *TestBody = Function::Create(FnType, GlobalValue::ExternalLinkage,
1042                                         0, "", &M);
1043 
1044   BasicBlock *BB0 = BasicBlock::Create(Ctx, "", TestBody);
1045   B.SetInsertPoint(BB0);
1046 
1047   FunctionCallee Intrin = M.getOrInsertFunction("llvm.foo", FnType);
1048   FunctionCallee Func = M.getOrInsertFunction("foo", FnType);
1049   FunctionCallee VarArgFunc
1050     = M.getOrInsertFunction("foo.vararg", VarArgFnType);
1051   FunctionCallee VarArgIntrin
1052     = M.getOrInsertFunction("llvm.foo.vararg", VarArgFnType);
1053 
1054   auto *CallToIntrin = B.CreateCall(Intrin);
1055   auto *CallToFunc = B.CreateCall(Func);
1056 
1057   // Test if it's valid to replace the callee operand.
1058   EXPECT_FALSE(canReplaceOperandWithVariable(CallToIntrin, 0));
1059   EXPECT_TRUE(canReplaceOperandWithVariable(CallToFunc, 0));
1060 
1061   // That it's invalid to replace an argument in the variadic argument list for
1062   // an intrinsic, but OK for a normal function.
1063   auto *CallToVarArgFunc = B.CreateCall(
1064     VarArgFunc, {B.getInt32(0), B.getInt32(1), B.getInt32(2)});
1065   EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 0));
1066   EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 1));
1067   EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 2));
1068   EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 3));
1069 
1070   auto *CallToVarArgIntrin = B.CreateCall(
1071     VarArgIntrin, {B.getInt32(0), B.getInt32(1), B.getInt32(2)});
1072   EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgIntrin, 0));
1073   EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 1));
1074   EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 2));
1075   EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 3));
1076 
1077   // Test that it's invalid to replace gcroot operands, even though it can't use
1078   // immarg.
1079   Type *PtrPtr = B.getInt8Ty()->getPointerTo(0);
1080   Value *Alloca = B.CreateAlloca(PtrPtr, (unsigned)0);
1081   CallInst *GCRoot = B.CreateIntrinsic(Intrinsic::gcroot, {},
1082     {Alloca, Constant::getNullValue(PtrPtr)});
1083   EXPECT_TRUE(canReplaceOperandWithVariable(GCRoot, 0)); // Alloca
1084   EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 1));
1085   EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 2));
1086 
1087   BB0->dropAllReferences();
1088 }
1089