Nick Lewycky | af50837 | 2016-04-24 17:55:41 +0000 | [diff] [blame] | 1 | //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===// |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file contains the implementation of the scalar evolution expander, |
| 11 | // which is used to generate the code corresponding to a given scalar evolution |
| 12 | // expression. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 16 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SmallSet.h" |
Benjamin Kramer | 8dd637a | 2014-06-21 11:47:18 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/InstructionSimplify.h" |
Bill Wendling | f3baad3 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | 26c59fa | 2013-01-07 14:41:08 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 22 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 23 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 24 | #include "llvm/IR/IntrinsicInst.h" |
| 25 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Module.h" |
Jingyue Wu | 6f72aed | 2015-06-24 19:28:40 +0000 | [diff] [blame] | 27 | #include "llvm/IR/PatternMatch.h" |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 28 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 29 | #include "llvm/Support/raw_ostream.h" |
Andrew Trick | 244e2c3 | 2011-07-16 00:59:39 +0000 | [diff] [blame] | 30 | |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 31 | using namespace llvm; |
Jingyue Wu | 6f72aed | 2015-06-24 19:28:40 +0000 | [diff] [blame] | 32 | using namespace PatternMatch; |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 33 | |
Gabor Greif | 8e66a42 | 2010-07-09 16:42:04 +0000 | [diff] [blame] | 34 | /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP, |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 35 | /// reusing an existing cast if a suitable one exists, moving an existing |
| 36 | /// cast if a suitable one exists but isn't in the right place, or |
Gabor Greif | 8e66a42 | 2010-07-09 16:42:04 +0000 | [diff] [blame] | 37 | /// creating a new one. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 38 | Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty, |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 39 | Instruction::CastOps Op, |
| 40 | BasicBlock::iterator IP) { |
Rafael Espindola | cd06b48 | 2012-02-22 03:21:39 +0000 | [diff] [blame] | 41 | // This function must be called with the builder having a valid insertion |
| 42 | // point. It doesn't need to be the actual IP where the uses of the returned |
| 43 | // cast will be added, but it must dominate such IP. |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 44 | // We use this precondition to produce a cast that will dominate all its |
| 45 | // uses. In particular, this is crucial for the case where the builder's |
| 46 | // insertion point *is* the point where we were asked to put the cast. |
Sylvestre Ledru | 35521e2 | 2012-07-23 08:51:15 +0000 | [diff] [blame] | 47 | // Since we don't know the builder's insertion point is actually |
Rafael Espindola | cd06b48 | 2012-02-22 03:21:39 +0000 | [diff] [blame] | 48 | // where the uses will be added (only that it dominates it), we are |
| 49 | // not allowed to move it. |
| 50 | BasicBlock::iterator BIP = Builder.GetInsertPoint(); |
| 51 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 52 | Instruction *Ret = nullptr; |
Rafael Espindola | 82d9575 | 2012-02-18 17:22:58 +0000 | [diff] [blame] | 53 | |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 54 | // Check to see if there is already a cast! |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 55 | for (User *U : V->users()) |
Gabor Greif | 3b740e9 | 2010-07-09 16:39:02 +0000 | [diff] [blame] | 56 | if (U->getType() == Ty) |
Gabor Greif | 8e66a42 | 2010-07-09 16:42:04 +0000 | [diff] [blame] | 57 | if (CastInst *CI = dyn_cast<CastInst>(U)) |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 58 | if (CI->getOpcode() == Op) { |
Rafael Espindola | 337cfaf | 2012-02-22 03:44:46 +0000 | [diff] [blame] | 59 | // If the cast isn't where we want it, create a new cast at IP. |
| 60 | // Likewise, do not reuse a cast at BIP because it must dominate |
| 61 | // instructions that might be inserted before BIP. |
Rafael Espindola | cd06b48 | 2012-02-22 03:21:39 +0000 | [diff] [blame] | 62 | if (BasicBlock::iterator(CI) != IP || BIP == IP) { |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 63 | // Create a new cast, and leave the old cast in place in case |
| 64 | // it is being used as an insert point. Clear its operand |
| 65 | // so that it doesn't hold anything live. |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 66 | Ret = CastInst::Create(Op, V, Ty, "", &*IP); |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 67 | Ret->takeName(CI); |
| 68 | CI->replaceAllUsesWith(Ret); |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 69 | CI->setOperand(0, UndefValue::get(V->getType())); |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 70 | break; |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 71 | } |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 72 | Ret = CI; |
| 73 | break; |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 74 | } |
| 75 | |
| 76 | // Create a new cast. |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 77 | if (!Ret) |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 78 | Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP); |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 79 | |
| 80 | // We assert at the end of the function since IP might point to an |
| 81 | // instruction with different dominance properties than a cast |
| 82 | // (an invoke for example) and not dominate BIP (but the cast does). |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 83 | assert(SE.DT.dominates(Ret, &*BIP)); |
Rafael Espindola | 09a4201 | 2012-02-27 02:13:03 +0000 | [diff] [blame] | 84 | |
| 85 | rememberInstruction(Ret); |
| 86 | return Ret; |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 87 | } |
| 88 | |
David Majnemer | dd9a815 | 2015-10-27 07:36:42 +0000 | [diff] [blame] | 89 | static BasicBlock::iterator findInsertPointAfter(Instruction *I, |
David Majnemer | dd9a815 | 2015-10-27 07:36:42 +0000 | [diff] [blame] | 90 | BasicBlock *MustDominate) { |
| 91 | BasicBlock::iterator IP = ++I->getIterator(); |
| 92 | if (auto *II = dyn_cast<InvokeInst>(I)) |
| 93 | IP = II->getNormalDest()->begin(); |
David Majnemer | dd9a815 | 2015-10-27 07:36:42 +0000 | [diff] [blame] | 94 | |
| 95 | while (isa<PHINode>(IP)) |
| 96 | ++IP; |
| 97 | |
David Majnemer | fa8681e4 | 2016-02-03 21:30:31 +0000 | [diff] [blame] | 98 | if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) { |
| 99 | ++IP; |
| 100 | } else if (isa<CatchSwitchInst>(IP)) { |
| 101 | IP = MustDominate->getFirstInsertionPt(); |
| 102 | } else { |
| 103 | assert(!IP->isEHPad() && "unexpected eh pad!"); |
David Majnemer | dd9a815 | 2015-10-27 07:36:42 +0000 | [diff] [blame] | 104 | } |
| 105 | |
| 106 | return IP; |
| 107 | } |
| 108 | |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 109 | /// InsertNoopCastOfTo - Insert a cast of V to the specified type, |
| 110 | /// which must be possible with a noop cast, doing what we can to share |
| 111 | /// the casts. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 112 | Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) { |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 113 | Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false); |
| 114 | assert((Op == Instruction::BitCast || |
| 115 | Op == Instruction::PtrToInt || |
| 116 | Op == Instruction::IntToPtr) && |
| 117 | "InsertNoopCastOfTo cannot perform non-noop casts!"); |
| 118 | assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) && |
| 119 | "InsertNoopCastOfTo cannot change sizes!"); |
| 120 | |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 121 | // Short-circuit unnecessary bitcasts. |
Andrew Trick | e0ced62 | 2011-12-14 22:07:19 +0000 | [diff] [blame] | 122 | if (Op == Instruction::BitCast) { |
| 123 | if (V->getType() == Ty) |
| 124 | return V; |
| 125 | if (CastInst *CI = dyn_cast<CastInst>(V)) { |
| 126 | if (CI->getOperand(0)->getType() == Ty) |
| 127 | return CI->getOperand(0); |
| 128 | } |
| 129 | } |
Dan Gohman | 66e038a | 2009-04-16 15:52:57 +0000 | [diff] [blame] | 130 | // Short-circuit unnecessary inttoptr<->ptrtoint casts. |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 131 | if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) && |
Dan Gohman | 150b4c3 | 2009-05-01 17:00:00 +0000 | [diff] [blame] | 132 | SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 133 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 134 | if ((CI->getOpcode() == Instruction::PtrToInt || |
| 135 | CI->getOpcode() == Instruction::IntToPtr) && |
| 136 | SE.getTypeSizeInBits(CI->getType()) == |
| 137 | SE.getTypeSizeInBits(CI->getOperand(0)->getType())) |
| 138 | return CI->getOperand(0); |
Dan Gohman | 150b4c3 | 2009-05-01 17:00:00 +0000 | [diff] [blame] | 139 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 140 | if ((CE->getOpcode() == Instruction::PtrToInt || |
| 141 | CE->getOpcode() == Instruction::IntToPtr) && |
| 142 | SE.getTypeSizeInBits(CE->getType()) == |
| 143 | SE.getTypeSizeInBits(CE->getOperand(0)->getType())) |
| 144 | return CE->getOperand(0); |
| 145 | } |
Dan Gohman | 66e038a | 2009-04-16 15:52:57 +0000 | [diff] [blame] | 146 | |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 147 | // Fold a cast of a constant. |
Chris Lattner | a6da69c | 2006-02-04 09:51:53 +0000 | [diff] [blame] | 148 | if (Constant *C = dyn_cast<Constant>(V)) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 149 | return ConstantExpr::getCast(Op, C, Ty); |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 150 | |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 151 | // Cast the argument at the beginning of the entry block, after |
| 152 | // any bitcasts of other arguments. |
Chris Lattner | a6da69c | 2006-02-04 09:51:53 +0000 | [diff] [blame] | 153 | if (Argument *A = dyn_cast<Argument>(V)) { |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 154 | BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin(); |
| 155 | while ((isa<BitCastInst>(IP) && |
| 156 | isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) && |
| 157 | cast<BitCastInst>(IP)->getOperand(0) != A) || |
David Majnemer | dd9a815 | 2015-10-27 07:36:42 +0000 | [diff] [blame] | 158 | isa<DbgInfoIntrinsic>(IP)) |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 159 | ++IP; |
| 160 | return ReuseOrCreateCast(A, Ty, Op, IP); |
Chris Lattner | a6da69c | 2006-02-04 09:51:53 +0000 | [diff] [blame] | 161 | } |
Wojciech Matyjewicz | 784d071e1 | 2008-02-09 18:30:13 +0000 | [diff] [blame] | 162 | |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 163 | // Cast the instruction immediately after the instruction. |
Chris Lattner | a6da69c | 2006-02-04 09:51:53 +0000 | [diff] [blame] | 164 | Instruction *I = cast<Instruction>(V); |
David Majnemer | 235acde | 2015-10-27 19:48:28 +0000 | [diff] [blame] | 165 | BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock()); |
Dan Gohman | d277246 | 2010-06-19 13:25:23 +0000 | [diff] [blame] | 166 | return ReuseOrCreateCast(I, Ty, Op, IP); |
Chris Lattner | a6da69c | 2006-02-04 09:51:53 +0000 | [diff] [blame] | 167 | } |
| 168 | |
Chris Lattner | e71f144 | 2007-04-13 05:04:18 +0000 | [diff] [blame] | 169 | /// InsertBinop - Insert the specified binary operator, doing a small amount |
| 170 | /// of work to avoid inserting an obviously redundant operation. |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 171 | Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, |
| 172 | Value *LHS, Value *RHS) { |
Dan Gohman | 00cb117 | 2007-06-15 19:21:55 +0000 | [diff] [blame] | 173 | // Fold a binop with constant operands. |
| 174 | if (Constant *CLHS = dyn_cast<Constant>(LHS)) |
| 175 | if (Constant *CRHS = dyn_cast<Constant>(RHS)) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 176 | return ConstantExpr::get(Opcode, CLHS, CRHS); |
Dan Gohman | 00cb117 | 2007-06-15 19:21:55 +0000 | [diff] [blame] | 177 | |
Chris Lattner | e71f144 | 2007-04-13 05:04:18 +0000 | [diff] [blame] | 178 | // Do a quick scan to see if we have this binop nearby. If so, reuse it. |
| 179 | unsigned ScanLimit = 6; |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 180 | BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); |
| 181 | // Scanning starts from the last instruction before the insertion point. |
| 182 | BasicBlock::iterator IP = Builder.GetInsertPoint(); |
| 183 | if (IP != BlockBegin) { |
Wojciech Matyjewicz | ae9753b2 | 2008-06-15 19:07:39 +0000 | [diff] [blame] | 184 | --IP; |
| 185 | for (; ScanLimit; --IP, --ScanLimit) { |
Dale Johannesen | f5cc1cd | 2010-03-05 21:12:40 +0000 | [diff] [blame] | 186 | // Don't count dbg.value against the ScanLimit, to avoid perturbing the |
| 187 | // generated code. |
| 188 | if (isa<DbgInfoIntrinsic>(IP)) |
| 189 | ScanLimit++; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 190 | if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS && |
| 191 | IP->getOperand(1) == RHS) |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 192 | return &*IP; |
Wojciech Matyjewicz | ae9753b2 | 2008-06-15 19:07:39 +0000 | [diff] [blame] | 193 | if (IP == BlockBegin) break; |
| 194 | } |
Chris Lattner | e71f144 | 2007-04-13 05:04:18 +0000 | [diff] [blame] | 195 | } |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 196 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 197 | // Save the original insertion point so we can restore it when we're done. |
Benjamin Kramer | 6e93152 | 2013-09-30 15:40:17 +0000 | [diff] [blame] | 198 | DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc(); |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 199 | SCEVInsertPointGuard Guard(Builder, this); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 200 | |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 201 | // Move the insertion point out of as many loops as we can. |
| 202 | while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { |
| 203 | if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break; |
| 204 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 205 | if (!Preheader) break; |
Sanjoy Das | 3d75b62 | 2016-11-10 07:56:12 +0000 | [diff] [blame] | 206 | |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 207 | // Ok, move up a level. |
| 208 | Builder.SetInsertPoint(Preheader->getTerminator()); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 209 | } |
| 210 | |
Wojciech Matyjewicz | ae9753b2 | 2008-06-15 19:07:39 +0000 | [diff] [blame] | 211 | // If we haven't found this binop, insert it. |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 212 | Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS)); |
Benjamin Kramer | 6e93152 | 2013-09-30 15:40:17 +0000 | [diff] [blame] | 213 | BO->setDebugLoc(Loc); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 214 | rememberInstruction(BO); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 215 | |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 216 | return BO; |
Chris Lattner | e71f144 | 2007-04-13 05:04:18 +0000 | [diff] [blame] | 217 | } |
| 218 | |
Dan Gohman | 1789362 | 2009-05-27 02:00:53 +0000 | [diff] [blame] | 219 | /// FactorOutConstant - Test if S is divisible by Factor, using signed |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 220 | /// division. If so, update S with Factor divided out and return true. |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 221 | /// S need not be evenly divisible if a reasonable remainder can be |
Dan Gohman | 1789362 | 2009-05-27 02:00:53 +0000 | [diff] [blame] | 222 | /// computed. |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 223 | /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made |
| 224 | /// unnecessary; in its place, just signed-divide Ops[i] by the scale and |
| 225 | /// check to see if the divide was folded. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 226 | static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder, |
| 227 | const SCEV *Factor, ScalarEvolution &SE, |
| 228 | const DataLayout &DL) { |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 229 | // Everything is divisible by one. |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 230 | if (Factor->isOne()) |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 231 | return true; |
| 232 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 233 | // x/x == 1. |
| 234 | if (S == Factor) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 235 | S = SE.getConstant(S->getType(), 1); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 236 | return true; |
| 237 | } |
| 238 | |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 239 | // For a Constant, check for a multiple of the given factor. |
Dan Gohman | 1789362 | 2009-05-27 02:00:53 +0000 | [diff] [blame] | 240 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 241 | // 0/x == 0. |
| 242 | if (C->isZero()) |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 243 | return true; |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 244 | // Check for divisibility. |
| 245 | if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) { |
| 246 | ConstantInt *CI = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 247 | ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt())); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 248 | // If the quotient is zero and the remainder is non-zero, reject |
| 249 | // the value at this scale. It will be considered for subsequent |
| 250 | // smaller scales. |
| 251 | if (!CI->isZero()) { |
| 252 | const SCEV *Div = SE.getConstant(CI); |
| 253 | S = Div; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 254 | Remainder = SE.getAddExpr( |
| 255 | Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt()))); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 256 | return true; |
| 257 | } |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 258 | } |
Dan Gohman | 1789362 | 2009-05-27 02:00:53 +0000 | [diff] [blame] | 259 | } |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 260 | |
| 261 | // In a Mul, check if there is a constant operand which is a multiple |
| 262 | // of the given factor. |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 263 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 264 | // Size is known, check if there is a constant operand which is a multiple |
| 265 | // of the given factor. If so, we can factor it. |
| 266 | const SCEVConstant *FC = cast<SCEVConstant>(Factor); |
| 267 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0))) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 268 | if (!C->getAPInt().srem(FC->getAPInt())) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 269 | SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end()); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 270 | NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt())); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 271 | S = SE.getMulExpr(NewMulOps); |
| 272 | return true; |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 273 | } |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 274 | } |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 275 | |
| 276 | // In an AddRec, check if both start and step are divisible. |
| 277 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 278 | const SCEV *Step = A->getStepRecurrence(SE); |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 279 | const SCEV *StepRem = SE.getConstant(Step->getType(), 0); |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 280 | if (!FactorOutConstant(Step, StepRem, Factor, SE, DL)) |
Dan Gohman | 1789362 | 2009-05-27 02:00:53 +0000 | [diff] [blame] | 281 | return false; |
| 282 | if (!StepRem->isZero()) |
| 283 | return false; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 284 | const SCEV *Start = A->getStart(); |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 285 | if (!FactorOutConstant(Start, Remainder, Factor, SE, DL)) |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 286 | return false; |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 287 | S = SE.getAddRecExpr(Start, Step, A->getLoop(), |
| 288 | A->getNoWrapFlags(SCEV::FlagNW)); |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 289 | return true; |
| 290 | } |
| 291 | |
| 292 | return false; |
| 293 | } |
| 294 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 295 | /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs |
| 296 | /// is the number of SCEVAddRecExprs present, which are kept at the end of |
| 297 | /// the list. |
| 298 | /// |
| 299 | static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 300 | Type *Ty, |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 301 | ScalarEvolution &SE) { |
| 302 | unsigned NumAddRecs = 0; |
| 303 | for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i) |
| 304 | ++NumAddRecs; |
| 305 | // Group Ops into non-addrecs and addrecs. |
| 306 | SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs); |
| 307 | SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end()); |
| 308 | // Let ScalarEvolution sort and simplify the non-addrecs list. |
| 309 | const SCEV *Sum = NoAddRecs.empty() ? |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 310 | SE.getConstant(Ty, 0) : |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 311 | SE.getAddExpr(NoAddRecs); |
| 312 | // If it returned an add, use the operands. Otherwise it simplified |
| 313 | // the sum into a single value, so just use that. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 314 | Ops.clear(); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 315 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum)) |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 316 | Ops.append(Add->op_begin(), Add->op_end()); |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 317 | else if (!Sum->isZero()) |
| 318 | Ops.push_back(Sum); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 319 | // Then append the addrecs. |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 320 | Ops.append(AddRecs.begin(), AddRecs.end()); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 321 | } |
| 322 | |
| 323 | /// SplitAddRecs - Flatten a list of add operands, moving addrec start values |
| 324 | /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}. |
| 325 | /// This helps expose more opportunities for folding parts of the expressions |
| 326 | /// into GEP indices. |
| 327 | /// |
| 328 | static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 329 | Type *Ty, |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 330 | ScalarEvolution &SE) { |
| 331 | // Find the addrecs. |
| 332 | SmallVector<const SCEV *, 8> AddRecs; |
| 333 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 334 | while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) { |
| 335 | const SCEV *Start = A->getStart(); |
| 336 | if (Start->isZero()) break; |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 337 | const SCEV *Zero = SE.getConstant(Ty, 0); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 338 | AddRecs.push_back(SE.getAddRecExpr(Zero, |
| 339 | A->getStepRecurrence(SE), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 340 | A->getLoop(), |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 341 | A->getNoWrapFlags(SCEV::FlagNW))); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 342 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) { |
| 343 | Ops[i] = Zero; |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 344 | Ops.append(Add->op_begin(), Add->op_end()); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 345 | e += Add->getNumOperands(); |
| 346 | } else { |
| 347 | Ops[i] = Start; |
| 348 | } |
| 349 | } |
| 350 | if (!AddRecs.empty()) { |
| 351 | // Add the addrecs onto the end of the list. |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 352 | Ops.append(AddRecs.begin(), AddRecs.end()); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 353 | // Resort the operand list, moving any constants to the front. |
| 354 | SimplifyAddOperands(Ops, Ty, SE); |
| 355 | } |
| 356 | } |
| 357 | |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 358 | /// expandAddToGEP - Expand an addition expression with a pointer type into |
| 359 | /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps |
| 360 | /// BasicAliasAnalysis and other passes analyze the result. See the rules |
| 361 | /// for getelementptr vs. inttoptr in |
| 362 | /// http://llvm.org/docs/LangRef.html#pointeraliasing |
| 363 | /// for details. |
Dan Gohman | 16e96c0 | 2009-07-20 17:44:17 +0000 | [diff] [blame] | 364 | /// |
Dan Gohman | 510bffc | 2010-01-19 22:26:02 +0000 | [diff] [blame] | 365 | /// Design note: The correctness of using getelementptr here depends on |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 366 | /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as |
| 367 | /// they may introduce pointer arithmetic which may not be safely converted |
| 368 | /// into getelementptr. |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 369 | /// |
| 370 | /// Design note: It might seem desirable for this function to be more |
| 371 | /// loop-aware. If some of the indices are loop-invariant while others |
| 372 | /// aren't, it might seem desirable to emit multiple GEPs, keeping the |
| 373 | /// loop-invariant portions of the overall computation outside the loop. |
| 374 | /// However, there are a few reasons this is not done here. Hoisting simple |
| 375 | /// arithmetic is a low-level optimization that often isn't very |
| 376 | /// important until late in the optimization process. In fact, passes |
| 377 | /// like InstructionCombining will combine GEPs, even if it means |
| 378 | /// pushing loop-invariant computation down into loops, so even if the |
| 379 | /// GEPs were split here, the work would quickly be undone. The |
| 380 | /// LoopStrengthReduction pass, which is usually run quite late (and |
| 381 | /// after the last InstructionCombining pass), takes care of hoisting |
| 382 | /// loop-invariant portions of expressions, after considering what |
| 383 | /// can be folded using target addressing modes. |
| 384 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 385 | Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin, |
| 386 | const SCEV *const *op_end, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 387 | PointerType *PTy, |
| 388 | Type *Ty, |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 389 | Value *V) { |
David Blaikie | 156d46e | 2015-03-24 23:34:31 +0000 | [diff] [blame] | 390 | Type *OriginalElTy = PTy->getElementType(); |
| 391 | Type *ElTy = OriginalElTy; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 392 | SmallVector<Value *, 4> GepIndices; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 393 | SmallVector<const SCEV *, 8> Ops(op_begin, op_end); |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 394 | bool AnyNonZeroIndices = false; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 395 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 396 | // Split AddRecs up into parts as either of the parts may be usable |
| 397 | // without the other. |
| 398 | SplitAddRecs(Ops, Ty, SE); |
| 399 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 400 | Type *IntPtrTy = DL.getIntPtrType(PTy); |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 401 | |
Bob Wilson | 2107eb7 | 2009-12-04 01:33:04 +0000 | [diff] [blame] | 402 | // Descend down the pointer's type and attempt to convert the other |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 403 | // operands into GEP indices, at each level. The first index in a GEP |
| 404 | // indexes into the array implied by the pointer operand; the rest of |
| 405 | // the indices index into the element or field type selected by the |
| 406 | // preceding index. |
| 407 | for (;;) { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 408 | // If the scale size is not 0, attempt to factor out a scale for |
| 409 | // array indexing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 410 | SmallVector<const SCEV *, 8> ScaledOps; |
Dan Gohman | 9f4ea22 | 2010-01-28 06:32:46 +0000 | [diff] [blame] | 411 | if (ElTy->isSized()) { |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 412 | const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy); |
Dan Gohman | 9f4ea22 | 2010-01-28 06:32:46 +0000 | [diff] [blame] | 413 | if (!ElSize->isZero()) { |
| 414 | SmallVector<const SCEV *, 8> NewOps; |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 415 | for (const SCEV *Op : Ops) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 416 | const SCEV *Remainder = SE.getConstant(Ty, 0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 417 | if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) { |
Dan Gohman | 9f4ea22 | 2010-01-28 06:32:46 +0000 | [diff] [blame] | 418 | // Op now has ElSize factored out. |
| 419 | ScaledOps.push_back(Op); |
| 420 | if (!Remainder->isZero()) |
| 421 | NewOps.push_back(Remainder); |
| 422 | AnyNonZeroIndices = true; |
| 423 | } else { |
| 424 | // The operand was not divisible, so add it to the list of operands |
| 425 | // we'll scan next iteration. |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 426 | NewOps.push_back(Op); |
Dan Gohman | 9f4ea22 | 2010-01-28 06:32:46 +0000 | [diff] [blame] | 427 | } |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 428 | } |
Dan Gohman | 9f4ea22 | 2010-01-28 06:32:46 +0000 | [diff] [blame] | 429 | // If we made any changes, update Ops. |
| 430 | if (!ScaledOps.empty()) { |
| 431 | Ops = NewOps; |
| 432 | SimplifyAddOperands(Ops, Ty, SE); |
| 433 | } |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 434 | } |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 435 | } |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 436 | |
| 437 | // Record the scaled array index for this level of the type. If |
| 438 | // we didn't find any operands that could be factored, tentatively |
| 439 | // assume that element zero was selected (since the zero offset |
| 440 | // would obviously be folded away). |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 441 | Value *Scaled = ScaledOps.empty() ? |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 442 | Constant::getNullValue(Ty) : |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 443 | expandCodeFor(SE.getAddExpr(ScaledOps), Ty); |
| 444 | GepIndices.push_back(Scaled); |
| 445 | |
| 446 | // Collect struct field index operands. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 447 | while (StructType *STy = dyn_cast<StructType>(ElTy)) { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 448 | bool FoundFieldNo = false; |
| 449 | // An empty struct has no fields. |
| 450 | if (STy->getNumElements() == 0) break; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 451 | // Field offsets are known. See if a constant offset falls within any of |
| 452 | // the struct fields. |
| 453 | if (Ops.empty()) |
| 454 | break; |
| 455 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0])) |
| 456 | if (SE.getTypeSizeInBits(C->getType()) <= 64) { |
| 457 | const StructLayout &SL = *DL.getStructLayout(STy); |
| 458 | uint64_t FullOffset = C->getValue()->getZExtValue(); |
| 459 | if (FullOffset < SL.getSizeInBytes()) { |
| 460 | unsigned ElIdx = SL.getElementContainingOffset(FullOffset); |
| 461 | GepIndices.push_back( |
| 462 | ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx)); |
| 463 | ElTy = STy->getTypeAtIndex(ElIdx); |
| 464 | Ops[0] = |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 465 | SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx)); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 466 | AnyNonZeroIndices = true; |
| 467 | FoundFieldNo = true; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 468 | } |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 469 | } |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 470 | // If no struct field offsets were found, tentatively assume that |
| 471 | // field zero was selected (since the zero offset would obviously |
| 472 | // be folded away). |
| 473 | if (!FoundFieldNo) { |
| 474 | ElTy = STy->getTypeAtIndex(0u); |
| 475 | GepIndices.push_back( |
| 476 | Constant::getNullValue(Type::getInt32Ty(Ty->getContext()))); |
| 477 | } |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 478 | } |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 479 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 480 | if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 481 | ElTy = ATy->getElementType(); |
| 482 | else |
| 483 | break; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 484 | } |
| 485 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 486 | // If none of the operands were convertible to proper GEP indices, cast |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 487 | // the base to i8* and do an ugly getelementptr with that. It's still |
| 488 | // better than ptrtoint+arithmetic+inttoptr at least. |
| 489 | if (!AnyNonZeroIndices) { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 490 | // Cast the base to i8*. |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 491 | V = InsertNoopCastOfTo(V, |
Duncan Sands | 9ed7b16 | 2009-10-06 15:40:36 +0000 | [diff] [blame] | 492 | Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace())); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 493 | |
Rafael Espindola | 729e3aa | 2012-02-21 03:51:14 +0000 | [diff] [blame] | 494 | assert(!isa<Instruction>(V) || |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 495 | SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint())); |
Rafael Espindola | 7d445e9 | 2012-02-21 01:19:51 +0000 | [diff] [blame] | 496 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 497 | // Expand the operands for a plain byte offset. |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 498 | Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty); |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 499 | |
| 500 | // Fold a GEP with constant operands. |
| 501 | if (Constant *CLHS = dyn_cast<Constant>(V)) |
| 502 | if (Constant *CRHS = dyn_cast<Constant>(Idx)) |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 503 | return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()), |
| 504 | CLHS, CRHS); |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 505 | |
| 506 | // Do a quick scan to see if we have this GEP nearby. If so, reuse it. |
| 507 | unsigned ScanLimit = 6; |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 508 | BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); |
| 509 | // Scanning starts from the last instruction before the insertion point. |
| 510 | BasicBlock::iterator IP = Builder.GetInsertPoint(); |
| 511 | if (IP != BlockBegin) { |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 512 | --IP; |
| 513 | for (; ScanLimit; --IP, --ScanLimit) { |
Dale Johannesen | f5cc1cd | 2010-03-05 21:12:40 +0000 | [diff] [blame] | 514 | // Don't count dbg.value against the ScanLimit, to avoid perturbing the |
| 515 | // generated code. |
| 516 | if (isa<DbgInfoIntrinsic>(IP)) |
| 517 | ScanLimit++; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 518 | if (IP->getOpcode() == Instruction::GetElementPtr && |
| 519 | IP->getOperand(0) == V && IP->getOperand(1) == Idx) |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 520 | return &*IP; |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 521 | if (IP == BlockBegin) break; |
| 522 | } |
| 523 | } |
| 524 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 525 | // Save the original insertion point so we can restore it when we're done. |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 526 | SCEVInsertPointGuard Guard(Builder, this); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 527 | |
| 528 | // Move the insertion point out of as many loops as we can. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 529 | while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 530 | if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break; |
| 531 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 532 | if (!Preheader) break; |
| 533 | |
| 534 | // Ok, move up a level. |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 535 | Builder.SetInsertPoint(Preheader->getTerminator()); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 536 | } |
| 537 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 538 | // Emit a GEP. |
David Blaikie | 93c5444 | 2015-04-03 19:41:44 +0000 | [diff] [blame] | 539 | Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 540 | rememberInstruction(GEP); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 541 | |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 542 | return GEP; |
| 543 | } |
| 544 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 545 | { |
| 546 | SCEVInsertPointGuard Guard(Builder, this); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 547 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 548 | // Move the insertion point out of as many loops as we can. |
| 549 | while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { |
| 550 | if (!L->isLoopInvariant(V)) break; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 551 | |
David Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 552 | bool AnyIndexNotLoopInvariant = any_of( |
| 553 | GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); }); |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 554 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 555 | if (AnyIndexNotLoopInvariant) |
| 556 | break; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 557 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 558 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 559 | if (!Preheader) break; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 560 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 561 | // Ok, move up a level. |
| 562 | Builder.SetInsertPoint(Preheader->getTerminator()); |
| 563 | } |
| 564 | |
| 565 | // Insert a pretty getelementptr. Note that this GEP is not marked inbounds, |
| 566 | // because ScalarEvolution may have changed the address arithmetic to |
| 567 | // compute a value which is beyond the end of the allocated object. |
| 568 | Value *Casted = V; |
| 569 | if (V->getType() != PTy) |
| 570 | Casted = InsertNoopCastOfTo(Casted, PTy); |
| 571 | Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep"); |
| 572 | Ops.push_back(SE.getUnknown(GEP)); |
| 573 | rememberInstruction(GEP); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 574 | } |
| 575 | |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 576 | return expand(SE.getAddExpr(Ops)); |
| 577 | } |
| 578 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 579 | /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for |
| 580 | /// SCEV expansion. If they are nested, this is the most nested. If they are |
| 581 | /// neighboring, pick the later. |
| 582 | static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B, |
| 583 | DominatorTree &DT) { |
| 584 | if (!A) return B; |
| 585 | if (!B) return A; |
| 586 | if (A->contains(B)) return B; |
| 587 | if (B->contains(A)) return A; |
| 588 | if (DT.dominates(A->getHeader(), B->getHeader())) return B; |
| 589 | if (DT.dominates(B->getHeader(), A->getHeader())) return A; |
| 590 | return A; // Arbitrarily break the tie. |
| 591 | } |
| 592 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 593 | /// getRelevantLoop - Get the most relevant loop associated with the given |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 594 | /// expression, according to PickMostRelevantLoop. |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 595 | const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) { |
| 596 | // Test whether we've already computed the most relevant loop for this SCEV. |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 597 | auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr)); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 598 | if (!Pair.second) |
| 599 | return Pair.first->second; |
| 600 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 601 | if (isa<SCEVConstant>(S)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 602 | // A constant has no relevant loops. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 603 | return nullptr; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 604 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 605 | if (const Instruction *I = dyn_cast<Instruction>(U->getValue())) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 606 | return Pair.first->second = SE.LI.getLoopFor(I->getParent()); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 607 | // A non-instruction has no relevant loops. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 608 | return nullptr; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 609 | } |
| 610 | if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 611 | const Loop *L = nullptr; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 612 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 613 | L = AR->getLoop(); |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 614 | for (const SCEV *Op : N->operands()) |
| 615 | L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 616 | return RelevantLoops[N] = L; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 617 | } |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 618 | if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) { |
| 619 | const Loop *Result = getRelevantLoop(C->getOperand()); |
| 620 | return RelevantLoops[C] = Result; |
| 621 | } |
| 622 | if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 623 | const Loop *Result = PickMostRelevantLoop( |
| 624 | getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 625 | return RelevantLoops[D] = Result; |
| 626 | } |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 627 | llvm_unreachable("Unexpected SCEV type!"); |
| 628 | } |
| 629 | |
Dan Gohman | b29cda9 | 2010-04-15 17:08:50 +0000 | [diff] [blame] | 630 | namespace { |
| 631 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 632 | /// LoopCompare - Compare loops by PickMostRelevantLoop. |
| 633 | class LoopCompare { |
| 634 | DominatorTree &DT; |
| 635 | public: |
| 636 | explicit LoopCompare(DominatorTree &dt) : DT(dt) {} |
| 637 | |
| 638 | bool operator()(std::pair<const Loop *, const SCEV *> LHS, |
| 639 | std::pair<const Loop *, const SCEV *> RHS) const { |
Dan Gohman | fbbdfca | 2010-07-15 23:38:13 +0000 | [diff] [blame] | 640 | // Keep pointer operands sorted at the end. |
| 641 | if (LHS.second->getType()->isPointerTy() != |
| 642 | RHS.second->getType()->isPointerTy()) |
| 643 | return LHS.second->getType()->isPointerTy(); |
| 644 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 645 | // Compare loops with PickMostRelevantLoop. |
| 646 | if (LHS.first != RHS.first) |
| 647 | return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first; |
| 648 | |
| 649 | // If one operand is a non-constant negative and the other is not, |
| 650 | // put the non-constant negative on the right so that a sub can |
| 651 | // be used instead of a negate and add. |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 652 | if (LHS.second->isNonConstantNegative()) { |
| 653 | if (!RHS.second->isNonConstantNegative()) |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 654 | return false; |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 655 | } else if (RHS.second->isNonConstantNegative()) |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 656 | return true; |
| 657 | |
| 658 | // Otherwise they are equivalent according to this comparison. |
| 659 | return false; |
| 660 | } |
| 661 | }; |
| 662 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 663 | } |
Dan Gohman | b29cda9 | 2010-04-15 17:08:50 +0000 | [diff] [blame] | 664 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 665 | Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 666 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Dan Gohman | 5bafe38 | 2009-09-26 16:11:57 +0000 | [diff] [blame] | 667 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 668 | // Collect all the add operands in a loop, along with their associated loops. |
| 669 | // Iterate in reverse so that constants are emitted last, all else equal, and |
| 670 | // so that pointer operands are inserted first, which the code below relies on |
| 671 | // to form more involved GEPs. |
| 672 | SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; |
| 673 | for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()), |
| 674 | E(S->op_begin()); I != E; ++I) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 675 | OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I)); |
Dan Gohman | 5bafe38 | 2009-09-26 16:11:57 +0000 | [diff] [blame] | 676 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 677 | // Sort by loop. Use a stable sort so that constants follow non-constants and |
| 678 | // pointer operands precede non-pointer operands. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 679 | std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT)); |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 680 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 681 | // Emit instructions to add all the operands. Hoist as much as possible |
| 682 | // out of loops, and form meaningful getelementptrs where possible. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 683 | Value *Sum = nullptr; |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 684 | for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 685 | const Loop *CurLoop = I->first; |
| 686 | const SCEV *Op = I->second; |
| 687 | if (!Sum) { |
| 688 | // This is the first operand. Just expand it. |
| 689 | Sum = expand(Op); |
| 690 | ++I; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 691 | } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 692 | // The running sum expression is a pointer. Try to form a getelementptr |
| 693 | // at this level with that as the base. |
| 694 | SmallVector<const SCEV *, 4> NewOps; |
Dan Gohman | fbbdfca | 2010-07-15 23:38:13 +0000 | [diff] [blame] | 695 | for (; I != E && I->first == CurLoop; ++I) { |
| 696 | // If the operand is SCEVUnknown and not instructions, peek through |
| 697 | // it, to enable more of it to be folded into the GEP. |
| 698 | const SCEV *X = I->second; |
| 699 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X)) |
| 700 | if (!isa<Instruction>(U->getValue())) |
| 701 | X = SE.getSCEV(U->getValue()); |
| 702 | NewOps.push_back(X); |
| 703 | } |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 704 | Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 705 | } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 706 | // The running sum is an integer, and there's a pointer at this level. |
Dan Gohman | 3295a6e | 2010-04-09 19:14:31 +0000 | [diff] [blame] | 707 | // Try to form a getelementptr. If the running sum is instructions, |
| 708 | // use a SCEVUnknown to avoid re-analyzing them. |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 709 | SmallVector<const SCEV *, 4> NewOps; |
Dan Gohman | 3295a6e | 2010-04-09 19:14:31 +0000 | [diff] [blame] | 710 | NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) : |
| 711 | SE.getSCEV(Sum)); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 712 | for (++I; I != E && I->first == CurLoop; ++I) |
| 713 | NewOps.push_back(I->second); |
| 714 | Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op)); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 715 | } else if (Op->isNonConstantNegative()) { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 716 | // Instead of doing a negate and add, just do a subtract. |
Dan Gohman | 2850b41 | 2010-03-03 04:36:42 +0000 | [diff] [blame] | 717 | Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 718 | Sum = InsertNoopCastOfTo(Sum, Ty); |
| 719 | Sum = InsertBinop(Instruction::Sub, Sum, W); |
| 720 | ++I; |
Dan Gohman | 2850b41 | 2010-03-03 04:36:42 +0000 | [diff] [blame] | 721 | } else { |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 722 | // A simple add. |
Dan Gohman | 2850b41 | 2010-03-03 04:36:42 +0000 | [diff] [blame] | 723 | Value *W = expandCodeFor(Op, Ty); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 724 | Sum = InsertNoopCastOfTo(Sum, Ty); |
| 725 | // Canonicalize a constant to the RHS. |
| 726 | if (isa<Constant>(Sum)) std::swap(Sum, W); |
| 727 | Sum = InsertBinop(Instruction::Add, Sum, W); |
| 728 | ++I; |
Dan Gohman | 2850b41 | 2010-03-03 04:36:42 +0000 | [diff] [blame] | 729 | } |
| 730 | } |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 731 | |
| 732 | return Sum; |
Dan Gohman | 095ca74 | 2008-06-18 16:37:11 +0000 | [diff] [blame] | 733 | } |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 734 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 735 | Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 736 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 737 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 738 | // Collect all the mul operands in a loop, along with their associated loops. |
| 739 | // Iterate in reverse so that constants are emitted last, all else equal. |
| 740 | SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; |
| 741 | for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()), |
| 742 | E(S->op_begin()); I != E; ++I) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 743 | OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I)); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 744 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 745 | // Sort by loop. Use a stable sort so that constants follow non-constants. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 746 | std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT)); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 747 | |
| 748 | // Emit instructions to mul all the operands. Hoist as much as possible |
| 749 | // out of loops. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 750 | Value *Prod = nullptr; |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 751 | for (const auto &I : OpsAndLoops) { |
| 752 | const SCEV *Op = I.second; |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 753 | if (!Prod) { |
| 754 | // This is the first operand. Just expand it. |
| 755 | Prod = expand(Op); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 756 | } else if (Op->isAllOnesValue()) { |
| 757 | // Instead of doing a multiply by negative one, just do a negate. |
| 758 | Prod = InsertNoopCastOfTo(Prod, Ty); |
| 759 | Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod); |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 760 | } else { |
| 761 | // A simple mul. |
| 762 | Value *W = expandCodeFor(Op, Ty); |
| 763 | Prod = InsertNoopCastOfTo(Prod, Ty); |
| 764 | // Canonicalize a constant to the RHS. |
| 765 | if (isa<Constant>(Prod)) std::swap(Prod, W); |
Jingyue Wu | 6f72aed | 2015-06-24 19:28:40 +0000 | [diff] [blame] | 766 | const APInt *RHS; |
| 767 | if (match(W, m_Power2(RHS))) { |
| 768 | // Canonicalize Prod*(1<<C) to Prod<<C. |
| 769 | assert(!Ty->isVectorTy() && "vector types are not SCEVable"); |
| 770 | Prod = InsertBinop(Instruction::Shl, Prod, |
| 771 | ConstantInt::get(Ty, RHS->logBase2())); |
| 772 | } else { |
| 773 | Prod = InsertBinop(Instruction::Mul, Prod, W); |
| 774 | } |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 775 | } |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 776 | } |
| 777 | |
Dan Gohman | 29707de | 2010-03-03 05:29:13 +0000 | [diff] [blame] | 778 | return Prod; |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 779 | } |
| 780 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 781 | Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 782 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 783 | |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 784 | Value *LHS = expandCodeFor(S->getLHS(), Ty); |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 785 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 786 | const APInt &RHS = SC->getAPInt(); |
Nick Lewycky | 3c94704 | 2008-07-08 05:05:37 +0000 | [diff] [blame] | 787 | if (RHS.isPowerOf2()) |
| 788 | return InsertBinop(Instruction::LShr, LHS, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 789 | ConstantInt::get(Ty, RHS.logBase2())); |
Nick Lewycky | 3c94704 | 2008-07-08 05:05:37 +0000 | [diff] [blame] | 790 | } |
| 791 | |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 792 | Value *RHS = expandCodeFor(S->getRHS(), Ty); |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 793 | return InsertBinop(Instruction::UDiv, LHS, RHS); |
Nick Lewycky | 3c94704 | 2008-07-08 05:05:37 +0000 | [diff] [blame] | 794 | } |
| 795 | |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 796 | /// Move parts of Base into Rest to leave Base with the minimal |
| 797 | /// expression that provides a pointer operand suitable for a |
| 798 | /// GEP expansion. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 799 | static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 800 | ScalarEvolution &SE) { |
| 801 | while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) { |
| 802 | Base = A->getStart(); |
| 803 | Rest = SE.getAddExpr(Rest, |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 804 | SE.getAddRecExpr(SE.getConstant(A->getType(), 0), |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 805 | A->getStepRecurrence(SE), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 806 | A->getLoop(), |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 807 | A->getNoWrapFlags(SCEV::FlagNW))); |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 808 | } |
| 809 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) { |
| 810 | Base = A->getOperand(A->getNumOperands()-1); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 811 | SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end()); |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 812 | NewAddOps.back() = Rest; |
| 813 | Rest = SE.getAddExpr(NewAddOps); |
| 814 | ExposePointerBase(Base, Rest, SE); |
| 815 | } |
| 816 | } |
| 817 | |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 818 | /// Determine if this is a well-behaved chain of instructions leading back to |
| 819 | /// the PHI. If so, it may be reused by expanded expressions. |
| 820 | bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, |
| 821 | const Loop *L) { |
| 822 | if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) || |
| 823 | (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) |
| 824 | return false; |
| 825 | // If any of the operands don't dominate the insert position, bail. |
| 826 | // Addrec operands are always loop-invariant, so this can only happen |
| 827 | // if there are instructions which haven't been hoisted. |
| 828 | if (L == IVIncInsertLoop) { |
| 829 | for (User::op_iterator OI = IncV->op_begin()+1, |
| 830 | OE = IncV->op_end(); OI != OE; ++OI) |
| 831 | if (Instruction *OInst = dyn_cast<Instruction>(OI)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 832 | if (!SE.DT.dominates(OInst, IVIncInsertPos)) |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 833 | return false; |
| 834 | } |
| 835 | // Advance to the next instruction. |
| 836 | IncV = dyn_cast<Instruction>(IncV->getOperand(0)); |
| 837 | if (!IncV) |
| 838 | return false; |
| 839 | |
| 840 | if (IncV->mayHaveSideEffects()) |
| 841 | return false; |
| 842 | |
| 843 | if (IncV != PN) |
| 844 | return true; |
| 845 | |
| 846 | return isNormalAddRecExprPHI(PN, IncV, L); |
| 847 | } |
| 848 | |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 849 | /// getIVIncOperand returns an induction variable increment's induction |
| 850 | /// variable operand. |
| 851 | /// |
| 852 | /// If allowScale is set, any type of GEP is allowed as long as the nonIV |
| 853 | /// operands dominate InsertPos. |
| 854 | /// |
| 855 | /// If allowScale is not set, ensure that a GEP increment conforms to one of the |
| 856 | /// simple patterns generated by getAddRecExprPHILiterally and |
| 857 | /// expandAddtoGEP. If the pattern isn't recognized, return NULL. |
| 858 | Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV, |
| 859 | Instruction *InsertPos, |
| 860 | bool allowScale) { |
| 861 | if (IncV == InsertPos) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 862 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 863 | |
| 864 | switch (IncV->getOpcode()) { |
| 865 | default: |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 866 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 867 | // Check for a simple Add/Sub or GEP of a loop invariant step. |
| 868 | case Instruction::Add: |
| 869 | case Instruction::Sub: { |
| 870 | Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 871 | if (!OInst || SE.DT.dominates(OInst, InsertPos)) |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 872 | return dyn_cast<Instruction>(IncV->getOperand(0)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 873 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 874 | } |
| 875 | case Instruction::BitCast: |
| 876 | return dyn_cast<Instruction>(IncV->getOperand(0)); |
| 877 | case Instruction::GetElementPtr: |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 878 | for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) { |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 879 | if (isa<Constant>(*I)) |
| 880 | continue; |
| 881 | if (Instruction *OInst = dyn_cast<Instruction>(*I)) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 882 | if (!SE.DT.dominates(OInst, InsertPos)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 883 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 884 | } |
| 885 | if (allowScale) { |
| 886 | // allow any kind of GEP as long as it can be hoisted. |
| 887 | continue; |
| 888 | } |
| 889 | // This must be a pointer addition of constants (pretty), which is already |
| 890 | // handled, or some number of address-size elements (ugly). Ugly geps |
| 891 | // have 2 operands. i1* is used by the expander to represent an |
| 892 | // address-size element. |
| 893 | if (IncV->getNumOperands() != 2) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 894 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 895 | unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace(); |
| 896 | if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS) |
| 897 | && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 898 | return nullptr; |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 899 | break; |
| 900 | } |
| 901 | return dyn_cast<Instruction>(IncV->getOperand(0)); |
| 902 | } |
| 903 | } |
| 904 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 905 | /// If the insert point of the current builder or any of the builders on the |
| 906 | /// stack of saved builders has 'I' as its insert point, update it to point to |
| 907 | /// the instruction after 'I'. This is intended to be used when the instruction |
| 908 | /// 'I' is being moved. If this fixup is not done and 'I' is moved to a |
| 909 | /// different block, the inconsistent insert point (with a mismatched |
| 910 | /// Instruction and Block) can lead to an instruction being inserted in a block |
| 911 | /// other than its parent. |
| 912 | void SCEVExpander::fixupInsertPoints(Instruction *I) { |
| 913 | BasicBlock::iterator It(*I); |
| 914 | BasicBlock::iterator NewInsertPt = std::next(It); |
| 915 | if (Builder.GetInsertPoint() == It) |
| 916 | Builder.SetInsertPoint(&*NewInsertPt); |
| 917 | for (auto *InsertPtGuard : InsertPointGuards) |
| 918 | if (InsertPtGuard->GetInsertPoint() == It) |
| 919 | InsertPtGuard->SetInsertPoint(NewInsertPt); |
| 920 | } |
| 921 | |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 922 | /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make |
| 923 | /// it available to other uses in this loop. Recursively hoist any operands, |
| 924 | /// until we reach a value that dominates InsertPos. |
| 925 | bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 926 | if (SE.DT.dominates(IncV, InsertPos)) |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 927 | return true; |
| 928 | |
| 929 | // InsertPos must itself dominate IncV so that IncV's new position satisfies |
| 930 | // its existing users. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 931 | if (isa<PHINode>(InsertPos) || |
| 932 | !SE.DT.dominates(InsertPos->getParent(), IncV->getParent())) |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 933 | return false; |
| 934 | |
Sanjoy Das | b771eb6 | 2015-12-08 00:13:17 +0000 | [diff] [blame] | 935 | if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos)) |
| 936 | return false; |
| 937 | |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 938 | // Check that the chain of IV operands leading back to Phi can be hoisted. |
| 939 | SmallVector<Instruction*, 4> IVIncs; |
| 940 | for(;;) { |
| 941 | Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true); |
| 942 | if (!Oper) |
| 943 | return false; |
| 944 | // IncV is safe to hoist. |
| 945 | IVIncs.push_back(IncV); |
| 946 | IncV = Oper; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 947 | if (SE.DT.dominates(IncV, InsertPos)) |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 948 | break; |
| 949 | } |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 950 | for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) { |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 951 | fixupInsertPoints(*I); |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 952 | (*I)->moveBefore(InsertPos); |
| 953 | } |
| 954 | return true; |
| 955 | } |
| 956 | |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 957 | /// Determine if this cyclic phi is in a form that would have been generated by |
| 958 | /// LSR. We don't care if the phi was actually expanded in this pass, as long |
| 959 | /// as it is in a low-cost form, for example, no implied multiplication. This |
| 960 | /// should match any patterns generated by getAddRecExprPHILiterally and |
| 961 | /// expandAddtoGEP. |
| 962 | bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, |
Andrew Trick | fd4ca0f | 2011-10-15 06:19:55 +0000 | [diff] [blame] | 963 | const Loop *L) { |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 964 | for(Instruction *IVOper = IncV; |
| 965 | (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(), |
| 966 | /*allowScale=*/false));) { |
| 967 | if (IVOper == PN) |
| 968 | return true; |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 969 | } |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 970 | return false; |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 971 | } |
| 972 | |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 973 | /// expandIVInc - Expand an IV increment at Builder's current InsertPos. |
| 974 | /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may |
| 975 | /// need to materialize IV increments elsewhere to handle difficult situations. |
| 976 | Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L, |
| 977 | Type *ExpandTy, Type *IntTy, |
| 978 | bool useSubtract) { |
| 979 | Value *IncV; |
| 980 | // If the PHI is a pointer, use a GEP, otherwise use an add or sub. |
| 981 | if (ExpandTy->isPointerTy()) { |
| 982 | PointerType *GEPPtrTy = cast<PointerType>(ExpandTy); |
| 983 | // If the step isn't constant, don't use an implicitly scaled GEP, because |
| 984 | // that would require a multiply inside the loop. |
| 985 | if (!isa<ConstantInt>(StepV)) |
| 986 | GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()), |
| 987 | GEPPtrTy->getAddressSpace()); |
| 988 | const SCEV *const StepArray[1] = { SE.getSCEV(StepV) }; |
| 989 | IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN); |
| 990 | if (IncV->getType() != PN->getType()) { |
| 991 | IncV = Builder.CreateBitCast(IncV, PN->getType()); |
| 992 | rememberInstruction(IncV); |
| 993 | } |
| 994 | } else { |
| 995 | IncV = useSubtract ? |
| 996 | Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") : |
| 997 | Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next"); |
| 998 | rememberInstruction(IncV); |
| 999 | } |
| 1000 | return IncV; |
| 1001 | } |
| 1002 | |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1003 | /// \brief Hoist the addrec instruction chain rooted in the loop phi above the |
| 1004 | /// position. This routine assumes that this is possible (has been checked). |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1005 | void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist, |
| 1006 | Instruction *Pos, PHINode *LoopPhi) { |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1007 | do { |
| 1008 | if (DT->dominates(InstToHoist, Pos)) |
| 1009 | break; |
| 1010 | // Make sure the increment is where we want it. But don't move it |
| 1011 | // down past a potential existing post-inc user. |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1012 | fixupInsertPoints(InstToHoist); |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1013 | InstToHoist->moveBefore(Pos); |
| 1014 | Pos = InstToHoist; |
| 1015 | InstToHoist = cast<Instruction>(InstToHoist->getOperand(0)); |
| 1016 | } while (InstToHoist != LoopPhi); |
| 1017 | } |
| 1018 | |
| 1019 | /// \brief Check whether we can cheaply express the requested SCEV in terms of |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1020 | /// the available PHI SCEV by truncation and/or inversion of the step. |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1021 | static bool canBeCheaplyTransformed(ScalarEvolution &SE, |
| 1022 | const SCEVAddRecExpr *Phi, |
| 1023 | const SCEVAddRecExpr *Requested, |
| 1024 | bool &InvertStep) { |
| 1025 | Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType()); |
| 1026 | Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType()); |
| 1027 | |
| 1028 | if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth()) |
| 1029 | return false; |
| 1030 | |
| 1031 | // Try truncate it if necessary. |
| 1032 | Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy)); |
| 1033 | if (!Phi) |
| 1034 | return false; |
| 1035 | |
| 1036 | // Check whether truncation will help. |
| 1037 | if (Phi == Requested) { |
| 1038 | InvertStep = false; |
| 1039 | return true; |
| 1040 | } |
| 1041 | |
| 1042 | // Check whether inverting will help: {R,+,-1} == R - {0,+,1}. |
| 1043 | if (SE.getAddExpr(Requested->getStart(), |
| 1044 | SE.getNegativeSCEV(Requested)) == Phi) { |
| 1045 | InvertStep = true; |
| 1046 | return true; |
| 1047 | } |
| 1048 | |
| 1049 | return false; |
| 1050 | } |
| 1051 | |
Sanjoy Das | dcc84db | 2015-02-25 20:02:59 +0000 | [diff] [blame] | 1052 | static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { |
| 1053 | if (!isa<IntegerType>(AR->getType())) |
| 1054 | return false; |
| 1055 | |
| 1056 | unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); |
| 1057 | Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); |
| 1058 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 1059 | const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy), |
| 1060 | SE.getSignExtendExpr(AR, WideTy)); |
| 1061 | const SCEV *ExtendAfterOp = |
| 1062 | SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy); |
| 1063 | return ExtendAfterOp == OpAfterExtend; |
| 1064 | } |
| 1065 | |
| 1066 | static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { |
| 1067 | if (!isa<IntegerType>(AR->getType())) |
| 1068 | return false; |
| 1069 | |
| 1070 | unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); |
| 1071 | Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); |
| 1072 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 1073 | const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy), |
| 1074 | SE.getZeroExtendExpr(AR, WideTy)); |
| 1075 | const SCEV *ExtendAfterOp = |
| 1076 | SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy); |
| 1077 | return ExtendAfterOp == OpAfterExtend; |
| 1078 | } |
| 1079 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1080 | /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand |
| 1081 | /// the base addrec, which is the addrec without any non-loop-dominating |
| 1082 | /// values, and return the PHI. |
| 1083 | PHINode * |
| 1084 | SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized, |
| 1085 | const Loop *L, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1086 | Type *ExpandTy, |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1087 | Type *IntTy, |
| 1088 | Type *&TruncTy, |
| 1089 | bool &InvertStep) { |
Benjamin Kramer | a7606b99 | 2011-07-16 22:26:27 +0000 | [diff] [blame] | 1090 | assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position"); |
Andrew Trick | 244e2c3 | 2011-07-16 00:59:39 +0000 | [diff] [blame] | 1091 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1092 | // Reuse a previously-inserted PHI, if present. |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1093 | BasicBlock *LatchBlock = L->getLoopLatch(); |
| 1094 | if (LatchBlock) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1095 | PHINode *AddRecPhiMatch = nullptr; |
| 1096 | Instruction *IncV = nullptr; |
| 1097 | TruncTy = nullptr; |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1098 | InvertStep = false; |
| 1099 | |
| 1100 | // Only try partially matching scevs that need truncation and/or |
| 1101 | // step-inversion if we know this loop is outside the current loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1102 | bool TryNonMatchingSCEV = |
| 1103 | IVIncInsertLoop && |
| 1104 | SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader()); |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1105 | |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 1106 | for (auto &I : *L->getHeader()) { |
| 1107 | auto *PN = dyn_cast<PHINode>(&I); |
| 1108 | if (!PN || !SE.isSCEVable(PN->getType())) |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1109 | continue; |
Dan Gohman | 148a972 | 2010-02-16 00:20:08 +0000 | [diff] [blame] | 1110 | |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1111 | const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN)); |
| 1112 | if (!PhiSCEV) |
| 1113 | continue; |
Dan Gohman | 148a972 | 2010-02-16 00:20:08 +0000 | [diff] [blame] | 1114 | |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1115 | bool IsMatchingSCEV = PhiSCEV == Normalized; |
| 1116 | // We only handle truncation and inversion of phi recurrences for the |
| 1117 | // expanded expression if the expanded expression's loop dominates the |
| 1118 | // loop we insert to. Check now, so we can bail out early. |
| 1119 | if (!IsMatchingSCEV && !TryNonMatchingSCEV) |
| 1120 | continue; |
| 1121 | |
| 1122 | Instruction *TempIncV = |
| 1123 | cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)); |
| 1124 | |
| 1125 | // Check whether we can reuse this PHI node. |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1126 | if (LSRMode) { |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1127 | if (!isExpandedAddRecExprPHI(PN, TempIncV, L)) |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1128 | continue; |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1129 | if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos)) |
| 1130 | continue; |
| 1131 | } else { |
| 1132 | if (!isNormalAddRecExprPHI(PN, TempIncV, L)) |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 1133 | continue; |
Dan Gohman | 45774ce | 2010-02-12 10:34:29 +0000 | [diff] [blame] | 1134 | } |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1135 | |
| 1136 | // Stop if we have found an exact match SCEV. |
| 1137 | if (IsMatchingSCEV) { |
| 1138 | IncV = TempIncV; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1139 | TruncTy = nullptr; |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1140 | InvertStep = false; |
| 1141 | AddRecPhiMatch = PN; |
| 1142 | break; |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1143 | } |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1144 | |
| 1145 | // Try whether the phi can be translated into the requested form |
| 1146 | // (truncated and/or offset by a constant). |
| 1147 | if ((!TruncTy || InvertStep) && |
| 1148 | canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) { |
| 1149 | // Record the phi node. But don't stop we might find an exact match |
| 1150 | // later. |
| 1151 | AddRecPhiMatch = PN; |
| 1152 | IncV = TempIncV; |
| 1153 | TruncTy = SE.getEffectiveSCEVType(Normalized->getType()); |
| 1154 | } |
| 1155 | } |
| 1156 | |
| 1157 | if (AddRecPhiMatch) { |
| 1158 | // Potentially, move the increment. We have made sure in |
| 1159 | // isExpandedAddRecExprPHI or hoistIVInc that this is possible. |
| 1160 | if (L == IVIncInsertLoop) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1161 | hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch); |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1162 | |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1163 | // Ok, the add recurrence looks usable. |
| 1164 | // Remember this PHI, even in post-inc mode. |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1165 | InsertedValues.insert(AddRecPhiMatch); |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1166 | // Remember the increment. |
| 1167 | rememberInstruction(IncV); |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1168 | return AddRecPhiMatch; |
Andrew Trick | 7fb669a | 2011-10-07 23:46:21 +0000 | [diff] [blame] | 1169 | } |
| 1170 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1171 | |
| 1172 | // Save the original insertion point so we can restore it when we're done. |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1173 | SCEVInsertPointGuard Guard(Builder, this); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1174 | |
Andrew Trick | b9aa26f | 2011-12-20 01:42:24 +0000 | [diff] [blame] | 1175 | // Another AddRec may need to be recursively expanded below. For example, if |
| 1176 | // this AddRec is quadratic, the StepV may itself be an AddRec in this |
| 1177 | // loop. Remove this loop from the PostIncLoops set before expanding such |
| 1178 | // AddRecs. Otherwise, we cannot find a valid position for the step |
| 1179 | // (i.e. StepV can never dominate its loop header). Ideally, we could do |
| 1180 | // SavedIncLoops.swap(PostIncLoops), but we generally have a single element, |
| 1181 | // so it's not worth implementing SmallPtrSet::swap. |
| 1182 | PostIncLoopSet SavedPostIncLoops = PostIncLoops; |
| 1183 | PostIncLoops.clear(); |
| 1184 | |
Sanjoy Das | ba1bf87 | 2016-12-11 19:02:21 +0000 | [diff] [blame] | 1185 | // Expand code for the start value into the loop preheader. |
| 1186 | assert(L->getLoopPreheader() && |
| 1187 | "Can't expand add recurrences without a loop preheader!"); |
| 1188 | Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy, |
| 1189 | L->getLoopPreheader()->getTerminator()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1190 | |
Sanjoy Das | ba1bf87 | 2016-12-11 19:02:21 +0000 | [diff] [blame] | 1191 | // StartV must have been be inserted into L's preheader to dominate the new |
| 1192 | // phi. |
Benjamin Kramer | a7606b99 | 2011-07-16 22:26:27 +0000 | [diff] [blame] | 1193 | assert(!isa<Instruction>(StartV) || |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1194 | SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(), |
| 1195 | L->getHeader())); |
Andrew Trick | 244e2c3 | 2011-07-16 00:59:39 +0000 | [diff] [blame] | 1196 | |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1197 | // Expand code for the step value. Do this before creating the PHI so that PHI |
| 1198 | // reuse code doesn't see an incomplete PHI. |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1199 | const SCEV *Step = Normalized->getStepRecurrence(SE); |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1200 | // If the stride is negative, insert a sub instead of an add for the increment |
| 1201 | // (unless it's a constant, because subtracts of constants are canonicalized |
| 1202 | // to adds). |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 1203 | bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative(); |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1204 | if (useSubtract) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1205 | Step = SE.getNegativeSCEV(Step); |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1206 | // Expand the step somewhere that dominates the loop header. |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1207 | Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1208 | |
Sanjoy Das | 54ef895 | 2015-02-26 19:51:35 +0000 | [diff] [blame] | 1209 | // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if |
| 1210 | // we actually do emit an addition. It does not apply if we emit a |
| 1211 | // subtraction. |
| 1212 | bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized); |
| 1213 | bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized); |
| 1214 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1215 | // Create the PHI. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 1216 | BasicBlock *Header = L->getHeader(); |
| 1217 | Builder.SetInsertPoint(Header, Header->begin()); |
| 1218 | pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header); |
Andrew Trick | 411daa5 | 2011-06-28 05:07:32 +0000 | [diff] [blame] | 1219 | PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE), |
Andrew Trick | 154d78a | 2011-06-28 05:41:52 +0000 | [diff] [blame] | 1220 | Twine(IVName) + ".iv"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1221 | rememberInstruction(PN); |
| 1222 | |
| 1223 | // Create the step instructions and populate the PHI. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 1224 | for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1225 | BasicBlock *Pred = *HPI; |
| 1226 | |
| 1227 | // Add a start value. |
| 1228 | if (!L->contains(Pred)) { |
| 1229 | PN->addIncoming(StartV, Pred); |
| 1230 | continue; |
| 1231 | } |
| 1232 | |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1233 | // Create a step value and add it to the PHI. |
| 1234 | // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the |
| 1235 | // instructions at IVIncInsertPos. |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1236 | Instruction *InsertPos = L == IVIncInsertLoop ? |
| 1237 | IVIncInsertPos : Pred->getTerminator(); |
Devang Patel | c3239d3 | 2011-07-05 21:48:22 +0000 | [diff] [blame] | 1238 | Builder.SetInsertPoint(InsertPos); |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1239 | Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract); |
Sanjoy Das | dcc84db | 2015-02-25 20:02:59 +0000 | [diff] [blame] | 1240 | |
Andrew Trick | 8eaae28 | 2013-07-14 02:50:07 +0000 | [diff] [blame] | 1241 | if (isa<OverflowingBinaryOperator>(IncV)) { |
Sanjoy Das | dcc84db | 2015-02-25 20:02:59 +0000 | [diff] [blame] | 1242 | if (IncrementIsNUW) |
Andrew Trick | 8eaae28 | 2013-07-14 02:50:07 +0000 | [diff] [blame] | 1243 | cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap(); |
Sanjoy Das | dcc84db | 2015-02-25 20:02:59 +0000 | [diff] [blame] | 1244 | if (IncrementIsNSW) |
Andrew Trick | 8eaae28 | 2013-07-14 02:50:07 +0000 | [diff] [blame] | 1245 | cast<BinaryOperator>(IncV)->setHasNoSignedWrap(); |
| 1246 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1247 | PN->addIncoming(IncV, Pred); |
| 1248 | } |
| 1249 | |
Andrew Trick | b9aa26f | 2011-12-20 01:42:24 +0000 | [diff] [blame] | 1250 | // After expanding subexpressions, restore the PostIncLoops set so the caller |
| 1251 | // can ensure that IVIncrement dominates the current uses. |
| 1252 | PostIncLoops = SavedPostIncLoops; |
| 1253 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1254 | // Remember this PHI, even in post-inc mode. |
| 1255 | InsertedValues.insert(PN); |
| 1256 | |
| 1257 | return PN; |
| 1258 | } |
| 1259 | |
| 1260 | Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1261 | Type *STy = S->getType(); |
| 1262 | Type *IntTy = SE.getEffectiveSCEVType(STy); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1263 | const Loop *L = S->getLoop(); |
| 1264 | |
| 1265 | // Determine a normalized form of this expression, which is the expression |
| 1266 | // before any post-inc adjustment is made. |
| 1267 | const SCEVAddRecExpr *Normalized = S; |
Dan Gohman | d006ab9 | 2010-04-07 22:27:08 +0000 | [diff] [blame] | 1268 | if (PostIncLoops.count(L)) { |
| 1269 | PostIncLoopSet Loops; |
| 1270 | Loops.insert(L); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1271 | Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse( |
| 1272 | Normalize, S, nullptr, nullptr, Loops, SE, SE.DT)); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1273 | } |
| 1274 | |
| 1275 | // Strip off any non-loop-dominating component from the addrec start. |
| 1276 | const SCEV *Start = Normalized->getStart(); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1277 | const SCEV *PostLoopOffset = nullptr; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 1278 | if (!SE.properlyDominates(Start, L->getHeader())) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1279 | PostLoopOffset = Start; |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1280 | Start = SE.getConstant(Normalized->getType(), 0); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1281 | Normalized = cast<SCEVAddRecExpr>( |
| 1282 | SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE), |
| 1283 | Normalized->getLoop(), |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 1284 | Normalized->getNoWrapFlags(SCEV::FlagNW))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1285 | } |
| 1286 | |
| 1287 | // Strip off any non-loop-dominating component from the addrec step. |
| 1288 | const SCEV *Step = Normalized->getStepRecurrence(SE); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1289 | const SCEV *PostLoopScale = nullptr; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 1290 | if (!SE.dominates(Step, L->getHeader())) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1291 | PostLoopScale = Step; |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1292 | Step = SE.getConstant(Normalized->getType(), 1); |
Keno Fischer | 1efc3b7 | 2016-07-13 01:28:12 +0000 | [diff] [blame] | 1293 | if (!Start->isZero()) { |
| 1294 | // The normalization below assumes that Start is constant zero, so if |
| 1295 | // it isn't re-associate Start to PostLoopOffset. |
| 1296 | assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?"); |
| 1297 | PostLoopOffset = Start; |
| 1298 | Start = SE.getConstant(Normalized->getType(), 0); |
| 1299 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1300 | Normalized = |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 1301 | cast<SCEVAddRecExpr>(SE.getAddRecExpr( |
| 1302 | Start, Step, Normalized->getLoop(), |
| 1303 | Normalized->getNoWrapFlags(SCEV::FlagNW))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1304 | } |
| 1305 | |
| 1306 | // Expand the core addrec. If we need post-loop scaling, force it to |
| 1307 | // expand to an integer type to avoid the need for additional casting. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1308 | Type *ExpandTy = PostLoopScale ? IntTy : STy; |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1309 | // In some cases, we decide to reuse an existing phi node but need to truncate |
| 1310 | // it and/or invert the step. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1311 | Type *TruncTy = nullptr; |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1312 | bool InvertStep = false; |
| 1313 | PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy, |
| 1314 | TruncTy, InvertStep); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1315 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1316 | // Accommodate post-inc mode, if necessary. |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1317 | Value *Result; |
Dan Gohman | d006ab9 | 2010-04-07 22:27:08 +0000 | [diff] [blame] | 1318 | if (!PostIncLoops.count(L)) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1319 | Result = PN; |
| 1320 | else { |
| 1321 | // In PostInc mode, use the post-incremented value. |
| 1322 | BasicBlock *LatchBlock = L->getLoopLatch(); |
| 1323 | assert(LatchBlock && "PostInc mode requires a unique loop latch!"); |
| 1324 | Result = PN->getIncomingValueForBlock(LatchBlock); |
Andrew Trick | 870c1a3 | 2011-10-13 21:55:29 +0000 | [diff] [blame] | 1325 | |
| 1326 | // For an expansion to use the postinc form, the client must call |
| 1327 | // expandCodeFor with an InsertPoint that is either outside the PostIncLoop |
| 1328 | // or dominated by IVIncInsertPos. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1329 | if (isa<Instruction>(Result) && |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1330 | !SE.DT.dominates(cast<Instruction>(Result), |
| 1331 | &*Builder.GetInsertPoint())) { |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1332 | // The induction variable's postinc expansion does not dominate this use. |
| 1333 | // IVUsers tries to prevent this case, so it is rare. However, it can |
| 1334 | // happen when an IVUser outside the loop is not dominated by the latch |
| 1335 | // block. Adjusting IVIncInsertPos before expansion begins cannot handle |
| 1336 | // all cases. Consider a phi outide whose operand is replaced during |
| 1337 | // expansion with the value of the postinc user. Without fundamentally |
| 1338 | // changing the way postinc users are tracked, the only remedy is |
| 1339 | // inserting an extra IV increment. StepV might fold into PostLoopOffset, |
| 1340 | // but hopefully expandCodeFor handles that. |
| 1341 | bool useSubtract = |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 1342 | !ExpandTy->isPointerTy() && Step->isNonConstantNegative(); |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1343 | if (useSubtract) |
| 1344 | Step = SE.getNegativeSCEV(Step); |
Benjamin Kramer | 6e93152 | 2013-09-30 15:40:17 +0000 | [diff] [blame] | 1345 | Value *StepV; |
| 1346 | { |
| 1347 | // Expand the step somewhere that dominates the loop header. |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1348 | SCEVInsertPointGuard Guard(Builder, this); |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1349 | StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front()); |
Benjamin Kramer | 6e93152 | 2013-09-30 15:40:17 +0000 | [diff] [blame] | 1350 | } |
Andrew Trick | ceafa2c | 2011-11-30 06:07:54 +0000 | [diff] [blame] | 1351 | Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract); |
| 1352 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1353 | } |
| 1354 | |
Arnold Schwaighofer | 26f567d | 2014-02-16 15:49:50 +0000 | [diff] [blame] | 1355 | // We have decided to reuse an induction variable of a dominating loop. Apply |
| 1356 | // truncation and/or invertion of the step. |
| 1357 | if (TruncTy) { |
| 1358 | Type *ResTy = Result->getType(); |
| 1359 | // Normalize the result type. |
| 1360 | if (ResTy != SE.getEffectiveSCEVType(ResTy)) |
| 1361 | Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy)); |
| 1362 | // Truncate the result. |
| 1363 | if (TruncTy != Result->getType()) { |
| 1364 | Result = Builder.CreateTrunc(Result, TruncTy); |
| 1365 | rememberInstruction(Result); |
| 1366 | } |
| 1367 | // Invert the result. |
| 1368 | if (InvertStep) { |
| 1369 | Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy), |
| 1370 | Result); |
| 1371 | rememberInstruction(Result); |
| 1372 | } |
| 1373 | } |
| 1374 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1375 | // Re-apply any non-loop-dominating scale. |
| 1376 | if (PostLoopScale) { |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 1377 | assert(S->isAffine() && "Can't linearly scale non-affine recurrences."); |
Dan Gohman | 1a8674e | 2010-02-12 20:39:25 +0000 | [diff] [blame] | 1378 | Result = InsertNoopCastOfTo(Result, IntTy); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1379 | Result = Builder.CreateMul(Result, |
| 1380 | expandCodeFor(PostLoopScale, IntTy)); |
| 1381 | rememberInstruction(Result); |
| 1382 | } |
| 1383 | |
| 1384 | // Re-apply any non-loop-dominating offset. |
| 1385 | if (PostLoopOffset) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1386 | if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1387 | const SCEV *const OffsetArray[1] = { PostLoopOffset }; |
| 1388 | Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result); |
| 1389 | } else { |
Dan Gohman | 1a8674e | 2010-02-12 20:39:25 +0000 | [diff] [blame] | 1390 | Result = InsertNoopCastOfTo(Result, IntTy); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1391 | Result = Builder.CreateAdd(Result, |
| 1392 | expandCodeFor(PostLoopOffset, IntTy)); |
| 1393 | rememberInstruction(Result); |
| 1394 | } |
| 1395 | } |
| 1396 | |
| 1397 | return Result; |
| 1398 | } |
| 1399 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1400 | Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1401 | if (!CanonicalMode) return expandAddRecExprLiterally(S); |
| 1402 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1403 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1404 | const Loop *L = S->getLoop(); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1405 | |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1406 | // First check for an existing canonical IV in a suitable type. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1407 | PHINode *CanonicalIV = nullptr; |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1408 | if (PHINode *PN = L->getCanonicalInductionVariable()) |
Dan Gohman | 3115875 | 2010-07-20 16:46:58 +0000 | [diff] [blame] | 1409 | if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty)) |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1410 | CanonicalIV = PN; |
| 1411 | |
| 1412 | // Rewrite an AddRec in terms of the canonical induction variable, if |
| 1413 | // its type is more narrow. |
| 1414 | if (CanonicalIV && |
| 1415 | SE.getTypeSizeInBits(CanonicalIV->getType()) > |
| 1416 | SE.getTypeSizeInBits(Ty)) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1417 | SmallVector<const SCEV *, 4> NewOps(S->getNumOperands()); |
| 1418 | for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i) |
| 1419 | NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1420 | Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(), |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 1421 | S->getNoWrapFlags(SCEV::FlagNW))); |
David Majnemer | 235acde | 2015-10-27 19:48:28 +0000 | [diff] [blame] | 1422 | BasicBlock::iterator NewInsertPt = |
| 1423 | findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock()); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1424 | V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr, |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1425 | &*NewInsertPt); |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1426 | return V; |
| 1427 | } |
| 1428 | |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1429 | // {X,+,F} --> X + {0,+,F} |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 1430 | if (!S->getStart()->isZero()) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1431 | SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end()); |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1432 | NewOps[0] = SE.getConstant(Ty, 0); |
Andrew Trick | aa8ceba | 2013-07-14 03:10:08 +0000 | [diff] [blame] | 1433 | const SCEV *Rest = SE.getAddRecExpr(NewOps, L, |
| 1434 | S->getNoWrapFlags(SCEV::FlagNW)); |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 1435 | |
| 1436 | // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the |
| 1437 | // comments on expandAddToGEP for details. |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 1438 | const SCEV *Base = S->getStart(); |
| 1439 | const SCEV *RestArray[1] = { Rest }; |
| 1440 | // Dig into the expression to find the pointer base for a GEP. |
| 1441 | ExposePointerBase(Base, RestArray[0], SE); |
| 1442 | // If we found a pointer, expand the AddRec with a GEP. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1443 | if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 1444 | // Make sure the Base isn't something exotic, such as a multiplied |
| 1445 | // or divided pointer value. In those cases, the result type isn't |
| 1446 | // actually a pointer type. |
| 1447 | if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) { |
| 1448 | Value *StartV = expand(Base); |
| 1449 | assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!"); |
| 1450 | return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV); |
Dan Gohman | 291c2e0 | 2009-05-24 18:06:31 +0000 | [diff] [blame] | 1451 | } |
| 1452 | } |
| 1453 | |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1454 | // Just do a normal add. Pre-expand the operands to suppress folding. |
Patrik Hagglund | 96f13af | 2016-06-20 10:19:04 +0000 | [diff] [blame] | 1455 | // |
| 1456 | // The LHS and RHS values are factored out of the expand call to make the |
| 1457 | // output independent of the argument evaluation order. |
| 1458 | const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart())); |
| 1459 | const SCEV *AddExprRHS = SE.getUnknown(expand(Rest)); |
| 1460 | return expand(SE.getAddExpr(AddExprLHS, AddExprRHS)); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1461 | } |
| 1462 | |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1463 | // If we don't yet have a canonical IV, create one. |
| 1464 | if (!CanonicalIV) { |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1465 | // Create and insert the PHI node for the induction variable in the |
| 1466 | // specified loop. |
| 1467 | BasicBlock *Header = L->getHeader(); |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 1468 | pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header); |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 1469 | CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar", |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1470 | &Header->front()); |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1471 | rememberInstruction(CanonicalIV); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1472 | |
Hal Finkel | 3f5279c | 2013-08-18 00:16:23 +0000 | [diff] [blame] | 1473 | SmallSet<BasicBlock *, 4> PredSeen; |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 1474 | Constant *One = ConstantInt::get(Ty, 1); |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 1475 | for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) { |
Gabor Greif | e82532a | 2010-07-09 15:40:10 +0000 | [diff] [blame] | 1476 | BasicBlock *HP = *HPI; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 1477 | if (!PredSeen.insert(HP).second) { |
Hal Finkel | 36eff0f | 2014-07-31 19:13:38 +0000 | [diff] [blame] | 1478 | // There must be an incoming value for each predecessor, even the |
| 1479 | // duplicates! |
| 1480 | CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP); |
Hal Finkel | 3f5279c | 2013-08-18 00:16:23 +0000 | [diff] [blame] | 1481 | continue; |
Hal Finkel | 36eff0f | 2014-07-31 19:13:38 +0000 | [diff] [blame] | 1482 | } |
Hal Finkel | 3f5279c | 2013-08-18 00:16:23 +0000 | [diff] [blame] | 1483 | |
Gabor Greif | e82532a | 2010-07-09 15:40:10 +0000 | [diff] [blame] | 1484 | if (L->contains(HP)) { |
Dan Gohman | 510bffc | 2010-01-19 22:26:02 +0000 | [diff] [blame] | 1485 | // Insert a unit add instruction right before the terminator |
| 1486 | // corresponding to the back-edge. |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1487 | Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One, |
| 1488 | "indvar.next", |
| 1489 | HP->getTerminator()); |
Devang Patel | ccf8dbf | 2011-06-22 20:56:56 +0000 | [diff] [blame] | 1490 | Add->setDebugLoc(HP->getTerminator()->getDebugLoc()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1491 | rememberInstruction(Add); |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1492 | CanonicalIV->addIncoming(Add, HP); |
Dan Gohman | 2aab867 | 2009-09-27 17:46:40 +0000 | [diff] [blame] | 1493 | } else { |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1494 | CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP); |
Dan Gohman | 2aab867 | 2009-09-27 17:46:40 +0000 | [diff] [blame] | 1495 | } |
Gabor Greif | e82532a | 2010-07-09 15:40:10 +0000 | [diff] [blame] | 1496 | } |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1497 | } |
| 1498 | |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1499 | // {0,+,1} --> Insert a canonical induction variable into the loop! |
| 1500 | if (S->isAffine() && S->getOperand(1)->isOne()) { |
| 1501 | assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) && |
| 1502 | "IVs with types different from the canonical IV should " |
| 1503 | "already have been handled!"); |
| 1504 | return CanonicalIV; |
| 1505 | } |
| 1506 | |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1507 | // {0,+,F} --> {0,+,1} * F |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1508 | |
Chris Lattner | f0b77f9 | 2005-10-30 06:24:33 +0000 | [diff] [blame] | 1509 | // If this is a simple linear addrec, emit it now as a special case. |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1510 | if (S->isAffine()) // {0,+,F} --> i*F |
| 1511 | return |
| 1512 | expand(SE.getTruncateOrNoop( |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1513 | SE.getMulExpr(SE.getUnknown(CanonicalIV), |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1514 | SE.getNoopOrAnyExtend(S->getOperand(1), |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1515 | CanonicalIV->getType())), |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1516 | Ty)); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1517 | |
| 1518 | // If this is a chain of recurrences, turn it into a closed form, using the |
| 1519 | // folders, then expandCodeFor the closed form. This allows the folders to |
| 1520 | // simplify the expression without having to build a bunch of special code |
| 1521 | // into this folder. |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1522 | const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV. |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1523 | |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1524 | // Promote S up to the canonical IV type, if the cast is foldable. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1525 | const SCEV *NewS = S; |
Dan Gohman | cd83870 | 2010-07-26 18:28:14 +0000 | [diff] [blame] | 1526 | const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType()); |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1527 | if (isa<SCEVAddRecExpr>(Ext)) |
| 1528 | NewS = Ext; |
| 1529 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1530 | const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE); |
Bill Wendling | f3baad3 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 1531 | //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n"; |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1532 | |
Dan Gohman | 426901a | 2009-06-13 16:25:49 +0000 | [diff] [blame] | 1533 | // Truncate the result down to the original type, if needed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1534 | const SCEV *T = SE.getTruncateOrNoop(V, Ty); |
Dan Gohman | fd76113 | 2009-06-22 22:08:45 +0000 | [diff] [blame] | 1535 | return expand(T); |
Nate Begeman | 2bca4d9 | 2005-07-30 00:12:19 +0000 | [diff] [blame] | 1536 | } |
Anton Korobeynikov | 5849a62 | 2007-08-20 21:17:26 +0000 | [diff] [blame] | 1537 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1538 | Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1539 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 1540 | Value *V = expandCodeFor(S->getOperand(), |
| 1541 | SE.getEffectiveSCEVType(S->getOperand()->getType())); |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 1542 | Value *I = Builder.CreateTrunc(V, Ty); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1543 | rememberInstruction(I); |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 1544 | return I; |
Dan Gohman | 0e4cf89 | 2008-06-22 19:09:18 +0000 | [diff] [blame] | 1545 | } |
| 1546 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1547 | Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1548 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 1549 | Value *V = expandCodeFor(S->getOperand(), |
| 1550 | SE.getEffectiveSCEVType(S->getOperand()->getType())); |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 1551 | Value *I = Builder.CreateZExt(V, Ty); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1552 | rememberInstruction(I); |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 1553 | return I; |
Dan Gohman | 0e4cf89 | 2008-06-22 19:09:18 +0000 | [diff] [blame] | 1554 | } |
| 1555 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1556 | Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1557 | Type *Ty = SE.getEffectiveSCEVType(S->getType()); |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 1558 | Value *V = expandCodeFor(S->getOperand(), |
| 1559 | SE.getEffectiveSCEVType(S->getOperand()->getType())); |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 1560 | Value *I = Builder.CreateSExt(V, Ty); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1561 | rememberInstruction(I); |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 1562 | return I; |
Dan Gohman | 0e4cf89 | 2008-06-22 19:09:18 +0000 | [diff] [blame] | 1563 | } |
| 1564 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1565 | Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) { |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1566 | Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1567 | Type *Ty = LHS->getType(); |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1568 | for (int i = S->getNumOperands()-2; i >= 0; --i) { |
| 1569 | // In the case of mixed integer and pointer types, do the |
| 1570 | // rest of the comparisons as integer. |
| 1571 | if (S->getOperand(i)->getType() != Ty) { |
| 1572 | Ty = SE.getEffectiveSCEVType(Ty); |
| 1573 | LHS = InsertNoopCastOfTo(LHS, Ty); |
| 1574 | } |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 1575 | Value *RHS = expandCodeFor(S->getOperand(i), Ty); |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 1576 | Value *ICmp = Builder.CreateICmpSGT(LHS, RHS); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1577 | rememberInstruction(ICmp); |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 1578 | Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1579 | rememberInstruction(Sel); |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 1580 | LHS = Sel; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 1581 | } |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1582 | // In the case of mixed integer and pointer types, cast the |
| 1583 | // final result back to the pointer type. |
| 1584 | if (LHS->getType() != S->getType()) |
| 1585 | LHS = InsertNoopCastOfTo(LHS, S->getType()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 1586 | return LHS; |
| 1587 | } |
| 1588 | |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1589 | Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) { |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1590 | Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1591 | Type *Ty = LHS->getType(); |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1592 | for (int i = S->getNumOperands()-2; i >= 0; --i) { |
| 1593 | // In the case of mixed integer and pointer types, do the |
| 1594 | // rest of the comparisons as integer. |
| 1595 | if (S->getOperand(i)->getType() != Ty) { |
| 1596 | Ty = SE.getEffectiveSCEVType(Ty); |
| 1597 | LHS = InsertNoopCastOfTo(LHS, Ty); |
| 1598 | } |
Dan Gohman | b8597bd | 2009-06-09 17:18:38 +0000 | [diff] [blame] | 1599 | Value *RHS = expandCodeFor(S->getOperand(i), Ty); |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 1600 | Value *ICmp = Builder.CreateICmpUGT(LHS, RHS); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1601 | rememberInstruction(ICmp); |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 1602 | Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1603 | rememberInstruction(Sel); |
Dan Gohman | d195a22 | 2009-05-01 17:13:31 +0000 | [diff] [blame] | 1604 | LHS = Sel; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1605 | } |
Dan Gohman | 92b969b | 2009-07-14 20:57:04 +0000 | [diff] [blame] | 1606 | // In the case of mixed integer and pointer types, cast the |
| 1607 | // final result back to the pointer type. |
| 1608 | if (LHS->getType() != S->getType()) |
| 1609 | LHS = InsertNoopCastOfTo(LHS, S->getType()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1610 | return LHS; |
| 1611 | } |
| 1612 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1613 | Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty, |
Andrew Trick | c908b43 | 2012-01-20 07:41:13 +0000 | [diff] [blame] | 1614 | Instruction *IP) { |
Geoff Berry | d018280 | 2016-08-11 21:05:17 +0000 | [diff] [blame] | 1615 | setInsertPoint(IP); |
Dan Gohman | 89d4e3c | 2010-03-19 21:51:03 +0000 | [diff] [blame] | 1616 | return expandCodeFor(SH, Ty); |
| 1617 | } |
| 1618 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1619 | Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) { |
Dan Gohman | 0e4cf89 | 2008-06-22 19:09:18 +0000 | [diff] [blame] | 1620 | // Expand the code for this SCEV. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 1621 | Value *V = expand(SH); |
Dan Gohman | 2649491 | 2009-05-19 02:15:55 +0000 | [diff] [blame] | 1622 | if (Ty) { |
| 1623 | assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) && |
| 1624 | "non-trivial casts should be done with the SCEVs directly!"); |
| 1625 | V = InsertNoopCastOfTo(V, Ty); |
| 1626 | } |
| 1627 | return V; |
Dan Gohman | 0e4cf89 | 2008-06-22 19:09:18 +0000 | [diff] [blame] | 1628 | } |
| 1629 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1630 | ScalarEvolution::ValueOffsetPair |
| 1631 | SCEVExpander::FindValueInExprValueMap(const SCEV *S, |
| 1632 | const Instruction *InsertPt) { |
| 1633 | SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S); |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1634 | // If the expansion is not in CanonicalMode, and the SCEV contains any |
| 1635 | // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally. |
| 1636 | if (CanonicalMode || !SE.containsAddRecurrence(S)) { |
| 1637 | // If S is scConstant, it may be worse to reuse an existing Value. |
| 1638 | if (S->getSCEVType() != scConstant && Set) { |
| 1639 | // Choose a Value from the set which dominates the insertPt. |
| 1640 | // insertPt should be inside the Value's parent loop so as not to break |
| 1641 | // the LCSSA form. |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1642 | for (auto const &VOPair : *Set) { |
| 1643 | Value *V = VOPair.first; |
| 1644 | ConstantInt *Offset = VOPair.second; |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1645 | Instruction *EntInst = nullptr; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1646 | if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) && |
| 1647 | S->getType() == V->getType() && |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1648 | EntInst->getFunction() == InsertPt->getFunction() && |
| 1649 | SE.DT.dominates(EntInst, InsertPt) && |
| 1650 | (SE.LI.getLoopFor(EntInst->getParent()) == nullptr || |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1651 | SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) |
| 1652 | return {V, Offset}; |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1653 | } |
| 1654 | } |
| 1655 | } |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1656 | return {nullptr, nullptr}; |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1657 | } |
| 1658 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 1659 | // The expansion of SCEV will either reuse a previous Value in ExprValueMap, |
| 1660 | // or expand the SCEV literally. Specifically, if the expansion is in LSRMode, |
| 1661 | // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded |
| 1662 | // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise, |
| 1663 | // the expansion will try to reuse Value from ExprValueMap, and only when it |
| 1664 | // fails, expand the SCEV literally. |
Dan Gohman | 056857a | 2009-04-18 17:56:28 +0000 | [diff] [blame] | 1665 | Value *SCEVExpander::expand(const SCEV *S) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1666 | // Compute an insertion point for this SCEV object. Hoist the instructions |
| 1667 | // as far out in the loop nest as possible. |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1668 | Instruction *InsertPt = &*Builder.GetInsertPoint(); |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 1669 | for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());; |
| 1670 | L = L->getParentLoop()) |
| 1671 | if (SE.isLoopInvariant(S, L)) { |
| 1672 | if (!L) break; |
| 1673 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 1674 | InsertPt = Preheader->getTerminator(); |
| 1675 | else { |
| 1676 | // LSR sets the insertion point for AddRec start/step values to the |
| 1677 | // block start to simplify value reuse, even though it's an invalid |
| 1678 | // position. SCEVExpander must correct for this in all cases. |
| 1679 | InsertPt = &*L->getHeader()->getFirstInsertionPt(); |
Andrew Trick | cbcc98f | 2012-01-02 21:25:10 +0000 | [diff] [blame] | 1680 | } |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 1681 | } else { |
| 1682 | // If the SCEV is computable at this level, insert it into the header |
| 1683 | // after the PHIs (and after any other instructions that we've inserted |
| 1684 | // there) so that it is guaranteed to dominate any user inside the loop. |
| 1685 | if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L)) |
| 1686 | InsertPt = &*L->getHeader()->getFirstInsertionPt(); |
| 1687 | while (InsertPt->getIterator() != Builder.GetInsertPoint() && |
| 1688 | (isInsertedInstruction(InsertPt) || |
| 1689 | isa<DbgInfoIntrinsic>(InsertPt))) { |
| 1690 | InsertPt = &*std::next(InsertPt->getIterator()); |
Nico Weber | 85740f6 | 2016-11-10 17:55:41 +0000 | [diff] [blame] | 1691 | } |
Reid Kleckner | 30422ee | 2016-12-12 18:52:32 +0000 | [diff] [blame] | 1692 | break; |
| 1693 | } |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1694 | |
Dan Gohman | daafbe6 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 1695 | // Check to see if we already expanded this here. |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 1696 | auto I = InsertedExpressions.find(std::make_pair(S, InsertPt)); |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 1697 | if (I != InsertedExpressions.end()) |
Dan Gohman | daafbe6 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 1698 | return I->second; |
Dan Gohman | 830fd38 | 2009-06-27 21:18:18 +0000 | [diff] [blame] | 1699 | |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1700 | SCEVInsertPointGuard Guard(Builder, this); |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1701 | Builder.SetInsertPoint(InsertPt); |
Dan Gohman | daafbe6 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 1702 | |
| 1703 | // Expand the expression into instructions. |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 1704 | ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt); |
| 1705 | Value *V = VO.first; |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1706 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 1707 | if (!V) |
| 1708 | V = visit(S); |
Wei Mi | 2466239 | 2016-09-14 04:39:50 +0000 | [diff] [blame] | 1709 | else if (VO.second) { |
| 1710 | if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) { |
| 1711 | Type *Ety = Vty->getPointerElementType(); |
| 1712 | int64_t Offset = VO.second->getSExtValue(); |
| 1713 | int64_t ESize = SE.getTypeSizeInBits(Ety); |
| 1714 | if ((Offset * 8) % ESize == 0) { |
| 1715 | ConstantInt *Idx = |
| 1716 | ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize); |
| 1717 | V = Builder.CreateGEP(Ety, V, Idx, "scevgep"); |
| 1718 | } else { |
| 1719 | ConstantInt *Idx = |
| 1720 | ConstantInt::getSigned(VO.second->getType(), -Offset); |
| 1721 | unsigned AS = Vty->getAddressSpace(); |
| 1722 | V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS)); |
| 1723 | V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx, |
| 1724 | "uglygep"); |
| 1725 | V = Builder.CreateBitCast(V, Vty); |
| 1726 | } |
| 1727 | } else { |
| 1728 | V = Builder.CreateSub(V, VO.second); |
| 1729 | } |
| 1730 | } |
Dan Gohman | daafbe6 | 2009-06-26 22:53:46 +0000 | [diff] [blame] | 1731 | // Remember the expanded value for this SCEV at this location. |
Andrew Trick | 870c1a3 | 2011-10-13 21:55:29 +0000 | [diff] [blame] | 1732 | // |
| 1733 | // This is independent of PostIncLoops. The mapped value simply materializes |
| 1734 | // the expression at this insertion point. If the mapped value happened to be |
Alp Toker | f907b89 | 2013-12-05 05:44:44 +0000 | [diff] [blame] | 1735 | // a postinc expansion, it could be reused by a non-postinc user, but only if |
Andrew Trick | 870c1a3 | 2011-10-13 21:55:29 +0000 | [diff] [blame] | 1736 | // its insertion point was already at the head of the loop. |
| 1737 | InsertedExpressions[std::make_pair(S, InsertPt)] = V; |
Anton Korobeynikov | 5849a62 | 2007-08-20 21:17:26 +0000 | [diff] [blame] | 1738 | return V; |
| 1739 | } |
Dan Gohman | 63964b5 | 2009-06-05 16:35:53 +0000 | [diff] [blame] | 1740 | |
Dan Gohman | 6b75173 | 2010-02-14 03:12:47 +0000 | [diff] [blame] | 1741 | void SCEVExpander::rememberInstruction(Value *I) { |
Dan Gohman | bbfb6ac | 2010-06-05 00:33:07 +0000 | [diff] [blame] | 1742 | if (!PostIncLoops.empty()) |
| 1743 | InsertedPostIncValues.insert(I); |
| 1744 | else |
Dan Gohman | 6b75173 | 2010-02-14 03:12:47 +0000 | [diff] [blame] | 1745 | InsertedValues.insert(I); |
Dan Gohman | 6b75173 | 2010-02-14 03:12:47 +0000 | [diff] [blame] | 1746 | } |
| 1747 | |
Dan Gohman | 63964b5 | 2009-06-05 16:35:53 +0000 | [diff] [blame] | 1748 | /// getOrInsertCanonicalInductionVariable - This method returns the |
| 1749 | /// canonical induction variable of the specified type for the specified |
| 1750 | /// loop (inserting one if there is none). A canonical induction variable |
| 1751 | /// starts at zero and steps by one on each iteration. |
Dan Gohman | 4fd9243 | 2010-07-20 16:44:52 +0000 | [diff] [blame] | 1752 | PHINode * |
Dan Gohman | 63964b5 | 2009-06-05 16:35:53 +0000 | [diff] [blame] | 1753 | SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1754 | Type *Ty) { |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 1755 | assert(Ty->isIntegerTy() && "Can only insert integer induction variables!"); |
Dan Gohman | 3115875 | 2010-07-20 16:46:58 +0000 | [diff] [blame] | 1756 | |
| 1757 | // Build a SCEV for {0,+,1}<L>. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1758 | // Conservatively use FlagAnyWrap for now. |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1759 | const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1760 | SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap); |
Dan Gohman | 3115875 | 2010-07-20 16:46:58 +0000 | [diff] [blame] | 1761 | |
| 1762 | // Emit code for it. |
Geoff Berry | 0c09517 | 2016-06-01 20:03:09 +0000 | [diff] [blame] | 1763 | SCEVInsertPointGuard Guard(Builder, this); |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1764 | PHINode *V = |
| 1765 | cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front())); |
Dan Gohman | 3115875 | 2010-07-20 16:46:58 +0000 | [diff] [blame] | 1766 | |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 1767 | return V; |
Dan Gohman | 63964b5 | 2009-06-05 16:35:53 +0000 | [diff] [blame] | 1768 | } |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1769 | |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1770 | /// replaceCongruentIVs - Check for congruent phis in this loop header and |
| 1771 | /// replace them with their most canonical representative. Return the number of |
| 1772 | /// phis eliminated. |
| 1773 | /// |
| 1774 | /// This does not depend on any SCEVExpander state but should be used in |
| 1775 | /// the same context that SCEVExpander is used. |
| 1776 | unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT, |
Nadav Rotem | 4dc976f | 2012-10-19 21:28:43 +0000 | [diff] [blame] | 1777 | SmallVectorImpl<WeakVH> &DeadInsts, |
Chandler Carruth | 26c59fa | 2013-01-07 14:41:08 +0000 | [diff] [blame] | 1778 | const TargetTransformInfo *TTI) { |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1779 | // Find integer phis in order of increasing width. |
| 1780 | SmallVector<PHINode*, 8> Phis; |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 1781 | for (auto &I : *L->getHeader()) { |
| 1782 | if (auto *PN = dyn_cast<PHINode>(&I)) |
| 1783 | Phis.push_back(PN); |
| 1784 | else |
| 1785 | break; |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1786 | } |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 1787 | |
Chandler Carruth | 26c59fa | 2013-01-07 14:41:08 +0000 | [diff] [blame] | 1788 | if (TTI) |
Benjamin Kramer | b0f74b2 | 2014-03-07 21:35:39 +0000 | [diff] [blame] | 1789 | std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) { |
| 1790 | // Put pointers at the back and make sure pointer < pointer = false. |
| 1791 | if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) |
| 1792 | return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy(); |
| 1793 | return RHS->getType()->getPrimitiveSizeInBits() < |
| 1794 | LHS->getType()->getPrimitiveSizeInBits(); |
| 1795 | }); |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1796 | |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1797 | unsigned NumElim = 0; |
| 1798 | DenseMap<const SCEV *, PHINode *> ExprToIVMap; |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 1799 | // Process phis from wide to narrow. Map wide phis to their truncation |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1800 | // so narrow phis can reuse them. |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 1801 | for (PHINode *Phi : Phis) { |
Silviu Baranga | 308a7c7 | 2015-11-03 16:27:04 +0000 | [diff] [blame] | 1802 | auto SimplifyPHINode = [&](PHINode *PN) -> Value * { |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1803 | if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC)) |
Silviu Baranga | 308a7c7 | 2015-11-03 16:27:04 +0000 | [diff] [blame] | 1804 | return V; |
| 1805 | if (!SE.isSCEVable(PN->getType())) |
| 1806 | return nullptr; |
| 1807 | auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN)); |
| 1808 | if (!Const) |
| 1809 | return nullptr; |
| 1810 | return Const->getValue(); |
| 1811 | }; |
| 1812 | |
Benjamin Kramer | a225ed8 | 2012-10-19 16:37:30 +0000 | [diff] [blame] | 1813 | // Fold constant phis. They may be congruent to other constant phis and |
| 1814 | // would confuse the logic below that expects proper IVs. |
Silviu Baranga | 308a7c7 | 2015-11-03 16:27:04 +0000 | [diff] [blame] | 1815 | if (Value *V = SimplifyPHINode(Phi)) { |
| 1816 | if (V->getType() != Phi->getType()) |
| 1817 | continue; |
Benjamin Kramer | a225ed8 | 2012-10-19 16:37:30 +0000 | [diff] [blame] | 1818 | Phi->replaceAllUsesWith(V); |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1819 | DeadInsts.emplace_back(Phi); |
Benjamin Kramer | a225ed8 | 2012-10-19 16:37:30 +0000 | [diff] [blame] | 1820 | ++NumElim; |
| 1821 | DEBUG_WITH_TYPE(DebugType, dbgs() |
| 1822 | << "INDVARS: Eliminated constant iv: " << *Phi << '\n'); |
| 1823 | continue; |
| 1824 | } |
| 1825 | |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1826 | if (!SE.isSCEVable(Phi->getType())) |
| 1827 | continue; |
| 1828 | |
| 1829 | PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)]; |
| 1830 | if (!OrigPhiRef) { |
| 1831 | OrigPhiRef = Phi; |
Sanjoy Das | 0b6518d | 2016-05-10 00:32:31 +0000 | [diff] [blame] | 1832 | if (Phi->getType()->isIntegerTy() && TTI && |
| 1833 | TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) { |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1834 | // This phi can be freely truncated to the narrowest phi type. Map the |
| 1835 | // truncated expression to it so it will be reused for narrow types. |
| 1836 | const SCEV *TruncExpr = |
| 1837 | SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType()); |
| 1838 | ExprToIVMap[TruncExpr] = Phi; |
| 1839 | } |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1840 | continue; |
| 1841 | } |
| 1842 | |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1843 | // Replacing a pointer phi with an integer phi or vice-versa doesn't make |
| 1844 | // sense. |
| 1845 | if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy()) |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1846 | continue; |
| 1847 | |
| 1848 | if (BasicBlock *LatchBlock = L->getLoopLatch()) { |
Sanjoy Das | 4e8c803 | 2016-05-11 17:41:41 +0000 | [diff] [blame] | 1849 | Instruction *OrigInc = dyn_cast<Instruction>( |
| 1850 | OrigPhiRef->getIncomingValueForBlock(LatchBlock)); |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1851 | Instruction *IsomorphicInc = |
Sanjoy Das | 4e8c803 | 2016-05-11 17:41:41 +0000 | [diff] [blame] | 1852 | dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock)); |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1853 | |
Sanjoy Das | 4e8c803 | 2016-05-11 17:41:41 +0000 | [diff] [blame] | 1854 | if (OrigInc && IsomorphicInc) { |
| 1855 | // If this phi has the same width but is more canonical, replace the |
| 1856 | // original with it. As part of the "more canonical" determination, |
| 1857 | // respect a prior decision to use an IV chain. |
| 1858 | if (OrigPhiRef->getType() == Phi->getType() && |
| 1859 | !(ChainedPhis.count(Phi) || |
| 1860 | isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) && |
| 1861 | (ChainedPhis.count(Phi) || |
| 1862 | isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) { |
| 1863 | std::swap(OrigPhiRef, Phi); |
| 1864 | std::swap(OrigInc, IsomorphicInc); |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1865 | } |
Sanjoy Das | 4e8c803 | 2016-05-11 17:41:41 +0000 | [diff] [blame] | 1866 | // Replacing the congruent phi is sufficient because acyclic |
| 1867 | // redundancy elimination, CSE/GVN, should handle the |
| 1868 | // rest. However, once SCEV proves that a phi is congruent, |
| 1869 | // it's often the head of an IV user cycle that is isomorphic |
| 1870 | // with the original phi. It's worth eagerly cleaning up the |
| 1871 | // common case of a single IV increment so that DeleteDeadPHIs |
| 1872 | // can remove cycles that had postinc uses. |
| 1873 | const SCEV *TruncExpr = |
| 1874 | SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType()); |
| 1875 | if (OrigInc != IsomorphicInc && |
| 1876 | TruncExpr == SE.getSCEV(IsomorphicInc) && |
| 1877 | SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) && |
| 1878 | hoistIVInc(OrigInc, IsomorphicInc)) { |
| 1879 | DEBUG_WITH_TYPE(DebugType, |
| 1880 | dbgs() << "INDVARS: Eliminated congruent iv.inc: " |
| 1881 | << *IsomorphicInc << '\n'); |
| 1882 | Value *NewInc = OrigInc; |
| 1883 | if (OrigInc->getType() != IsomorphicInc->getType()) { |
| 1884 | Instruction *IP = nullptr; |
| 1885 | if (PHINode *PN = dyn_cast<PHINode>(OrigInc)) |
| 1886 | IP = &*PN->getParent()->getFirstInsertionPt(); |
| 1887 | else |
| 1888 | IP = OrigInc->getNextNode(); |
| 1889 | |
| 1890 | IRBuilder<> Builder(IP); |
| 1891 | Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc()); |
| 1892 | NewInc = Builder.CreateTruncOrBitCast( |
| 1893 | OrigInc, IsomorphicInc->getType(), IVName); |
| 1894 | } |
| 1895 | IsomorphicInc->replaceAllUsesWith(NewInc); |
| 1896 | DeadInsts.emplace_back(IsomorphicInc); |
| 1897 | } |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1898 | } |
| 1899 | } |
Sanjoy Das | 0b6518d | 2016-05-10 00:32:31 +0000 | [diff] [blame] | 1900 | DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: " |
| 1901 | << *Phi << '\n'); |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1902 | ++NumElim; |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1903 | Value *NewIV = OrigPhiRef; |
| 1904 | if (OrigPhiRef->getType() != Phi->getType()) { |
Duncan P. N. Exon Smith | 5a82c91 | 2015-10-10 00:53:03 +0000 | [diff] [blame] | 1905 | IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt()); |
Andrew Trick | 5adedf5 | 2012-01-07 01:12:09 +0000 | [diff] [blame] | 1906 | Builder.SetCurrentDebugLocation(Phi->getDebugLoc()); |
| 1907 | NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName); |
| 1908 | } |
| 1909 | Phi->replaceAllUsesWith(NewIV); |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1910 | DeadInsts.emplace_back(Phi); |
Andrew Trick | f9201c5 | 2011-10-11 02:28:51 +0000 | [diff] [blame] | 1911 | } |
| 1912 | return NumElim; |
| 1913 | } |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 1914 | |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1915 | Value *SCEVExpander::getExactExistingExpansion(const SCEV *S, |
| 1916 | const Instruction *At, Loop *L) { |
| 1917 | Optional<ScalarEvolution::ValueOffsetPair> VO = |
| 1918 | getRelatedExistingExpansion(S, At, L); |
| 1919 | if (VO && VO.getValue().second == nullptr) |
| 1920 | return VO.getValue().first; |
| 1921 | return nullptr; |
| 1922 | } |
| 1923 | |
| 1924 | Optional<ScalarEvolution::ValueOffsetPair> |
| 1925 | SCEVExpander::getRelatedExistingExpansion(const SCEV *S, const Instruction *At, |
| 1926 | Loop *L) { |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1927 | using namespace llvm::PatternMatch; |
| 1928 | |
Igor Laevsky | 06044f9 | 2015-08-17 16:37:04 +0000 | [diff] [blame] | 1929 | SmallVector<BasicBlock *, 4> ExitingBlocks; |
| 1930 | L->getExitingBlocks(ExitingBlocks); |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1931 | |
Igor Laevsky | 06044f9 | 2015-08-17 16:37:04 +0000 | [diff] [blame] | 1932 | // Look for suitable value in simple conditions at the loop exits. |
| 1933 | for (BasicBlock *BB : ExitingBlocks) { |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1934 | ICmpInst::Predicate Pred; |
| 1935 | Instruction *LHS, *RHS; |
| 1936 | BasicBlock *TrueBB, *FalseBB; |
| 1937 | |
| 1938 | if (!match(BB->getTerminator(), |
| 1939 | m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)), |
| 1940 | TrueBB, FalseBB))) |
| 1941 | continue; |
| 1942 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1943 | if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At)) |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1944 | return ScalarEvolution::ValueOffsetPair(LHS, nullptr); |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1945 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1946 | if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At)) |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1947 | return ScalarEvolution::ValueOffsetPair(RHS, nullptr); |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1948 | } |
| 1949 | |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1950 | // Use expand's logic which is used for reusing a previous Value in |
| 1951 | // ExprValueMap. |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1952 | ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At); |
| 1953 | if (VO.first) |
| 1954 | return VO; |
Junmo Park | 6ebdc14 | 2016-02-16 06:46:58 +0000 | [diff] [blame] | 1955 | |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1956 | // There is potential to make this significantly smarter, but this simple |
| 1957 | // heuristic already gets some interesting cases. |
| 1958 | |
| 1959 | // Can not find suitable value. |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1960 | return None; |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1961 | } |
| 1962 | |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 1963 | bool SCEVExpander::isHighCostExpansionHelper( |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1964 | const SCEV *S, Loop *L, const Instruction *At, |
| 1965 | SmallPtrSetImpl<const SCEV *> &Processed) { |
| 1966 | |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 1967 | // If we can find an existing value for this scev available at the point "At" |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1968 | // then consider the expression cheap. |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 1969 | if (At && getRelatedExistingExpansion(S, At, L)) |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1970 | return false; |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 1971 | |
| 1972 | // Zero/One operand expressions |
| 1973 | switch (S->getSCEVType()) { |
| 1974 | case scUnknown: |
| 1975 | case scConstant: |
| 1976 | return false; |
| 1977 | case scTruncate: |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1978 | return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(), |
| 1979 | L, At, Processed); |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 1980 | case scZeroExtend: |
| 1981 | return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(), |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1982 | L, At, Processed); |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 1983 | case scSignExtend: |
| 1984 | return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(), |
Igor Laevsky | 4709c03 | 2015-08-10 18:23:58 +0000 | [diff] [blame] | 1985 | L, At, Processed); |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 1986 | } |
| 1987 | |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 1988 | if (!Processed.insert(S).second) |
| 1989 | return false; |
| 1990 | |
Sanjoy Das | a9f1e27 | 2015-04-14 03:20:32 +0000 | [diff] [blame] | 1991 | if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) { |
| 1992 | // If the divisor is a power of two and the SCEV type fits in a native |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1993 | // integer, consider the division cheap irrespective of whether it occurs in |
Sanjoy Das | a9f1e27 | 2015-04-14 03:20:32 +0000 | [diff] [blame] | 1994 | // the user code since it can be lowered into a right shift. |
| 1995 | if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS())) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1996 | if (SC->getAPInt().isPowerOf2()) { |
Sanjoy Das | a9f1e27 | 2015-04-14 03:20:32 +0000 | [diff] [blame] | 1997 | const DataLayout &DL = |
| 1998 | L->getHeader()->getParent()->getParent()->getDataLayout(); |
| 1999 | unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth(); |
| 2000 | return DL.isIllegalInteger(Width); |
| 2001 | } |
| 2002 | |
| 2003 | // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or |
| 2004 | // HowManyLessThans produced to compute a precise expression, rather than a |
| 2005 | // UDiv from the user's code. If we can't find a UDiv in the code with some |
| 2006 | // simple searching, assume the former consider UDivExpr expensive to |
| 2007 | // compute. |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 2008 | BasicBlock *ExitingBB = L->getExitingBlock(); |
| 2009 | if (!ExitingBB) |
| 2010 | return true; |
| 2011 | |
Igor Laevsky | 06044f9 | 2015-08-17 16:37:04 +0000 | [diff] [blame] | 2012 | // At the beginning of this function we already tried to find existing value |
| 2013 | // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern |
| 2014 | // involving division. This is just a simple search heuristic. |
| 2015 | if (!At) |
| 2016 | At = &ExitingBB->back(); |
Wei Mi | 5754350 | 2016-08-09 20:40:03 +0000 | [diff] [blame] | 2017 | if (!getRelatedExistingExpansion( |
Igor Laevsky | 06044f9 | 2015-08-17 16:37:04 +0000 | [diff] [blame] | 2018 | SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L)) |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 2019 | return true; |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 2020 | } |
| 2021 | |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 2022 | // HowManyLessThans uses a Max expression whenever the loop is not guarded by |
| 2023 | // the exit condition. |
| 2024 | if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S)) |
| 2025 | return true; |
| 2026 | |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 2027 | // Recurse past nary expressions, which commonly occur in the |
| 2028 | // BackedgeTakenCount. They may already exist in program code, and if not, |
| 2029 | // they are not too expensive rematerialize. |
| 2030 | if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) { |
Sanjoy Das | b37c4c4 | 2015-11-21 23:20:10 +0000 | [diff] [blame] | 2031 | for (auto *Op : NAry->operands()) |
| 2032 | if (isHighCostExpansionHelper(Op, L, At, Processed)) |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 2033 | return true; |
Wei Mi | e2538b5 | 2015-05-28 21:49:07 +0000 | [diff] [blame] | 2034 | } |
| 2035 | |
Sanjoy Das | 2e6bb3b | 2015-04-14 03:20:28 +0000 | [diff] [blame] | 2036 | // If we haven't recognized an expensive SCEV pattern, assume it's an |
| 2037 | // expression produced by program code. |
| 2038 | return false; |
| 2039 | } |
| 2040 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 2041 | Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred, |
| 2042 | Instruction *IP) { |
| 2043 | assert(IP); |
| 2044 | switch (Pred->getKind()) { |
| 2045 | case SCEVPredicate::P_Union: |
| 2046 | return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP); |
| 2047 | case SCEVPredicate::P_Equal: |
| 2048 | return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2049 | case SCEVPredicate::P_Wrap: { |
| 2050 | auto *AddRecPred = cast<SCEVWrapPredicate>(Pred); |
| 2051 | return expandWrapPredicate(AddRecPred, IP); |
| 2052 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 2053 | } |
| 2054 | llvm_unreachable("Unknown SCEV predicate type"); |
| 2055 | } |
| 2056 | |
| 2057 | Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred, |
| 2058 | Instruction *IP) { |
| 2059 | Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP); |
| 2060 | Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP); |
| 2061 | |
| 2062 | Builder.SetInsertPoint(IP); |
| 2063 | auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check"); |
| 2064 | return I; |
| 2065 | } |
| 2066 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2067 | Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR, |
| 2068 | Instruction *Loc, bool Signed) { |
| 2069 | assert(AR->isAffine() && "Cannot generate RT check for " |
| 2070 | "non-affine expression"); |
| 2071 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 2072 | SCEVUnionPredicate Pred; |
| 2073 | const SCEV *ExitCount = |
| 2074 | SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2075 | |
| 2076 | assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count"); |
| 2077 | |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2078 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 2079 | const SCEV *Start = AR->getStart(); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2080 | |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2081 | unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType()); |
| 2082 | unsigned DstBits = SE.getTypeSizeInBits(AR->getType()); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2083 | |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2084 | // The expression {Start,+,Step} has nusw/nssw if |
| 2085 | // Step < 0, Start - |Step| * Backedge <= Start |
| 2086 | // Step >= 0, Start + |Step| * Backedge > Start |
| 2087 | // and |Step| * Backedge doesn't unsigned overflow. |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2088 | |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2089 | IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits); |
| 2090 | Builder.SetInsertPoint(Loc); |
| 2091 | Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc); |
| 2092 | |
| 2093 | IntegerType *Ty = |
| 2094 | IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(AR->getType())); |
| 2095 | |
| 2096 | Value *StepValue = expandCodeFor(Step, Ty, Loc); |
| 2097 | Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc); |
| 2098 | Value *StartValue = expandCodeFor(Start, Ty, Loc); |
| 2099 | |
| 2100 | ConstantInt *Zero = |
| 2101 | ConstantInt::get(Loc->getContext(), APInt::getNullValue(DstBits)); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2102 | |
| 2103 | Builder.SetInsertPoint(Loc); |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2104 | // Compute |Step| |
| 2105 | Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero); |
| 2106 | Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2107 | |
Silviu Baranga | 795c629 | 2016-04-25 09:27:16 +0000 | [diff] [blame] | 2108 | // Get the backedge taken count and truncate or extended to the AR type. |
| 2109 | Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty); |
| 2110 | auto *MulF = Intrinsic::getDeclaration(Loc->getModule(), |
| 2111 | Intrinsic::umul_with_overflow, Ty); |
| 2112 | |
| 2113 | // Compute |Step| * Backedge |
| 2114 | CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul"); |
| 2115 | Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result"); |
| 2116 | Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow"); |
| 2117 | |
| 2118 | // Compute: |
| 2119 | // Start + |Step| * Backedge < Start |
| 2120 | // Start - |Step| * Backedge > Start |
| 2121 | Value *Add = Builder.CreateAdd(StartValue, MulV); |
| 2122 | Value *Sub = Builder.CreateSub(StartValue, MulV); |
| 2123 | |
| 2124 | Value *EndCompareGT = Builder.CreateICmp( |
| 2125 | Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue); |
| 2126 | |
| 2127 | Value *EndCompareLT = Builder.CreateICmp( |
| 2128 | Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue); |
| 2129 | |
| 2130 | // Select the answer based on the sign of Step. |
| 2131 | Value *EndCheck = |
| 2132 | Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT); |
| 2133 | |
| 2134 | // If the backedge taken count type is larger than the AR type, |
| 2135 | // check that we don't drop any bits by truncating it. If we are |
| 2136 | // droping bits, then we have overflow (unless the step is zero). |
| 2137 | if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) { |
| 2138 | auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits); |
| 2139 | auto *BackedgeCheck = |
| 2140 | Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal, |
| 2141 | ConstantInt::get(Loc->getContext(), MaxVal)); |
| 2142 | BackedgeCheck = Builder.CreateAnd( |
| 2143 | BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero)); |
| 2144 | |
| 2145 | EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck); |
| 2146 | } |
| 2147 | |
| 2148 | EndCheck = Builder.CreateOr(EndCheck, OfMul); |
| 2149 | return EndCheck; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 2150 | } |
| 2151 | |
| 2152 | Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred, |
| 2153 | Instruction *IP) { |
| 2154 | const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr()); |
| 2155 | Value *NSSWCheck = nullptr, *NUSWCheck = nullptr; |
| 2156 | |
| 2157 | // Add a check for NUSW |
| 2158 | if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW) |
| 2159 | NUSWCheck = generateOverflowCheck(A, IP, false); |
| 2160 | |
| 2161 | // Add a check for NSSW |
| 2162 | if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW) |
| 2163 | NSSWCheck = generateOverflowCheck(A, IP, true); |
| 2164 | |
| 2165 | if (NUSWCheck && NSSWCheck) |
| 2166 | return Builder.CreateOr(NUSWCheck, NSSWCheck); |
| 2167 | |
| 2168 | if (NUSWCheck) |
| 2169 | return NUSWCheck; |
| 2170 | |
| 2171 | if (NSSWCheck) |
| 2172 | return NSSWCheck; |
| 2173 | |
| 2174 | return ConstantInt::getFalse(IP->getContext()); |
| 2175 | } |
| 2176 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 2177 | Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union, |
| 2178 | Instruction *IP) { |
| 2179 | auto *BoolType = IntegerType::get(IP->getContext(), 1); |
| 2180 | Value *Check = ConstantInt::getNullValue(BoolType); |
| 2181 | |
| 2182 | // Loop over all checks in this set. |
| 2183 | for (auto Pred : Union->getPredicates()) { |
| 2184 | auto *NextCheck = expandCodeForPredicate(Pred, IP); |
| 2185 | Builder.SetInsertPoint(IP); |
| 2186 | Check = Builder.CreateOr(Check, NextCheck); |
| 2187 | } |
| 2188 | |
| 2189 | return Check; |
| 2190 | } |
| 2191 | |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2192 | namespace { |
| 2193 | // Search for a SCEV subexpression that is not safe to expand. Any expression |
| 2194 | // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely |
| 2195 | // UDiv expressions. We don't know if the UDiv is derived from an IR divide |
| 2196 | // instruction, but the important thing is that we prove the denominator is |
| 2197 | // nonzero before expansion. |
| 2198 | // |
| 2199 | // IVUsers already checks that IV-derived expressions are safe. So this check is |
| 2200 | // only needed when the expression includes some subexpression that is not IV |
| 2201 | // derived. |
| 2202 | // |
| 2203 | // Currently, we only allow division by a nonzero constant here. If this is |
| 2204 | // inadequate, we could easily allow division by SCEVUnknown by using |
| 2205 | // ValueTracking to check isKnownNonZero(). |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 2206 | // |
| 2207 | // We cannot generally expand recurrences unless the step dominates the loop |
| 2208 | // header. The expander handles the special case of affine recurrences by |
| 2209 | // scaling the recurrence outside the loop, but this technique isn't generally |
| 2210 | // applicable. Expanding a nested recurrence outside a loop requires computing |
| 2211 | // binomial coefficients. This could be done, but the recurrence has to be in a |
| 2212 | // perfectly reduced form, which can't be guaranteed. |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2213 | struct SCEVFindUnsafe { |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 2214 | ScalarEvolution &SE; |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2215 | bool IsUnsafe; |
| 2216 | |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 2217 | SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {} |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2218 | |
| 2219 | bool follow(const SCEV *S) { |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 2220 | if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { |
| 2221 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS()); |
| 2222 | if (!SC || SC->getValue()->isZero()) { |
| 2223 | IsUnsafe = true; |
| 2224 | return false; |
| 2225 | } |
| 2226 | } |
| 2227 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 2228 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 2229 | if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) { |
| 2230 | IsUnsafe = true; |
| 2231 | return false; |
| 2232 | } |
| 2233 | } |
| 2234 | return true; |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2235 | } |
| 2236 | bool isDone() const { return IsUnsafe; } |
| 2237 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 2238 | } |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2239 | |
| 2240 | namespace llvm { |
Andrew Trick | 57243da | 2013-10-25 21:35:56 +0000 | [diff] [blame] | 2241 | bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) { |
| 2242 | SCEVFindUnsafe Search(SE); |
Andrew Trick | 653513b | 2012-07-13 23:33:10 +0000 | [diff] [blame] | 2243 | visitAll(S, Search); |
| 2244 | return !Search.IsUnsafe; |
| 2245 | } |
| 2246 | } |