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