blob: c4a2113d43b055001a2c130f79d52726b3136893 [file] [log] [blame]
Dan Gohman7cac9572010-08-02 23:49:30 +00001//===- ScalarEvolutionsTest.cpp - ScalarEvolution unit tests --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dan Gohman7cac9572010-08-02 23:49:30 +00006//
7//===----------------------------------------------------------------------===//
8
Keno Fischer090f1952017-05-27 03:22:55 +00009#include "llvm/ADT/SmallVector.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000010#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000011#include "llvm/Analysis/LoopInfo.h"
Keno Fischer090f1952017-05-27 03:22:55 +000012#include "llvm/Analysis/ScalarEvolutionExpander.h"
13#include "llvm/Analysis/ScalarEvolutionExpressions.h"
14#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000015#include "llvm/AsmParser/Parser.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
Chandler Carruth2f1fd162015-08-17 02:08:17 +000017#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/GlobalVariable.h"
Keno Fischer090f1952017-05-27 03:22:55 +000019#include "llvm/IR/IRBuilder.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000020#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000022#include "llvm/IR/LegacyPassManager.h"
Keno Fischer090f1952017-05-27 03:22:55 +000023#include "llvm/IR/Module.h"
Sanjoy Das507dd402016-10-18 17:45:16 +000024#include "llvm/IR/Verifier.h"
25#include "llvm/Support/SourceMgr.h"
Dan Gohman7cac9572010-08-02 23:49:30 +000026#include "gtest/gtest.h"
27
28namespace llvm {
29namespace {
30
Nick Lewycky287682e2011-10-04 06:51:26 +000031// We use this fixture to ensure that we clean up ScalarEvolution before
32// deleting the PassManager.
33class ScalarEvolutionsTest : public testing::Test {
34protected:
Dan Gohman7cac9572010-08-02 23:49:30 +000035 LLVMContext Context;
Nick Lewycky287682e2011-10-04 06:51:26 +000036 Module M;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000037 TargetLibraryInfoImpl TLII;
38 TargetLibraryInfo TLI;
39
Daniel Jasperaec2fa32016-12-19 08:22:17 +000040 std::unique_ptr<AssumptionCache> AC;
Chandler Carruth2f1fd162015-08-17 02:08:17 +000041 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) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +000047 AC.reset(new AssumptionCache(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +000048 DT.reset(new DominatorTree(F));
49 LI.reset(new LoopInfo(*DT));
Daniel Jasperaec2fa32016-12-19 08:22:17 +000050 return ScalarEvolution(F, TLI, *AC, *DT, *LI);
Chandler Carruth2f1fd162015-08-17 02:08:17 +000051 }
Sanjoy Das6764b9a2016-11-10 07:56:05 +000052
Sanjoy Das044f9562017-04-14 23:47:53 +000053 void runWithSE(
Sanjoy Dasb1227db2016-12-12 14:57:11 +000054 Module &M, StringRef FuncName,
Sanjoy Das044f9562017-04-14 23:47:53 +000055 function_ref<void(Function &F, LoopInfo &LI, ScalarEvolution &SE)> Test) {
Reid Kleckner30422ee2016-12-12 18:52:32 +000056 auto *F = M.getFunction(FuncName);
57 ASSERT_NE(F, nullptr) << "Could not find " << FuncName;
58 ScalarEvolution SE = buildSE(*F);
Sanjoy Das044f9562017-04-14 23:47:53 +000059 Test(*F, *LI, SE);
Sanjoy Das6764b9a2016-11-10 07:56:05 +000060 }
Nick Lewycky287682e2011-10-04 06:51:26 +000061};
Dan Gohman7cac9572010-08-02 23:49:30 +000062
Nick Lewycky287682e2011-10-04 06:51:26 +000063TEST_F(ScalarEvolutionsTest, SCEVUnknownRAUW) {
Chris Lattner229907c2011-07-18 04:54:35 +000064 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Context),
Jay Foadb804a2b2011-07-12 14:06:48 +000065 std::vector<Type *>(), false);
Dan Gohman7cac9572010-08-02 23:49:30 +000066 Function *F = cast<Function>(M.getOrInsertFunction("f", FTy));
67 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
Craig Topper66f09ad2014-06-08 22:29:17 +000068 ReturnInst::Create(Context, nullptr, BB);
Dan Gohman7cac9572010-08-02 23:49:30 +000069
Chris Lattner229907c2011-07-18 04:54:35 +000070 Type *Ty = Type::getInt1Ty(Context);
Dan Gohman7cac9572010-08-02 23:49:30 +000071 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
Chandler Carruth2f1fd162015-08-17 02:08:17 +000076 ScalarEvolution SE = buildSE(*F);
Dan Gohman7cac9572010-08-02 23:49:30 +000077
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);
Nick Lewycky287682e2011-10-04 06:51:26 +0000110}
Dan Gohman7cac9572010-08-02 23:49:30 +0000111
Tobias Grosser11332e52016-02-21 17:42:10 +0000112TEST_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);
Tobias Grosser946ca0a2016-02-22 07:20:40 +0000130 auto *ZeroConst = SE.getConstant(Ty, 0);
Tobias Grosser11332e52016-02-21 17:42:10 +0000131
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.
Tobias Grosser946ca0a2016-02-22 07:20:40 +0000135 EXPECT_EQ(S1, ZeroConst);
136 EXPECT_EQ(S1, S2);
Tobias Grosser11332e52016-02-21 17:42:10 +0000137}
138
Wei Mi3076cc32016-09-15 04:06:44 +0000139TEST_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
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000167 const DataLayout &DL = F->getParent()->getDataLayout();
Wei Mi3076cc32016-09-15 04:06:44 +0000168 BranchInst *Br = BranchInst::Create(
169 LoopBB, ExitBB, UndefValue::get(Type::getInt1Ty(Context)), LoopBB);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000170 AllocaInst *Alloca = new AllocaInst(I32Ty, DL.getAllocaAddrSpace(),
171 "alloca", Br);
Wei Mi3076cc32016-09-15 04:06:44 +0000172 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
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000205static Instruction *getInstructionByName(Function &F, StringRef Name) {
206 for (auto &I : instructions(F))
207 if (I.getName() == Name)
208 return &I;
Sanjoy Das507dd402016-10-18 17:45:16 +0000209 llvm_unreachable("Expected to find instruction!");
210}
211
212TEST_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\" "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000217 " "
Sanjoy Das299e6722016-10-30 23:52:56 +0000218 "@var_0 = external global i32, align 4"
219 "@var_1 = external global i32, align 4"
Sanjoy Dasfd080902016-10-31 03:32:45 +0000220 "@var_2 = external global i32, align 4"
Sanjoy Das299e6722016-10-30 23:52:56 +0000221 " "
Sanjoy Das17078692016-10-31 03:32:43 +0000222 "declare i32 @unknown(i32, i32, i32)"
223 " "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000224 "define void @f_1(i8* nocapture %arr, i32 %n, i32* %A, i32* %B) "
Sanjoy Das507dd402016-10-18 17:45:16 +0000225 " 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 " "
Sanjoy Dasb53021d2016-10-30 23:52:50 +0000254 "define void @f_2(i32* %X, i32* %Y, i32* %Z) { "
Sanjoy Das507dd402016-10-18 17:45:16 +0000255 " %x = load i32, i32* %X "
256 " %y = load i32, i32* %Y "
257 " %z = load i32, i32* %Z "
258 " ret void "
Sanjoy Das299e6722016-10-30 23:52:56 +0000259 "} "
260 " "
Sanjoy Das299e6722016-10-30 23:52:56 +0000261 "define void @f_3() { "
262 " %x = load i32, i32* @var_0"
263 " %y = load i32, i32* @var_1"
Sanjoy Dasfd080902016-10-31 03:32:45 +0000264 " %z = load i32, i32* @var_2"
Sanjoy Das299e6722016-10-30 23:52:56 +0000265 " ret void"
266 "} "
Sanjoy Das17078692016-10-31 03:32:43 +0000267 " "
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 "} "
Sanjoy Das299e6722016-10-30 23:52:56 +0000274 ,
Sanjoy Das507dd402016-10-18 17:45:16 +0000275 Err, C);
276
277 assert(M && "Could not parse module?");
278 assert(!verifyModule(*M) && "Must have been well formed!");
279
Sanjoy Das044f9562017-04-14 23:47:53 +0000280 runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
Sanjoy Das3d6e3df2016-10-31 03:32:39 +0000281 auto *IV0 = getInstructionByName(F, "iv0");
282 auto *IV0Inc = getInstructionByName(F, "iv0.inc");
Sanjoy Das507dd402016-10-18 17:45:16 +0000283
Sanjoy Das507dd402016-10-18 17:45:16 +0000284 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));
Sanjoy Das3d6e3df2016-10-31 03:32:39 +0000291 });
Sanjoy Das507dd402016-10-18 17:45:16 +0000292
Sanjoy Das17078692016-10-31 03:32:43 +0000293 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));
Sanjoy Das507dd402016-10-18 17:45:16 +0000298
Sanjoy Das17078692016-10-31 03:32:43 +0000299 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};
Sanjoy Das507dd402016-10-18 17:45:16 +0000305
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
Sanjoy Das17078692016-10-31 03:32:43 +0000313 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
Sanjoy Dasfd080902016-10-31 03:32:45 +0000320 for (StringRef FuncName : {"f_2", "f_3", "f_4"})
Sanjoy Das044f9562017-04-14 23:47:53 +0000321 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 });
Sanjoy Das507dd402016-10-18 17:45:16 +0000327}
328
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000329TEST_F(ScalarEvolutionsTest, CompareSCEVComplexity) {
Daniil Fukalov4c3322c2016-11-17 16:07:52 +0000330 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
Sanjoy Das1bd479d2017-03-05 23:49:17 +0000396TEST_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
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000432TEST_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);
Chandler Carruthcd07efc2017-02-06 21:27:12 +0000449 // 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++) {
Daniil Fukalov6378bdb2017-02-06 12:38:06 +0000454 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
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000464static 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
471TEST_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 "} "
Sanjoy Dasbbebcb62017-04-25 00:09:19 +0000501 " "
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 "} "
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000520 ,
521 Err, C);
522
523 assert(M && "Could not parse module?");
524 assert(!verifyModule(*M) && "Must have been well formed!");
525
Sanjoy Das044f9562017-04-14 23:47:53 +0000526 runWithSE(*M, "f_1", [&](Function &F, LoopInfo &LI, ScalarEvolution &SE) {
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000527 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 });
Sanjoy Dasbbebcb62017-04-25 00:09:19 +0000544
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 });
Sanjoy Dasb600d3f2017-04-14 15:50:04 +0000623}
624
Wei Mi8c405332017-04-17 20:40:05 +0000625// Expect the call of getZeroExtendExpr will not cost exponential time.
626TEST_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
Max Kazantsev65cb9d72018-11-08 05:07:58 +0000703 Accum = GetElementPtrInst::Create(I8Ty, Accum, PN, "gep", EndBB);
Wei Mi8c405332017-04-17 20:40:05 +0000704
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}
Keno Fischer090f1952017-05-27 03:22:55 +0000714
715// Make sure that SCEV doesn't introduce illegal ptrtoint/inttoptr instructions
716TEST_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);
Gor Nishanove5d29112017-05-27 05:24:30 +0000774 Value *GepBase = Builder.CreateGEP(Arg, ConstantInt::get(T_int64, 1));
Keno Fischer090f1952017-05-27 03:22:55 +0000775 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
Max Kazantsev2cb36532017-08-03 08:41:30 +0000791// Make sure that SCEV invalidates exit limits after invalidating the values it
792// depends on when we forget a loop.
793TEST_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
Max Kazantsev2cb36532017-08-03 08:41:30 +0000826 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));
Max Kazantsevba1e70e2017-08-04 05:06:44 +0000855 EXPECT_TRUE(isa<SCEVConstant>(EC));
Max Kazantsev6e724762017-08-04 06:03:51 +0000856 EXPECT_EQ(cast<SCEVConstant>(EC)->getAPInt().getLimitedValue(), 999u);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000857
Sanjoy Dase6b995f2017-10-13 05:50:52 +0000858 // 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
Max Kazantsev2cb36532017-08-03 08:41:30 +0000869 SE.forgetLoop(Loop);
870 Br->eraseFromParent();
871 Cond->eraseFromParent();
872
873 Builder.SetInsertPoint(L);
Benjamin Kramera73b4102017-08-03 15:59:37 +0000874 auto *NewCond = Builder.CreateICmp(
875 ICmpInst::ICMP_SLT, Add, ConstantInt::get(T_int64, 2000), "new.cond");
876 Builder.CreateCondBr(NewCond, L, Post);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000877 const SCEV *NewEC = SE.getBackedgeTakenCount(Loop);
Max Kazantsevba1e70e2017-08-04 05:06:44 +0000878 EXPECT_FALSE(isa<SCEVCouldNotCompute>(NewEC));
879 EXPECT_TRUE(isa<SCEVConstant>(NewEC));
Max Kazantsev6e724762017-08-04 06:03:51 +0000880 EXPECT_EQ(cast<SCEVConstant>(NewEC)->getAPInt().getLimitedValue(), 1999u);
Sanjoy Dase6b995f2017-10-13 05:50:52 +0000881 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);
Max Kazantsev2cb36532017-08-03 08:41:30 +0000886}
887
Sanjoy Das3a5e2522017-10-17 01:03:56 +0000888// Make sure that SCEV invalidates exit limits after invalidating the values it
889// depends on when we forget a value.
890TEST_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
Daniel Neilson3f0e4ad2017-09-05 19:54:03 +0000972TEST_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
Daniel Neilson5acfd1d2017-10-11 19:05:14 +00001027TEST_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
Daniel Neilson1341ac22017-09-22 15:47:57 +00001084TEST_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);
Daniel Neilson1341ac22017-09-22 15:47:57 +00001110 // Verify that the SCEV was folded to 0
1111 const auto *ZeroConst = SE.getConstant(Int32Ty, 0);
1112 EXPECT_EQ(Expr, ZeroConst);
1113}
1114
Max Kazantsev87f4a3d2017-11-16 05:10:56 +00001115// Check that we can correctly identify the points at which the SCEV of the
1116// AddRec can be expanded.
1117TEST_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
Serguei Katkovda56a7f2017-12-27 08:26:22 +00001186// Check that SCEV expander does not use the nuw instruction
1187// for expansion.
1188TEST_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.
1240TEST_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
Serguei Katkov6a7a4c62018-01-09 06:47:14 +00001290// Check that SCEV does not save the SCEV -> V
1291// mapping of SCEV differ from V in NUW flag.
1292TEST_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.
1343TEST_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
Max Kazantsev85c98832019-01-21 06:19:50 +00001392// Check logic of SCEV expression size computation.
1393TEST_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 auto *R = cast<Instruction>(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(), 1);
1436 EXPECT_EQ(BS->getExpressionSize(), 1);
1437 EXPECT_EQ(CS->getExpressionSize(), 1);
1438 EXPECT_EQ(S1S->getExpressionSize(), 3);
1439 EXPECT_EQ(S2S->getExpressionSize(), 5);
1440}
1441
Dan Gohman7cac9572010-08-02 23:49:30 +00001442} // end anonymous namespace
1443} // end namespace llvm