1 //===- ScalarEvolutionsTest.cpp - ScalarEvolution unit tests --------------===//
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/ADT/SmallVector.h"
10 #include "llvm/Analysis/AssumptionCache.h"
11 #include "llvm/Analysis/LoopInfo.h"
12 #include "llvm/Analysis/ScalarEvolutionExpander.h"
13 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
14 #include "llvm/Analysis/TargetLibraryInfo.h"
15 #include "llvm/AsmParser/Parser.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/InstIterator.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "gtest/gtest.h"
27 
28 namespace llvm {
29 namespace {
30 
31 // We use this fixture to ensure that we clean up ScalarEvolution before
32 // deleting the PassManager.
33 class ScalarEvolutionsTest : public testing::Test {
34 protected:
35   LLVMContext Context;
36   Module M;
37   TargetLibraryInfoImpl TLII;
38   TargetLibraryInfo TLI;
39 
40   std::unique_ptr<AssumptionCache> AC;
41   std::unique_ptr<DominatorTree> DT;
42   std::unique_ptr<LoopInfo> LI;
43 
44   ScalarEvolutionsTest() : M("", Context), TLII(), TLI(TLII) {}
45 
46   ScalarEvolution buildSE(Function &F) {
47     AC.reset(new AssumptionCache(F));
48     DT.reset(new DominatorTree(F));
49     LI.reset(new LoopInfo(*DT));
50     return ScalarEvolution(F, TLI, *AC, *DT, *LI);
51   }
52 
53   void runWithSE(
54       Module &M, StringRef FuncName,
55       function_ref<void(Function &F, LoopInfo &LI, ScalarEvolution &SE)> Test) {
56     auto *F = M.getFunction(FuncName);
57     ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
58     ScalarEvolution SE = buildSE(*F);
59     Test(*F, *LI, SE);
60   }
61 };
62 
63 TEST_F(ScalarEvolutionsTest, SCEVUnknownRAUW) {
64   FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
65                                               std::vector<Type *>(), false);
66   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
67   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
68   ReturnInst::Create(Context, nullptr, BB);
69 
70   Type *Ty = Type::getInt1Ty(Context);
71   Constant *Init = Constant::getNullValue(Ty);
72   Value *V0 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V0");
73   Value *V1 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V1");
74   Value *V2 = new GlobalVariable(M, Ty, false, GlobalValue::ExternalLinkage, Init, "V2");
75 
76   ScalarEvolution SE = buildSE(*F);
77 
78   const SCEV *S0 = SE.getSCEV(V0);
79   const SCEV *S1 = SE.getSCEV(V1);
80   const SCEV *S2 = SE.getSCEV(V2);
81 
82   const SCEV *P0 = SE.getAddExpr(S0, S0);
83   const SCEV *P1 = SE.getAddExpr(S1, S1);
84   const SCEV *P2 = SE.getAddExpr(S2, S2);
85 
86   const SCEVMulExpr *M0 = cast<SCEVMulExpr>(P0);
87   const SCEVMulExpr *M1 = cast<SCEVMulExpr>(P1);
88   const SCEVMulExpr *M2 = cast<SCEVMulExpr>(P2);
89 
90   EXPECT_EQ(cast<SCEVConstant>(M0->getOperand(0))->getValue()->getZExtValue(),
91             2u);
92   EXPECT_EQ(cast<SCEVConstant>(M1->getOperand(0))->getValue()->getZExtValue(),
93             2u);
94   EXPECT_EQ(cast<SCEVConstant>(M2->getOperand(0))->getValue()->getZExtValue(),
95             2u);
96 
97   // Before the RAUWs, these are all pointing to separate values.
98   EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0);
99   EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V1);
100   EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V2);
101 
102   // Do some RAUWs.
103   V2->replaceAllUsesWith(V1);
104   V1->replaceAllUsesWith(V0);
105 
106   // After the RAUWs, these should all be pointing to V0.
107   EXPECT_EQ(cast<SCEVUnknown>(M0->getOperand(1))->getValue(), V0);
108   EXPECT_EQ(cast<SCEVUnknown>(M1->getOperand(1))->getValue(), V0);
109   EXPECT_EQ(cast<SCEVUnknown>(M2->getOperand(1))->getValue(), V0);
110 }
111 
112 TEST_F(ScalarEvolutionsTest, SimplifiedPHI) {
113   FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
114                                               std::vector<Type *>(), false);
115   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
116   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
117   BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
118   BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
119   BranchInst::Create(LoopBB, EntryBB);
120   BranchInst::Create(LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)),
121                      LoopBB);
122   ReturnInst::Create(Context, nullptr, ExitBB);
123   auto *Ty = Type::getInt32Ty(Context);
124   auto *PN = PHINode::Create(Ty, 2, "", &*LoopBB->begin());
125   PN->addIncoming(Constant::getNullValue(Ty), EntryBB);
126   PN->addIncoming(UndefValue::get(Ty), LoopBB);
127   ScalarEvolution SE = buildSE(*F);
128   auto *S1 = SE.getSCEV(PN);
129   auto *S2 = SE.getSCEV(PN);
130   auto *ZeroConst = SE.getConstant(Ty, 0);
131 
132   // At some point, only the first call to getSCEV returned the simplified
133   // SCEVConstant and later calls just returned a SCEVUnknown referencing the
134   // PHI node.
135   EXPECT_EQ(S1, ZeroConst);
136   EXPECT_EQ(S1, S2);
137 }
138 
139 TEST_F(ScalarEvolutionsTest, ExpandPtrTypeSCEV) {
140   // It is to test the fix for PR30213. It exercises the branch in scev
141   // expansion when the value in ValueOffsetPair is a ptr and the offset
142   // is not divisible by the elem type size of value.
143   auto *I8Ty = Type::getInt8Ty(Context);
144   auto *I8PtrTy = Type::getInt8PtrTy(Context);
145   auto *I32Ty = Type::getInt32Ty(Context);
146   auto *I32PtrTy = Type::getInt32PtrTy(Context);
147   FunctionType *FTy =
148       FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
149   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
150   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
151   BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
152   BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
153   BranchInst::Create(LoopBB, EntryBB);
154   ReturnInst::Create(Context, nullptr, ExitBB);
155 
156   // loop:                            ; preds = %loop, %entry
157   //   %alloca = alloca i32
158   //   %gep0 = getelementptr i32, i32* %alloca, i32 1
159   //   %bitcast1 = bitcast i32* %gep0 to i8*
160   //   %gep1 = getelementptr i8, i8* %bitcast1, i32 1
161   //   %gep2 = getelementptr i8, i8* undef, i32 1
162   //   %cmp = icmp ult i8* undef, %bitcast1
163   //   %select = select i1 %cmp, i8* %gep1, i8* %gep2
164   //   %bitcast2 = bitcast i8* %select to i32*
165   //   br i1 undef, label %loop, label %exit
166 
167   const DataLayout &DL = F->getParent()->getDataLayout();
168   BranchInst *Br = BranchInst::Create(
169       LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
170   AllocaInst *Alloca = new AllocaInst(I32Ty, DL.getAllocaAddrSpace(),
171                                       "alloca", Br);
172   ConstantInt *Ci32 = ConstantInt::get(Context, APInt(32, 1));
173   GetElementPtrInst *Gep0 =
174       GetElementPtrInst::Create(I32Ty, Alloca, Ci32, "gep0", Br);
175   CastInst *CastA =
176       CastInst::CreateBitOrPointerCast(Gep0, I8PtrTy, "bitcast1", Br);
177   GetElementPtrInst *Gep1 =
178       GetElementPtrInst::Create(I8Ty, CastA, Ci32, "gep1", Br);
179   GetElementPtrInst *Gep2 = GetElementPtrInst::Create(
180       I8Ty, UndefValue::get(I8PtrTy), Ci32, "gep2", Br);
181   CmpInst *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULT,
182                                  UndefValue::get(I8PtrTy), CastA, "cmp", Br);
183   SelectInst *Sel = SelectInst::Create(Cmp, Gep1, Gep2, "select", Br);
184   CastInst *CastB =
185       CastInst::CreateBitOrPointerCast(Sel, I32PtrTy, "bitcast2", Br);
186 
187   ScalarEvolution SE = buildSE(*F);
188   auto *S = SE.getSCEV(CastB);
189   SCEVExpander Exp(SE, M.getDataLayout(), "expander");
190   Value *V =
191       Exp.expandCodeFor(cast<SCEVAddExpr>(S)->getOperand(1), nullptr, Br);
192 
193   // Expect the expansion code contains:
194   //   %0 = bitcast i32* %bitcast2 to i8*
195   //   %uglygep = getelementptr i8, i8* %0, i64 -1
196   //   %1 = bitcast i8* %uglygep to i32*
197   EXPECT_TRUE(isa<BitCastInst>(V));
198   Instruction *Gep = cast<Instruction>(V)->getPrevNode();
199   EXPECT_TRUE(isa<GetElementPtrInst>(Gep));
200   EXPECT_TRUE(isa<ConstantInt>(Gep->getOperand(1)));
201   EXPECT_EQ(cast<ConstantInt>(Gep->getOperand(1))->getSExtValue(), -1);
202   EXPECT_TRUE(isa<BitCastInst>(Gep->getPrevNode()));
203 }
204 
205 static Instruction *getInstructionByName(Function &F, StringRef Name) {
206   for (auto &I : instructions(F))
207     if (I.getName() == Name)
208       return &I;
209   llvm_unreachable("Expected to find instruction!");
210 }
211 
212 TEST_F(ScalarEvolutionsTest, CommutativeExprOperandOrder) {
213   LLVMContext C;
214   SMDiagnostic Err;
215   std::unique_ptr<Module> M = parseAssemblyString(
216       "target datalayout = \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\" "
217       " "
218       "@var_0 = external global i32, align 4"
219       "@var_1 = external global i32, align 4"
220       "@var_2 = external global i32, align 4"
221       " "
222       "declare i32 @unknown(i32, i32, i32)"
223       " "
224       "define void @f_1(i8* nocapture %arr, i32 %n, i32* %A, i32* %B) "
225       "    local_unnamed_addr { "
226       "entry: "
227       "  %entrycond = icmp sgt i32 %n, 0 "
228       "  br i1 %entrycond, label %loop.ph, label %for.end "
229       " "
230       "loop.ph: "
231       "  %a = load i32, i32* %A, align 4 "
232       "  %b = load i32, i32* %B, align 4 "
233       "  %mul = mul nsw i32 %b, %a "
234       "  %iv0.init = getelementptr inbounds i8, i8* %arr, i32 %mul "
235       "  br label %loop "
236       " "
237       "loop: "
238       "  %iv0 = phi i8* [ %iv0.inc, %loop ], [ %iv0.init, %loop.ph ] "
239       "  %iv1 = phi i32 [ %iv1.inc, %loop ], [ 0, %loop.ph ] "
240       "  %conv = trunc i32 %iv1 to i8 "
241       "  store i8 %conv, i8* %iv0, align 1 "
242       "  %iv0.inc = getelementptr inbounds i8, i8* %iv0, i32 %b "
243       "  %iv1.inc = add nuw nsw i32 %iv1, 1 "
244       "  %exitcond = icmp eq i32 %iv1.inc, %n "
245       "  br i1 %exitcond, label %for.end.loopexit, label %loop "
246       " "
247       "for.end.loopexit: "
248       "  br label %for.end "
249       " "
250       "for.end: "
251       "  ret void "
252       "} "
253       " "
254       "define void @f_2(i32* %X, i32* %Y, i32* %Z) { "
255       "  %x = load i32, i32* %X "
256       "  %y = load i32, i32* %Y "
257       "  %z = load i32, i32* %Z "
258       "  ret void "
259       "} "
260       " "
261       "define void @f_3() { "
262       "  %x = load i32, i32* @var_0"
263       "  %y = load i32, i32* @var_1"
264       "  %z = load i32, i32* @var_2"
265       "  ret void"
266       "} "
267       " "
268       "define void @f_4(i32 %a, i32 %b, i32 %c) { "
269       "  %x = call i32 @unknown(i32 %a, i32 %b, i32 %c)"
270       "  %y = call i32 @unknown(i32 %b, i32 %c, i32 %a)"
271       "  %z = call i32 @unknown(i32 %c, i32 %a, i32 %b)"
272       "  ret void"
273       "} "
274       ,
275       Err, C);
276 
277   assert(M && "Could not parse module?");
278   assert(!verifyModule(*M) && "Must have been well formed!");
279 
280   runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
281     auto *IV0 = getInstructionByName(F, "iv0");
282     auto *IV0Inc = getInstructionByName(F, "iv0.inc");
283 
284     auto *FirstExprForIV0 = SE.getSCEV(IV0);
285     auto *FirstExprForIV0Inc = SE.getSCEV(IV0Inc);
286     auto *SecondExprForIV0 = SE.getSCEV(IV0);
287 
288     EXPECT_TRUE(isa<SCEVAddRecExpr>(FirstExprForIV0));
289     EXPECT_TRUE(isa<SCEVAddRecExpr>(FirstExprForIV0Inc));
290     EXPECT_TRUE(isa<SCEVAddRecExpr>(SecondExprForIV0));
291   });
292 
293   auto CheckCommutativeMulExprs = [&](ScalarEvolution &SE, const SCEV *A,
294                                       const SCEV *B, const SCEV *C) {
295     EXPECT_EQ(SE.getMulExpr(A, B), SE.getMulExpr(B, A));
296     EXPECT_EQ(SE.getMulExpr(B, C), SE.getMulExpr(C, B));
297     EXPECT_EQ(SE.getMulExpr(A, C), SE.getMulExpr(C, A));
298 
299     SmallVector<const SCEV *, 3> Ops0 = {A, B, C};
300     SmallVector<const SCEV *, 3> Ops1 = {A, C, B};
301     SmallVector<const SCEV *, 3> Ops2 = {B, A, C};
302     SmallVector<const SCEV *, 3> Ops3 = {B, C, A};
303     SmallVector<const SCEV *, 3> Ops4 = {C, B, A};
304     SmallVector<const SCEV *, 3> Ops5 = {C, A, B};
305 
306     auto *Mul0 = SE.getMulExpr(Ops0);
307     auto *Mul1 = SE.getMulExpr(Ops1);
308     auto *Mul2 = SE.getMulExpr(Ops2);
309     auto *Mul3 = SE.getMulExpr(Ops3);
310     auto *Mul4 = SE.getMulExpr(Ops4);
311     auto *Mul5 = SE.getMulExpr(Ops5);
312 
313     EXPECT_EQ(Mul0, Mul1) << "Expected " << *Mul0 << " == " << *Mul1;
314     EXPECT_EQ(Mul1, Mul2) << "Expected " << *Mul1 << " == " << *Mul2;
315     EXPECT_EQ(Mul2, Mul3) << "Expected " << *Mul2 << " == " << *Mul3;
316     EXPECT_EQ(Mul3, Mul4) << "Expected " << *Mul3 << " == " << *Mul4;
317     EXPECT_EQ(Mul4, Mul5) << "Expected " << *Mul4 << " == " << *Mul5;
318   };
319 
320   for (StringRef FuncName : {"f_2", "f_3", "f_4"})
321     runWithSE(
322         *M, FuncName, [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
323           CheckCommutativeMulExprs(SE, SE.getSCEV(getInstructionByName(F, "x")),
324                                    SE.getSCEV(getInstructionByName(F, "y")),
325                                    SE.getSCEV(getInstructionByName(F, "z")));
326         });
327 }
328 
329 TEST_F(ScalarEvolutionsTest, CompareSCEVComplexity) {
330   FunctionType *FTy =
331       FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
332   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
333   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
334   BasicBlock *LoopBB = BasicBlock::Create(Context, "bb1", F);
335   BranchInst::Create(LoopBB, EntryBB);
336 
337   auto *Ty = Type::getInt32Ty(Context);
338   SmallVector<Instruction*, 8> Muls(8), Acc(8), NextAcc(8);
339 
340   Acc[0] = PHINode::Create(Ty, 2, "", LoopBB);
341   Acc[1] = PHINode::Create(Ty, 2, "", LoopBB);
342   Acc[2] = PHINode::Create(Ty, 2, "", LoopBB);
343   Acc[3] = PHINode::Create(Ty, 2, "", LoopBB);
344   Acc[4] = PHINode::Create(Ty, 2, "", LoopBB);
345   Acc[5] = PHINode::Create(Ty, 2, "", LoopBB);
346   Acc[6] = PHINode::Create(Ty, 2, "", LoopBB);
347   Acc[7] = PHINode::Create(Ty, 2, "", LoopBB);
348 
349   for (int i = 0; i < 20; i++) {
350     Muls[0] = BinaryOperator::CreateMul(Acc[0], Acc[0], "", LoopBB);
351     NextAcc[0] = BinaryOperator::CreateAdd(Muls[0], Acc[4], "", LoopBB);
352     Muls[1] = BinaryOperator::CreateMul(Acc[1], Acc[1], "", LoopBB);
353     NextAcc[1] = BinaryOperator::CreateAdd(Muls[1], Acc[5], "", LoopBB);
354     Muls[2] = BinaryOperator::CreateMul(Acc[2], Acc[2], "", LoopBB);
355     NextAcc[2] = BinaryOperator::CreateAdd(Muls[2], Acc[6], "", LoopBB);
356     Muls[3] = BinaryOperator::CreateMul(Acc[3], Acc[3], "", LoopBB);
357     NextAcc[3] = BinaryOperator::CreateAdd(Muls[3], Acc[7], "", LoopBB);
358 
359     Muls[4] = BinaryOperator::CreateMul(Acc[4], Acc[4], "", LoopBB);
360     NextAcc[4] = BinaryOperator::CreateAdd(Muls[4], Acc[0], "", LoopBB);
361     Muls[5] = BinaryOperator::CreateMul(Acc[5], Acc[5], "", LoopBB);
362     NextAcc[5] = BinaryOperator::CreateAdd(Muls[5], Acc[1], "", LoopBB);
363     Muls[6] = BinaryOperator::CreateMul(Acc[6], Acc[6], "", LoopBB);
364     NextAcc[6] = BinaryOperator::CreateAdd(Muls[6], Acc[2], "", LoopBB);
365     Muls[7] = BinaryOperator::CreateMul(Acc[7], Acc[7], "", LoopBB);
366     NextAcc[7] = BinaryOperator::CreateAdd(Muls[7], Acc[3], "", LoopBB);
367     Acc = NextAcc;
368   }
369 
370   auto II = LoopBB->begin();
371   for (int i = 0; i < 8; i++) {
372     PHINode *Phi = cast<PHINode>(&*II++);
373     Phi->addIncoming(Acc[i], LoopBB);
374     Phi->addIncoming(UndefValue::get(Ty), EntryBB);
375   }
376 
377   BasicBlock *ExitBB = BasicBlock::Create(Context, "bb2", F);
378   BranchInst::Create(LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)),
379                      LoopBB);
380 
381   Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
382   Acc[1] = BinaryOperator::CreateAdd(Acc[2], Acc[3], "", ExitBB);
383   Acc[2] = BinaryOperator::CreateAdd(Acc[4], Acc[5], "", ExitBB);
384   Acc[3] = BinaryOperator::CreateAdd(Acc[6], Acc[7], "", ExitBB);
385   Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
386   Acc[1] = BinaryOperator::CreateAdd(Acc[2], Acc[3], "", ExitBB);
387   Acc[0] = BinaryOperator::CreateAdd(Acc[0], Acc[1], "", ExitBB);
388 
389   ReturnInst::Create(Context, nullptr, ExitBB);
390 
391   ScalarEvolution SE = buildSE(*F);
392 
393   EXPECT_NE(nullptr, SE.getSCEV(Acc[0]));
394 }
395 
396 TEST_F(ScalarEvolutionsTest, CompareValueComplexity) {
397   IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(Context);
398   PointerType *IntPtrPtrTy = IntPtrTy->getPointerTo();
399 
400   FunctionType *FTy =
401       FunctionType::get(Type::getVoidTy(Context), {IntPtrTy, IntPtrTy}, false);
402   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
403   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
404 
405   Value *X = &*F->arg_begin();
406   Value *Y = &*std::next(F->arg_begin());
407 
408   const int ValueDepth = 10;
409   for (int i = 0; i < ValueDepth; i++) {
410     X = new LoadInst(new IntToPtrInst(X, IntPtrPtrTy, "", EntryBB), "",
411                      /*isVolatile*/ false, EntryBB);
412     Y = new LoadInst(new IntToPtrInst(Y, IntPtrPtrTy, "", EntryBB), "",
413                      /*isVolatile*/ false, EntryBB);
414   }
415 
416   auto *MulA = BinaryOperator::CreateMul(X, Y, "", EntryBB);
417   auto *MulB = BinaryOperator::CreateMul(Y, X, "", EntryBB);
418   ReturnInst::Create(Context, nullptr, EntryBB);
419 
420   // This test isn't checking for correctness.  Today making A and B resolve to
421   // the same SCEV would require deeper searching in CompareValueComplexity,
422   // which will slow down compilation.  However, this test can fail (with LLVM's
423   // behavior still being correct) if we ever have a smarter
424   // CompareValueComplexity that is both fast and more accurate.
425 
426   ScalarEvolution SE = buildSE(*F);
427   auto *A = SE.getSCEV(MulA);
428   auto *B = SE.getSCEV(MulB);
429   EXPECT_NE(A, B);
430 }
431 
432 TEST_F(ScalarEvolutionsTest, SCEVAddExpr) {
433   Type *Ty32 = Type::getInt32Ty(Context);
434   Type *ArgTys[] = {Type::getInt64Ty(Context), Ty32};
435 
436   FunctionType *FTy =
437       FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
438   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
439 
440   Argument *A1 = &*F->arg_begin();
441   Argument *A2 = &*(std::next(F->arg_begin()));
442   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
443 
444   Instruction *Trunc = CastInst::CreateTruncOrBitCast(A1, Ty32, "", EntryBB);
445   Instruction *Mul1 = BinaryOperator::CreateMul(Trunc, A2, "", EntryBB);
446   Instruction *Add1 = BinaryOperator::CreateAdd(Mul1, Trunc, "", EntryBB);
447   Mul1 = BinaryOperator::CreateMul(Add1, Trunc, "", EntryBB);
448   Instruction *Add2 = BinaryOperator::CreateAdd(Mul1, Add1, "", EntryBB);
449   // FIXME: The size of this is arbitrary and doesn't seem to change the
450   // result, but SCEV will do quadratic work for these so a large number here
451   // will be extremely slow. We should revisit what and how this is testing
452   // SCEV.
453   for (int i = 0; i < 10; i++) {
454     Mul1 = BinaryOperator::CreateMul(Add2, Add1, "", EntryBB);
455     Add1 = Add2;
456     Add2 = BinaryOperator::CreateAdd(Mul1, Add1, "", EntryBB);
457   }
458 
459   ReturnInst::Create(Context, nullptr, EntryBB);
460   ScalarEvolution SE = buildSE(*F);
461   EXPECT_NE(nullptr, SE.getSCEV(Mul1));
462 }
463 
464 static Instruction &GetInstByName(Function &F, StringRef Name) {
465   for (auto &I : instructions(F))
466     if (I.getName() == Name)
467       return I;
468   llvm_unreachable("Could not find instructions!");
469 }
470 
471 TEST_F(ScalarEvolutionsTest, SCEVNormalization) {
472   LLVMContext C;
473   SMDiagnostic Err;
474   std::unique_ptr<Module> M = parseAssemblyString(
475       "target datalayout = \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\" "
476       " "
477       "@var_0 = external global i32, align 4"
478       "@var_1 = external global i32, align 4"
479       "@var_2 = external global i32, align 4"
480       " "
481       "declare i32 @unknown(i32, i32, i32)"
482       " "
483       "define void @f_1(i8* nocapture %arr, i32 %n, i32* %A, i32* %B) "
484       "    local_unnamed_addr { "
485       "entry: "
486       "  br label %loop.ph "
487       " "
488       "loop.ph: "
489       "  br label %loop "
490       " "
491       "loop: "
492       "  %iv0 = phi i32 [ %iv0.inc, %loop ], [ 0, %loop.ph ] "
493       "  %iv1 = phi i32 [ %iv1.inc, %loop ], [ -2147483648, %loop.ph ] "
494       "  %iv0.inc = add i32 %iv0, 1 "
495       "  %iv1.inc = add i32 %iv1, 3 "
496       "  br i1 undef, label %for.end.loopexit, label %loop "
497       " "
498       "for.end.loopexit: "
499       "  ret void "
500       "} "
501       " "
502       "define void @f_2(i32 %a, i32 %b, i32 %c, i32 %d) "
503       "    local_unnamed_addr { "
504       "entry: "
505       "  br label %loop_0 "
506       " "
507       "loop_0: "
508       "  br i1 undef, label %loop_0, label %loop_1 "
509       " "
510       "loop_1: "
511       "  br i1 undef, label %loop_2, label %loop_1 "
512       " "
513       " "
514       "loop_2: "
515       "  br i1 undef, label %end, label %loop_2 "
516       " "
517       "end: "
518       "  ret void "
519       "} "
520       ,
521       Err, C);
522 
523   assert(M && "Could not parse module?");
524   assert(!verifyModule(*M) && "Must have been well formed!");
525 
526   runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
527     auto &I0 = GetInstByName(F, "iv0");
528     auto &I1 = *I0.getNextNode();
529 
530     auto *S0 = cast<SCEVAddRecExpr>(SE.getSCEV(&I0));
531     PostIncLoopSet Loops;
532     Loops.insert(S0->getLoop());
533     auto *N0 = normalizeForPostIncUse(S0, Loops, SE);
534     auto *D0 = denormalizeForPostIncUse(N0, Loops, SE);
535     EXPECT_EQ(S0, D0) << *S0 << " " << *D0;
536 
537     auto *S1 = cast<SCEVAddRecExpr>(SE.getSCEV(&I1));
538     Loops.clear();
539     Loops.insert(S1->getLoop());
540     auto *N1 = normalizeForPostIncUse(S1, Loops, SE);
541     auto *D1 = denormalizeForPostIncUse(N1, Loops, SE);
542     EXPECT_EQ(S1, D1) << *S1 << " " << *D1;
543   });
544 
545   runWithSE(*M, "f_2", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
546     auto *L2 = *LI.begin();
547     auto *L1 = *std::next(LI.begin());
548     auto *L0 = *std::next(LI.begin(), 2);
549 
550     auto GetAddRec = [&SE](const Loop *L, std::initializer_list<const SCEV *> Ops) {
551       SmallVector<const SCEV *, 4> OpsCopy(Ops);
552       return SE.getAddRecExpr(OpsCopy, L, SCEV::FlagAnyWrap);
553     };
554 
555     auto GetAdd = [&SE](std::initializer_list<const SCEV *> Ops) {
556       SmallVector<const SCEV *, 4> OpsCopy(Ops);
557       return SE.getAddExpr(OpsCopy, SCEV::FlagAnyWrap);
558     };
559 
560     // We first populate the AddRecs vector with a few "interesting" SCEV
561     // expressions, and then we go through the list and assert that each
562     // expression in it has an invertible normalization.
563 
564     std::vector<const SCEV *> Exprs;
565     {
566       const SCEV *V0 = SE.getSCEV(&*F.arg_begin());
567       const SCEV *V1 = SE.getSCEV(&*std::next(F.arg_begin(), 1));
568       const SCEV *V2 = SE.getSCEV(&*std::next(F.arg_begin(), 2));
569       const SCEV *V3 = SE.getSCEV(&*std::next(F.arg_begin(), 3));
570 
571       Exprs.push_back(GetAddRec(L0, {V0}));             // 0
572       Exprs.push_back(GetAddRec(L0, {V0, V1}));         // 1
573       Exprs.push_back(GetAddRec(L0, {V0, V1, V2}));     // 2
574       Exprs.push_back(GetAddRec(L0, {V0, V1, V2, V3})); // 3
575 
576       Exprs.push_back(
577           GetAddRec(L1, {Exprs[1], Exprs[2], Exprs[3], Exprs[0]})); // 4
578       Exprs.push_back(
579           GetAddRec(L1, {Exprs[1], Exprs[2], Exprs[0], Exprs[3]})); // 5
580       Exprs.push_back(
581           GetAddRec(L1, {Exprs[1], Exprs[3], Exprs[3], Exprs[1]})); // 6
582 
583       Exprs.push_back(GetAdd({Exprs[6], Exprs[3], V2})); // 7
584 
585       Exprs.push_back(
586           GetAddRec(L2, {Exprs[4], Exprs[3], Exprs[3], Exprs[5]})); // 8
587 
588       Exprs.push_back(
589           GetAddRec(L2, {Exprs[4], Exprs[6], Exprs[7], Exprs[3], V0})); // 9
590     }
591 
592     std::vector<PostIncLoopSet> LoopSets;
593     for (int i = 0; i < 8; i++) {
594       LoopSets.emplace_back();
595       if (i & 1)
596         LoopSets.back().insert(L0);
597       if (i & 2)
598         LoopSets.back().insert(L1);
599       if (i & 4)
600         LoopSets.back().insert(L2);
601     }
602 
603     for (const auto &LoopSet : LoopSets)
604       for (auto *S : Exprs) {
605         {
606           auto *N = llvm::normalizeForPostIncUse(S, LoopSet, SE);
607           auto *D = llvm::denormalizeForPostIncUse(N, LoopSet, SE);
608 
609           // Normalization and then denormalizing better give us back the same
610           // value.
611           EXPECT_EQ(S, D) << "S = " << *S << "  D = " << *D << " N = " << *N;
612         }
613         {
614           auto *D = llvm::denormalizeForPostIncUse(S, LoopSet, SE);
615           auto *N = llvm::normalizeForPostIncUse(D, LoopSet, SE);
616 
617           // Denormalization and then normalizing better give us back the same
618           // value.
619           EXPECT_EQ(S, N) << "S = " << *S << "  N = " << *N;
620         }
621       }
622   });
623 }
624 
625 // Expect the call of getZeroExtendExpr will not cost exponential time.
626 TEST_F(ScalarEvolutionsTest, SCEVZeroExtendExpr) {
627   LLVMContext C;
628   SMDiagnostic Err;
629 
630   // Generate a function like below:
631   // define void @foo() {
632   // entry:
633   //   br label %for.cond
634   //
635   // for.cond:
636   //   %0 = phi i64 [ 100, %entry ], [ %dec, %for.inc ]
637   //   %cmp = icmp sgt i64 %0, 90
638   //   br i1 %cmp, label %for.inc, label %for.cond1
639   //
640   // for.inc:
641   //   %dec = add nsw i64 %0, -1
642   //   br label %for.cond
643   //
644   // for.cond1:
645   //   %1 = phi i64 [ 100, %for.cond ], [ %dec5, %for.inc2 ]
646   //   %cmp3 = icmp sgt i64 %1, 90
647   //   br i1 %cmp3, label %for.inc2, label %for.cond4
648   //
649   // for.inc2:
650   //   %dec5 = add nsw i64 %1, -1
651   //   br label %for.cond1
652   //
653   // ......
654   //
655   // for.cond89:
656   //   %19 = phi i64 [ 100, %for.cond84 ], [ %dec94, %for.inc92 ]
657   //   %cmp93 = icmp sgt i64 %19, 90
658   //   br i1 %cmp93, label %for.inc92, label %for.end
659   //
660   // for.inc92:
661   //   %dec94 = add nsw i64 %19, -1
662   //   br label %for.cond89
663   //
664   // for.end:
665   //   %gep = getelementptr i8, i8* null, i64 %dec
666   //   %gep6 = getelementptr i8, i8* %gep, i64 %dec5
667   //   ......
668   //   %gep95 = getelementptr i8, i8* %gep91, i64 %dec94
669   //   ret void
670   // }
671   FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), {}, false);
672   Function *F = cast<Function>(M.getOrInsertFunction("foo", FTy));
673 
674   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
675   BasicBlock *CondBB = BasicBlock::Create(Context, "for.cond", F);
676   BasicBlock *EndBB = BasicBlock::Create(Context, "for.end", F);
677   BranchInst::Create(CondBB, EntryBB);
678   BasicBlock *PrevBB = EntryBB;
679 
680   Type *I64Ty = Type::getInt64Ty(Context);
681   Type *I8Ty = Type::getInt8Ty(Context);
682   Type *I8PtrTy = Type::getInt8PtrTy(Context);
683   Value *Accum = Constant::getNullValue(I8PtrTy);
684   int Iters = 20;
685   for (int i = 0; i < Iters; i++) {
686     BasicBlock *IncBB = BasicBlock::Create(Context, "for.inc", F, EndBB);
687     auto *PN = PHINode::Create(I64Ty, 2, "", CondBB);
688     PN->addIncoming(ConstantInt::get(Context, APInt(64, 100)), PrevBB);
689     auto *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT, PN,
690                                 ConstantInt::get(Context, APInt(64, 90)), "cmp",
691                                 CondBB);
692     BasicBlock *NextBB;
693     if (i != Iters - 1)
694       NextBB = BasicBlock::Create(Context, "for.cond", F, EndBB);
695     else
696       NextBB = EndBB;
697     BranchInst::Create(IncBB, NextBB, Cmp, CondBB);
698     auto *Dec = BinaryOperator::CreateNSWAdd(
699         PN, ConstantInt::get(Context, APInt(64, -1)), "dec", IncBB);
700     PN->addIncoming(Dec, IncBB);
701     BranchInst::Create(CondBB, IncBB);
702 
703     Accum = GetElementPtrInst::Create(I8Ty, Accum, PN, "gep", EndBB);
704 
705     PrevBB = CondBB;
706     CondBB = NextBB;
707   }
708   ReturnInst::Create(Context, nullptr, EndBB);
709   ScalarEvolution SE = buildSE(*F);
710   const SCEV *S = SE.getSCEV(Accum);
711   Type *I128Ty = Type::getInt128Ty(Context);
712   SE.getZeroExtendExpr(S, I128Ty);
713 }
714 
715 // Make sure that SCEV doesn't introduce illegal ptrtoint/inttoptr instructions
716 TEST_F(ScalarEvolutionsTest, SCEVZeroExtendExprNonIntegral) {
717   /*
718    * Create the following code:
719    * func(i64 addrspace(10)* %arg)
720    * top:
721    *  br label %L.ph
722    * L.ph:
723    *  br label %L
724    * L:
725    *  %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
726    *  %add = add i64 %phi2, 1
727    *  br i1 undef, label %post, label %L2
728    * post:
729    *  %gepbase = getelementptr i64 addrspace(10)* %arg, i64 1
730    *  #= %gep = getelementptr i64 addrspace(10)* %gepbase, i64 %add =#
731    *  ret void
732    *
733    * We will create the appropriate SCEV expression for %gep and expand it,
734    * then check that no inttoptr/ptrtoint instructions got inserted.
735    */
736 
737   // Create a module with non-integral pointers in it's datalayout
738   Module NIM("nonintegral", Context);
739   std::string DataLayout = M.getDataLayoutStr();
740   if (!DataLayout.empty())
741     DataLayout += "-";
742   DataLayout += "ni:10";
743   NIM.setDataLayout(DataLayout);
744 
745   Type *T_int1 = Type::getInt1Ty(Context);
746   Type *T_int64 = Type::getInt64Ty(Context);
747   Type *T_pint64 = T_int64->getPointerTo(10);
748 
749   FunctionType *FTy =
750       FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
751   Function *F = cast<Function>(NIM.getOrInsertFunction("foo", FTy));
752 
753   Argument *Arg = &*F->arg_begin();
754 
755   BasicBlock *Top = BasicBlock::Create(Context, "top", F);
756   BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
757   BasicBlock *L = BasicBlock::Create(Context, "L", F);
758   BasicBlock *Post = BasicBlock::Create(Context, "post", F);
759 
760   IRBuilder<> Builder(Top);
761   Builder.CreateBr(LPh);
762 
763   Builder.SetInsertPoint(LPh);
764   Builder.CreateBr(L);
765 
766   Builder.SetInsertPoint(L);
767   PHINode *Phi = Builder.CreatePHI(T_int64, 2);
768   Value *Add = Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add");
769   Builder.CreateCondBr(UndefValue::get(T_int1), L, Post);
770   Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
771   Phi->addIncoming(Add, L);
772 
773   Builder.SetInsertPoint(Post);
774   Value *GepBase = Builder.CreateGEP(Arg, ConstantInt::get(T_int64, 1));
775   Instruction *Ret = Builder.CreateRetVoid();
776 
777   ScalarEvolution SE = buildSE(*F);
778   auto *AddRec =
779       SE.getAddRecExpr(SE.getUnknown(GepBase), SE.getConstant(T_int64, 1),
780                        LI->getLoopFor(L), SCEV::FlagNUW);
781 
782   SCEVExpander Exp(SE, NIM.getDataLayout(), "expander");
783   Exp.disableCanonicalMode();
784   Exp.expandCodeFor(AddRec, T_pint64, Ret);
785 
786   // Make sure none of the instructions inserted were inttoptr/ptrtoint.
787   // The verifier will check this.
788   EXPECT_FALSE(verifyFunction(*F, &errs()));
789 }
790 
791 // Make sure that SCEV invalidates exit limits after invalidating the values it
792 // depends on when we forget a loop.
793 TEST_F(ScalarEvolutionsTest, SCEVExitLimitForgetLoop) {
794   /*
795    * Create the following code:
796    * func(i64 addrspace(10)* %arg)
797    * top:
798    *  br label %L.ph
799    * L.ph:
800    *  br label %L
801    * L:
802    *  %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
803    *  %add = add i64 %phi2, 1
804    *  %cond = icmp slt i64 %add, 1000; then becomes 2000.
805    *  br i1 %cond, label %post, label %L2
806    * post:
807    *  ret void
808    *
809    */
810 
811   // Create a module with non-integral pointers in it's datalayout
812   Module NIM("nonintegral", Context);
813   std::string DataLayout = M.getDataLayoutStr();
814   if (!DataLayout.empty())
815     DataLayout += "-";
816   DataLayout += "ni:10";
817   NIM.setDataLayout(DataLayout);
818 
819   Type *T_int64 = Type::getInt64Ty(Context);
820   Type *T_pint64 = T_int64->getPointerTo(10);
821 
822   FunctionType *FTy =
823       FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
824   Function *F = cast<Function>(NIM.getOrInsertFunction("foo", FTy));
825 
826   BasicBlock *Top = BasicBlock::Create(Context, "top", F);
827   BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
828   BasicBlock *L = BasicBlock::Create(Context, "L", F);
829   BasicBlock *Post = BasicBlock::Create(Context, "post", F);
830 
831   IRBuilder<> Builder(Top);
832   Builder.CreateBr(LPh);
833 
834   Builder.SetInsertPoint(LPh);
835   Builder.CreateBr(L);
836 
837   Builder.SetInsertPoint(L);
838   PHINode *Phi = Builder.CreatePHI(T_int64, 2);
839   auto *Add = cast<Instruction>(
840       Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
841   auto *Limit = ConstantInt::get(T_int64, 1000);
842   auto *Cond = cast<Instruction>(
843       Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Limit, "cond"));
844   auto *Br = cast<Instruction>(Builder.CreateCondBr(Cond, L, Post));
845   Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
846   Phi->addIncoming(Add, L);
847 
848   Builder.SetInsertPoint(Post);
849   Builder.CreateRetVoid();
850 
851   ScalarEvolution SE = buildSE(*F);
852   auto *Loop = LI->getLoopFor(L);
853   const SCEV *EC = SE.getBackedgeTakenCount(Loop);
854   EXPECT_FALSE(isa<SCEVCouldNotCompute>(EC));
855   EXPECT_TRUE(isa<SCEVConstant>(EC));
856   EXPECT_EQ(cast<SCEVConstant>(EC)->getAPInt().getLimitedValue(), 999u);
857 
858   // The add recurrence {5,+,1} does not correspond to any PHI in the IR, and
859   // that is relevant to this test.
860   auto *Five = SE.getConstant(APInt(/*numBits=*/64, 5));
861   auto *AR =
862       SE.getAddRecExpr(Five, SE.getOne(T_int64), Loop, SCEV::FlagAnyWrap);
863   const SCEV *ARAtLoopExit = SE.getSCEVAtScope(AR, nullptr);
864   EXPECT_FALSE(isa<SCEVCouldNotCompute>(ARAtLoopExit));
865   EXPECT_TRUE(isa<SCEVConstant>(ARAtLoopExit));
866   EXPECT_EQ(cast<SCEVConstant>(ARAtLoopExit)->getAPInt().getLimitedValue(),
867             1004u);
868 
869   SE.forgetLoop(Loop);
870   Br->eraseFromParent();
871   Cond->eraseFromParent();
872 
873   Builder.SetInsertPoint(L);
874   auto *NewCond = Builder.CreateICmp(
875       ICmpInst::ICMP_SLT, Add, ConstantInt::get(T_int64, 2000), "new.cond");
876   Builder.CreateCondBr(NewCond, L, Post);
877   const SCEV *NewEC = SE.getBackedgeTakenCount(Loop);
878   EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewEC));
879   EXPECT_TRUE(isa<SCEVConstant>(NewEC));
880   EXPECT_EQ(cast<SCEVConstant>(NewEC)->getAPInt().getLimitedValue(), 1999u);
881   const SCEV *NewARAtLoopExit = SE.getSCEVAtScope(AR, nullptr);
882   EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewARAtLoopExit));
883   EXPECT_TRUE(isa<SCEVConstant>(NewARAtLoopExit));
884   EXPECT_EQ(cast<SCEVConstant>(NewARAtLoopExit)->getAPInt().getLimitedValue(),
885             2004u);
886 }
887 
888 // Make sure that SCEV invalidates exit limits after invalidating the values it
889 // depends on when we forget a value.
890 TEST_F(ScalarEvolutionsTest, SCEVExitLimitForgetValue) {
891   /*
892    * Create the following code:
893    * func(i64 addrspace(10)* %arg)
894    * top:
895    *  br label %L.ph
896    * L.ph:
897    *  %load = load i64 addrspace(10)* %arg
898    *  br label %L
899    * L:
900    *  %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
901    *  %add = add i64 %phi2, 1
902    *  %cond = icmp slt i64 %add, %load ; then becomes 2000.
903    *  br i1 %cond, label %post, label %L2
904    * post:
905    *  ret void
906    *
907    */
908 
909   // Create a module with non-integral pointers in it's datalayout
910   Module NIM("nonintegral", Context);
911   std::string DataLayout = M.getDataLayoutStr();
912   if (!DataLayout.empty())
913     DataLayout += "-";
914   DataLayout += "ni:10";
915   NIM.setDataLayout(DataLayout);
916 
917   Type *T_int64 = Type::getInt64Ty(Context);
918   Type *T_pint64 = T_int64->getPointerTo(10);
919 
920   FunctionType *FTy =
921       FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
922   Function *F = cast<Function>(NIM.getOrInsertFunction("foo", FTy));
923 
924   Argument *Arg = &*F->arg_begin();
925 
926   BasicBlock *Top = BasicBlock::Create(Context, "top", F);
927   BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
928   BasicBlock *L = BasicBlock::Create(Context, "L", F);
929   BasicBlock *Post = BasicBlock::Create(Context, "post", F);
930 
931   IRBuilder<> Builder(Top);
932   Builder.CreateBr(LPh);
933 
934   Builder.SetInsertPoint(LPh);
935   auto *Load = cast<Instruction>(Builder.CreateLoad(T_int64, Arg, "load"));
936   Builder.CreateBr(L);
937 
938   Builder.SetInsertPoint(L);
939   PHINode *Phi = Builder.CreatePHI(T_int64, 2);
940   auto *Add = cast<Instruction>(
941       Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
942   auto *Cond = cast<Instruction>(
943       Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Load, "cond"));
944   auto *Br = cast<Instruction>(Builder.CreateCondBr(Cond, L, Post));
945   Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
946   Phi->addIncoming(Add, L);
947 
948   Builder.SetInsertPoint(Post);
949   Builder.CreateRetVoid();
950 
951   ScalarEvolution SE = buildSE(*F);
952   auto *Loop = LI->getLoopFor(L);
953   const SCEV *EC = SE.getBackedgeTakenCount(Loop);
954   EXPECT_FALSE(isa<SCEVCouldNotCompute>(EC));
955   EXPECT_FALSE(isa<SCEVConstant>(EC));
956 
957   SE.forgetValue(Load);
958   Br->eraseFromParent();
959   Cond->eraseFromParent();
960   Load->eraseFromParent();
961 
962   Builder.SetInsertPoint(L);
963   auto *NewCond = Builder.CreateICmp(
964       ICmpInst::ICMP_SLT, Add, ConstantInt::get(T_int64, 2000), "new.cond");
965   Builder.CreateCondBr(NewCond, L, Post);
966   const SCEV *NewEC = SE.getBackedgeTakenCount(Loop);
967   EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewEC));
968   EXPECT_TRUE(isa<SCEVConstant>(NewEC));
969   EXPECT_EQ(cast<SCEVConstant>(NewEC)->getAPInt().getLimitedValue(), 1999u);
970 }
971 
972 TEST_F(ScalarEvolutionsTest, SCEVAddRecFromPHIwithLargeConstants) {
973   // Reference: https://reviews.llvm.org/D37265
974   // Make sure that SCEV does not blow up when constructing an AddRec
975   // with predicates for a phi with the update pattern:
976   //  (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
977   // when either the initial value of the Phi or the InvariantAccum are
978   // constants that are too large to fit in an ix but are zero when truncated to
979   // ix.
980   FunctionType *FTy =
981       FunctionType::get(Type::getVoidTy(Context), std::vector<Type *>(), false);
982   Function *F = cast<Function>(M.getOrInsertFunction("addrecphitest", FTy));
983 
984   /*
985     Create IR:
986     entry:
987      br label %loop
988     loop:
989      %0 = phi i64 [-9223372036854775808, %entry], [%3, %loop]
990      %1 = shl i64 %0, 32
991      %2 = ashr exact i64 %1, 32
992      %3 = add i64 %2, -9223372036854775808
993      br i1 undef, label %exit, label %loop
994     exit:
995      ret void
996    */
997   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
998   BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
999   BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
1000 
1001   // entry:
1002   BranchInst::Create(LoopBB, EntryBB);
1003   // loop:
1004   auto *MinInt64 =
1005       ConstantInt::get(Context, APInt(64, 0x8000000000000000U, true));
1006   auto *Int64_32 = ConstantInt::get(Context, APInt(64, 32));
1007   auto *Br = BranchInst::Create(
1008       LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
1009   auto *Phi = PHINode::Create(Type::getInt64Ty(Context), 2, "", Br);
1010   auto *Shl = BinaryOperator::CreateShl(Phi, Int64_32, "", Br);
1011   auto *AShr = BinaryOperator::CreateExactAShr(Shl, Int64_32, "", Br);
1012   auto *Add = BinaryOperator::CreateAdd(AShr, MinInt64, "", Br);
1013   Phi->addIncoming(MinInt64, EntryBB);
1014   Phi->addIncoming(Add, LoopBB);
1015   // exit:
1016   ReturnInst::Create(Context, nullptr, ExitBB);
1017 
1018   // Make sure that SCEV doesn't blow up
1019   ScalarEvolution SE = buildSE(*F);
1020   SCEVUnionPredicate Preds;
1021   const SCEV *Expr = SE.getSCEV(Phi);
1022   EXPECT_NE(nullptr, Expr);
1023   EXPECT_TRUE(isa<SCEVUnknown>(Expr));
1024   auto Result = SE.createAddRecFromPHIWithCasts(cast<SCEVUnknown>(Expr));
1025 }
1026 
1027 TEST_F(ScalarEvolutionsTest, SCEVAddRecFromPHIwithLargeConstantAccum) {
1028   // Make sure that SCEV does not blow up when constructing an AddRec
1029   // with predicates for a phi with the update pattern:
1030   //  (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
1031   // when the InvariantAccum is a constant that is too large to fit in an
1032   // ix but are zero when truncated to ix, and the initial value of the
1033   // phi is not a constant.
1034   Type *Int32Ty = Type::getInt32Ty(Context);
1035   SmallVector<Type *, 1> Types;
1036   Types.push_back(Int32Ty);
1037   FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), Types, false);
1038   Function *F = cast<Function>(M.getOrInsertFunction("addrecphitest", FTy));
1039 
1040   /*
1041     Create IR:
1042     define @addrecphitest(i32)
1043     entry:
1044      br label %loop
1045     loop:
1046      %1 = phi i32 [%0, %entry], [%4, %loop]
1047      %2 = shl i32 %1, 16
1048      %3 = ashr exact i32 %2, 16
1049      %4 = add i32 %3, -2147483648
1050      br i1 undef, label %exit, label %loop
1051     exit:
1052      ret void
1053    */
1054   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", F);
1055   BasicBlock *LoopBB = BasicBlock::Create(Context, "loop", F);
1056   BasicBlock *ExitBB = BasicBlock::Create(Context, "exit", F);
1057 
1058   // entry:
1059   BranchInst::Create(LoopBB, EntryBB);
1060   // loop:
1061   auto *MinInt32 = ConstantInt::get(Context, APInt(32, 0x80000000U, true));
1062   auto *Int32_16 = ConstantInt::get(Context, APInt(32, 16));
1063   auto *Br = BranchInst::Create(
1064       LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
1065   auto *Phi = PHINode::Create(Int32Ty, 2, "", Br);
1066   auto *Shl = BinaryOperator::CreateShl(Phi, Int32_16, "", Br);
1067   auto *AShr = BinaryOperator::CreateExactAShr(Shl, Int32_16, "", Br);
1068   auto *Add = BinaryOperator::CreateAdd(AShr, MinInt32, "", Br);
1069   auto *Arg = &*(F->arg_begin());
1070   Phi->addIncoming(Arg, EntryBB);
1071   Phi->addIncoming(Add, LoopBB);
1072   // exit:
1073   ReturnInst::Create(Context, nullptr, ExitBB);
1074 
1075   // Make sure that SCEV doesn't blow up
1076   ScalarEvolution SE = buildSE(*F);
1077   SCEVUnionPredicate Preds;
1078   const SCEV *Expr = SE.getSCEV(Phi);
1079   EXPECT_NE(nullptr, Expr);
1080   EXPECT_TRUE(isa<SCEVUnknown>(Expr));
1081   auto Result = SE.createAddRecFromPHIWithCasts(cast<SCEVUnknown>(Expr));
1082 }
1083 
1084 TEST_F(ScalarEvolutionsTest, SCEVFoldSumOfTruncs) {
1085   // Verify that the following SCEV gets folded to a zero:
1086   //  (-1 * (trunc i64 (-1 * %0) to i32)) + (-1 * (trunc i64 %0 to i32)
1087   Type *ArgTy = Type::getInt64Ty(Context);
1088   Type *Int32Ty = Type::getInt32Ty(Context);
1089   SmallVector<Type *, 1> Types;
1090   Types.push_back(ArgTy);
1091   FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context), Types, false);
1092   Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
1093   BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
1094   ReturnInst::Create(Context, nullptr, BB);
1095 
1096   ScalarEvolution SE = buildSE(*F);
1097 
1098   auto *Arg = &*(F->arg_begin());
1099   const auto *ArgSCEV = SE.getSCEV(Arg);
1100 
1101   // Build the SCEV
1102   const auto *A0 = SE.getNegativeSCEV(ArgSCEV);
1103   const auto *A1 = SE.getTruncateExpr(A0, Int32Ty);
1104   const auto *A = SE.getNegativeSCEV(A1);
1105 
1106   const auto *B0 = SE.getTruncateExpr(ArgSCEV, Int32Ty);
1107   const auto *B = SE.getNegativeSCEV(B0);
1108 
1109   const auto *Expr = SE.getAddExpr(A, B);
1110   // Verify that the SCEV was folded to 0
1111   const auto *ZeroConst = SE.getConstant(Int32Ty, 0);
1112   EXPECT_EQ(Expr, ZeroConst);
1113 }
1114 
1115 // Check that we can correctly identify the points at which the SCEV of the
1116 // AddRec can be expanded.
1117 TEST_F(ScalarEvolutionsTest, SCEVExpanderIsSafeToExpandAt) {
1118   /*
1119    * Create the following code:
1120    * func(i64 addrspace(10)* %arg)
1121    * top:
1122    *  br label %L.ph
1123    * L.ph:
1124    *  br label %L
1125    * L:
1126    *  %phi = phi i64 [i64 0, %L.ph], [ %add, %L2 ]
1127    *  %add = add i64 %phi2, 1
1128    *  %cond = icmp slt i64 %add, 1000; then becomes 2000.
1129    *  br i1 %cond, label %post, label %L2
1130    * post:
1131    *  ret void
1132    *
1133    */
1134 
1135   // Create a module with non-integral pointers in it's datalayout
1136   Module NIM("nonintegral", Context);
1137   std::string DataLayout = M.getDataLayoutStr();
1138   if (!DataLayout.empty())
1139     DataLayout += "-";
1140   DataLayout += "ni:10";
1141   NIM.setDataLayout(DataLayout);
1142 
1143   Type *T_int64 = Type::getInt64Ty(Context);
1144   Type *T_pint64 = T_int64->getPointerTo(10);
1145 
1146   FunctionType *FTy =
1147       FunctionType::get(Type::getVoidTy(Context), {T_pint64}, false);
1148   Function *F = cast<Function>(NIM.getOrInsertFunction("foo", FTy));
1149 
1150   BasicBlock *Top = BasicBlock::Create(Context, "top", F);
1151   BasicBlock *LPh = BasicBlock::Create(Context, "L.ph", F);
1152   BasicBlock *L = BasicBlock::Create(Context, "L", F);
1153   BasicBlock *Post = BasicBlock::Create(Context, "post", F);
1154 
1155   IRBuilder<> Builder(Top);
1156   Builder.CreateBr(LPh);
1157 
1158   Builder.SetInsertPoint(LPh);
1159   Builder.CreateBr(L);
1160 
1161   Builder.SetInsertPoint(L);
1162   PHINode *Phi = Builder.CreatePHI(T_int64, 2);
1163   auto *Add = cast<Instruction>(
1164       Builder.CreateAdd(Phi, ConstantInt::get(T_int64, 1), "add"));
1165   auto *Limit = ConstantInt::get(T_int64, 1000);
1166   auto *Cond = cast<Instruction>(
1167       Builder.CreateICmp(ICmpInst::ICMP_SLT, Add, Limit, "cond"));
1168   Builder.CreateCondBr(Cond, L, Post);
1169   Phi->addIncoming(ConstantInt::get(T_int64, 0), LPh);
1170   Phi->addIncoming(Add, L);
1171 
1172   Builder.SetInsertPoint(Post);
1173   Builder.CreateRetVoid();
1174 
1175   ScalarEvolution SE = buildSE(*F);
1176   const SCEV *S = SE.getSCEV(Phi);
1177   EXPECT_TRUE(isa<SCEVAddRecExpr>(S));
1178   const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
1179   EXPECT_TRUE(AR->isAffine());
1180   EXPECT_FALSE(isSafeToExpandAt(AR, Top->getTerminator(), SE));
1181   EXPECT_FALSE(isSafeToExpandAt(AR, LPh->getTerminator(), SE));
1182   EXPECT_TRUE(isSafeToExpandAt(AR, L->getTerminator(), SE));
1183   EXPECT_TRUE(isSafeToExpandAt(AR, Post->getTerminator(), SE));
1184 }
1185 
1186 // Check that SCEV expander does not use the nuw instruction
1187 // for expansion.
1188 TEST_F(ScalarEvolutionsTest, SCEVExpanderNUW) {
1189   /*
1190    * Create the following code:
1191    * func(i64 %a)
1192    * entry:
1193    *   br false, label %exit, label %body
1194    * body:
1195    *  %s1 = add i64 %a, -1
1196    *  br label %exit
1197    * exit:
1198    *  %s = add nuw i64 %a, -1
1199    *  ret %s
1200    */
1201 
1202   // Create a module.
1203   Module M("SCEVExpanderNUW", Context);
1204 
1205   Type *T_int64 = Type::getInt64Ty(Context);
1206 
1207   FunctionType *FTy =
1208       FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
1209   Function *F = cast<Function>(M.getOrInsertFunction("func", FTy));
1210   Argument *Arg = &*F->arg_begin();
1211   ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1212 
1213   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1214   BasicBlock *Body = BasicBlock::Create(Context, "body", F);
1215   BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1216 
1217   IRBuilder<> Builder(Entry);
1218   ConstantInt *Cond = ConstantInt::get(Context, APInt(1, 0));
1219   Builder.CreateCondBr(Cond, Exit, Body);
1220 
1221   Builder.SetInsertPoint(Body);
1222   auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1223   Builder.CreateBr(Exit);
1224 
1225   Builder.SetInsertPoint(Exit);
1226   auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1227   S2->setHasNoUnsignedWrap(true);
1228   auto *R = cast<Instruction>(Builder.CreateRetVoid());
1229 
1230   ScalarEvolution SE = buildSE(*F);
1231   const SCEV *S = SE.getSCEV(S1);
1232   EXPECT_TRUE(isa<SCEVAddExpr>(S));
1233   SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1234   auto *I = cast<Instruction>(Exp.expandCodeFor(S, nullptr, R));
1235   EXPECT_FALSE(I->hasNoUnsignedWrap());
1236 }
1237 
1238 // Check that SCEV expander does not use the nsw instruction
1239 // for expansion.
1240 TEST_F(ScalarEvolutionsTest, SCEVExpanderNSW) {
1241   /*
1242    * Create the following code:
1243    * func(i64 %a)
1244    * entry:
1245    *   br false, label %exit, label %body
1246    * body:
1247    *  %s1 = add i64 %a, -1
1248    *  br label %exit
1249    * exit:
1250    *  %s = add nsw i64 %a, -1
1251    *  ret %s
1252    */
1253 
1254   // Create a module.
1255   Module M("SCEVExpanderNSW", Context);
1256 
1257   Type *T_int64 = Type::getInt64Ty(Context);
1258 
1259   FunctionType *FTy =
1260       FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
1261   Function *F = cast<Function>(M.getOrInsertFunction("func", FTy));
1262   Argument *Arg = &*F->arg_begin();
1263   ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1264 
1265   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1266   BasicBlock *Body = BasicBlock::Create(Context, "body", F);
1267   BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1268 
1269   IRBuilder<> Builder(Entry);
1270   ConstantInt *Cond = ConstantInt::get(Context, APInt(1, 0));
1271   Builder.CreateCondBr(Cond, Exit, Body);
1272 
1273   Builder.SetInsertPoint(Body);
1274   auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1275   Builder.CreateBr(Exit);
1276 
1277   Builder.SetInsertPoint(Exit);
1278   auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1279   S2->setHasNoSignedWrap(true);
1280   auto *R = cast<Instruction>(Builder.CreateRetVoid());
1281 
1282   ScalarEvolution SE = buildSE(*F);
1283   const SCEV *S = SE.getSCEV(S1);
1284   EXPECT_TRUE(isa<SCEVAddExpr>(S));
1285   SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1286   auto *I = cast<Instruction>(Exp.expandCodeFor(S, nullptr, R));
1287   EXPECT_FALSE(I->hasNoSignedWrap());
1288 }
1289 
1290 // Check that SCEV does not save the SCEV -> V
1291 // mapping of SCEV differ from V in NUW flag.
1292 TEST_F(ScalarEvolutionsTest, SCEVCacheNUW) {
1293   /*
1294    * Create the following code:
1295    * func(i64 %a)
1296    * entry:
1297    *  %s1 = add i64 %a, -1
1298    *  %s2 = add nuw i64 %a, -1
1299    *  br label %exit
1300    * exit:
1301    *  ret %s
1302    */
1303 
1304   // Create a module.
1305   Module M("SCEVCacheNUW", Context);
1306 
1307   Type *T_int64 = Type::getInt64Ty(Context);
1308 
1309   FunctionType *FTy =
1310       FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
1311   Function *F = cast<Function>(M.getOrInsertFunction("func", FTy));
1312   Argument *Arg = &*F->arg_begin();
1313   ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1314 
1315   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1316   BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1317 
1318   IRBuilder<> Builder(Entry);
1319   auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1320   auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1321   S2->setHasNoUnsignedWrap(true);
1322   Builder.CreateBr(Exit);
1323 
1324   Builder.SetInsertPoint(Exit);
1325   auto *R = cast<Instruction>(Builder.CreateRetVoid());
1326 
1327   ScalarEvolution SE = buildSE(*F);
1328   // Get S2 first to move it to cache.
1329   const SCEV *SC2 = SE.getSCEV(S2);
1330   EXPECT_TRUE(isa<SCEVAddExpr>(SC2));
1331   // Now get S1.
1332   const SCEV *SC1 = SE.getSCEV(S1);
1333   EXPECT_TRUE(isa<SCEVAddExpr>(SC1));
1334   // Expand for S1, it should use S1 not S2 in spite S2
1335   // first in the cache.
1336   SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1337   auto *I = cast<Instruction>(Exp.expandCodeFor(SC1, nullptr, R));
1338   EXPECT_FALSE(I->hasNoUnsignedWrap());
1339 }
1340 
1341 // Check that SCEV does not save the SCEV -> V
1342 // mapping of SCEV differ from V in NSW flag.
1343 TEST_F(ScalarEvolutionsTest, SCEVCacheNSW) {
1344   /*
1345    * Create the following code:
1346    * func(i64 %a)
1347    * entry:
1348    *  %s1 = add i64 %a, -1
1349    *  %s2 = add nsw i64 %a, -1
1350    *  br label %exit
1351    * exit:
1352    *  ret %s
1353    */
1354 
1355   // Create a module.
1356   Module M("SCEVCacheNUW", Context);
1357 
1358   Type *T_int64 = Type::getInt64Ty(Context);
1359 
1360   FunctionType *FTy =
1361       FunctionType::get(Type::getVoidTy(Context), { T_int64 }, false);
1362   Function *F = cast<Function>(M.getOrInsertFunction("func", FTy));
1363   Argument *Arg = &*F->arg_begin();
1364   ConstantInt *C = ConstantInt::get(Context, APInt(64, -1));
1365 
1366   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1367   BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1368 
1369   IRBuilder<> Builder(Entry);
1370   auto *S1 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1371   auto *S2 = cast<Instruction>(Builder.CreateAdd(Arg, C, "add"));
1372   S2->setHasNoSignedWrap(true);
1373   Builder.CreateBr(Exit);
1374 
1375   Builder.SetInsertPoint(Exit);
1376   auto *R = cast<Instruction>(Builder.CreateRetVoid());
1377 
1378   ScalarEvolution SE = buildSE(*F);
1379   // Get S2 first to move it to cache.
1380   const SCEV *SC2 = SE.getSCEV(S2);
1381   EXPECT_TRUE(isa<SCEVAddExpr>(SC2));
1382   // Now get S1.
1383   const SCEV *SC1 = SE.getSCEV(S1);
1384   EXPECT_TRUE(isa<SCEVAddExpr>(SC1));
1385   // Expand for S1, it should use S1 not S2 in spite S2
1386   // first in the cache.
1387   SCEVExpander Exp(SE, M.getDataLayout(), "expander");
1388   auto *I = cast<Instruction>(Exp.expandCodeFor(SC1, nullptr, R));
1389   EXPECT_FALSE(I->hasNoSignedWrap());
1390 }
1391 
1392 // Check logic of SCEV expression size computation.
1393 TEST_F(ScalarEvolutionsTest, SCEVComputeExpressionSize) {
1394   /*
1395    * Create the following code:
1396    * void func(i64 %a, i64 %b)
1397    * entry:
1398    *  %s1 = add i64 %a, 1
1399    *  %s2 = udiv i64 %s1, %b
1400    *  br label %exit
1401    * exit:
1402    *  ret
1403    */
1404 
1405   // Create a module.
1406   Module M("SCEVComputeExpressionSize", Context);
1407 
1408   Type *T_int64 = Type::getInt64Ty(Context);
1409 
1410   FunctionType *FTy =
1411       FunctionType::get(Type::getVoidTy(Context), { T_int64, T_int64 }, false);
1412   Function *F = cast<Function>(M.getOrInsertFunction("func", FTy));
1413   Argument *A = &*F->arg_begin();
1414   Argument *B = &*std::next(F->arg_begin());
1415   ConstantInt *C = ConstantInt::get(Context, APInt(64, 1));
1416 
1417   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
1418   BasicBlock *Exit = BasicBlock::Create(Context, "exit", F);
1419 
1420   IRBuilder<> Builder(Entry);
1421   auto *S1 = cast<Instruction>(Builder.CreateAdd(A, C, "s1"));
1422   auto *S2 = cast<Instruction>(Builder.CreateUDiv(S1, B, "s2"));
1423   Builder.CreateBr(Exit);
1424 
1425   Builder.SetInsertPoint(Exit);
1426   Builder.CreateRetVoid();
1427 
1428   ScalarEvolution SE = buildSE(*F);
1429   // Get S2 first to move it to cache.
1430   const SCEV *AS = SE.getSCEV(A);
1431   const SCEV *BS = SE.getSCEV(B);
1432   const SCEV *CS = SE.getSCEV(C);
1433   const SCEV *S1S = SE.getSCEV(S1);
1434   const SCEV *S2S = SE.getSCEV(S2);
1435   EXPECT_EQ(AS->getExpressionSize(), 1u);
1436   EXPECT_EQ(BS->getExpressionSize(), 1u);
1437   EXPECT_EQ(CS->getExpressionSize(), 1u);
1438   EXPECT_EQ(S1S->getExpressionSize(), 3u);
1439   EXPECT_EQ(S2S->getExpressionSize(), 5u);
1440 }
1441 
1442 }  // end anonymous namespace
1443 }  // end namespace llvm
1444