Chris Lattner | e679449 | 2002-08-12 21:17:25 +0000 | [diff] [blame] | 1 | //===- InstructionCombining.cpp - Combine multiple instructions -----------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 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. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
John Criswell | 482202a | 2003-10-20 19:43:21 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 9 | // |
| 10 | // InstructionCombining - Combine instructions to form fewer, simple |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 11 | // instructions. This pass does not modify the CFG. This pass is where |
| 12 | // algebraic simplification happens. |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 13 | // |
| 14 | // This pass combines things like: |
Chris Lattner | 0741842 | 2007-03-18 22:51:34 +0000 | [diff] [blame] | 15 | // %Y = add i32 %X, 1 |
| 16 | // %Z = add i32 %Y, 1 |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 17 | // into: |
Chris Lattner | 0741842 | 2007-03-18 22:51:34 +0000 | [diff] [blame] | 18 | // %Z = add i32 %X, 2 |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 19 | // |
| 20 | // This is a simple worklist driven algorithm. |
| 21 | // |
Chris Lattner | 216c7b8 | 2003-09-10 05:29:43 +0000 | [diff] [blame] | 22 | // This pass guarantees that the following canonicalizations are performed on |
Chris Lattner | bfb1d03 | 2003-07-23 21:41:57 +0000 | [diff] [blame] | 23 | // the program: |
| 24 | // 1. If a binary operator has a constant operand, it is moved to the RHS |
Chris Lattner | deaa0dd | 2003-08-12 21:53:41 +0000 | [diff] [blame] | 25 | // 2. Bitwise operators with constant operands are always grouped so that |
| 26 | // shifts are performed first, then or's, then and's, then xor's. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 27 | // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible |
| 28 | // 4. All cmp instructions on boolean values are replaced with logical ops |
Chris Lattner | ede3fe0 | 2003-08-13 04:18:28 +0000 | [diff] [blame] | 29 | // 5. add X, X is represented as (X*2) => (X << 1) |
| 30 | // 6. Multiplies with a power-of-two constant argument are transformed into |
| 31 | // shifts. |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 32 | // ... etc. |
Chris Lattner | bfb1d03 | 2003-07-23 21:41:57 +0000 | [diff] [blame] | 33 | // |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 34 | //===----------------------------------------------------------------------===// |
| 35 | |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/InstCombine/InstCombine.h" |
Chandler Carruth | a917458 | 2015-01-22 05:25:13 +0000 | [diff] [blame] | 37 | #include "InstCombineInternal.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 38 | #include "llvm-c/Initialization.h" |
| 39 | #include "llvm/ADT/SmallPtrSet.h" |
| 40 | #include "llvm/ADT/Statistic.h" |
| 41 | #include "llvm/ADT/StringSwitch.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 42 | #include "llvm/Analysis/AssumptionCache.h" |
David Majnemer | 7e2b988 | 2014-11-03 21:55:12 +0000 | [diff] [blame] | 43 | #include "llvm/Analysis/CFG.h" |
Chris Lattner | 024f4ab | 2007-01-30 23:46:24 +0000 | [diff] [blame] | 44 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 45 | #include "llvm/Analysis/GlobalsModRef.h" |
Chris Lattner | c1f1907 | 2009-11-09 23:28:39 +0000 | [diff] [blame] | 46 | #include "llvm/Analysis/InstructionSimplify.h" |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 47 | #include "llvm/Analysis/LibCallSemantics.h" |
David Majnemer | 7e2b988 | 2014-11-03 21:55:12 +0000 | [diff] [blame] | 48 | #include "llvm/Analysis/LoopInfo.h" |
Victor Hernandez | f390e04 | 2009-10-27 20:05:49 +0000 | [diff] [blame] | 49 | #include "llvm/Analysis/MemoryBuiltins.h" |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 50 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Sanjay Patel | 5881444 | 2014-07-09 16:34:54 +0000 | [diff] [blame] | 51 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1305dc3 | 2014-03-04 11:45:46 +0000 | [diff] [blame] | 52 | #include "llvm/IR/CFG.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 53 | #include "llvm/IR/DataLayout.h" |
Hal Finkel | 60db058 | 2014-09-07 18:57:58 +0000 | [diff] [blame] | 54 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 55 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 56 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 57 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 58 | #include "llvm/IR/ValueHandle.h" |
Meador Inge | 193e035 | 2012-11-13 04:16:17 +0000 | [diff] [blame] | 59 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 60 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 61 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 62 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 63 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | 053c093 | 2002-05-14 15:24:07 +0000 | [diff] [blame] | 64 | #include <algorithm> |
Torok Edwin | ab20784 | 2008-04-20 08:33:11 +0000 | [diff] [blame] | 65 | #include <climits> |
Chris Lattner | 8427bff | 2003-12-07 01:24:23 +0000 | [diff] [blame] | 66 | using namespace llvm; |
Chris Lattner | d4252a7 | 2004-07-30 07:50:03 +0000 | [diff] [blame] | 67 | using namespace llvm::PatternMatch; |
Brian Gaeke | 960707c | 2003-11-11 22:41:34 +0000 | [diff] [blame] | 68 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 69 | #define DEBUG_TYPE "instcombine" |
| 70 | |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 71 | STATISTIC(NumCombined , "Number of insts combined"); |
| 72 | STATISTIC(NumConstProp, "Number of constant folds"); |
| 73 | STATISTIC(NumDeadInst , "Number of dead inst eliminated"); |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 74 | STATISTIC(NumSunkInst , "Number of instructions sunk"); |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 75 | STATISTIC(NumExpand, "Number of expansions"); |
Duncan Sands | 3547d2e | 2010-12-22 09:40:51 +0000 | [diff] [blame] | 76 | STATISTIC(NumFactor , "Number of factorizations"); |
| 77 | STATISTIC(NumReassoc , "Number of reassociations"); |
Chris Lattner | bf3a099 | 2002-10-01 22:38:41 +0000 | [diff] [blame] | 78 | |
Nuno Lopes | a2f6cec | 2012-05-22 17:19:09 +0000 | [diff] [blame] | 79 | Value *InstCombiner::EmitGEPOffset(User *GEP) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 80 | return llvm::EmitGEPOffset(Builder, DL, GEP); |
Nuno Lopes | a2f6cec | 2012-05-22 17:19:09 +0000 | [diff] [blame] | 81 | } |
| 82 | |
Sanjay Patel | 55dcd40 | 2015-09-21 16:09:37 +0000 | [diff] [blame] | 83 | /// Return true if it is desirable to convert an integer computation from a |
| 84 | /// given bit width to a new bit width. |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 85 | /// We don't want to convert from a legal to an illegal type for example or from |
| 86 | /// a smaller to a larger illegal type. |
Sanjay Patel | 55dcd40 | 2015-09-21 16:09:37 +0000 | [diff] [blame] | 87 | bool InstCombiner::ShouldChangeType(unsigned FromWidth, |
| 88 | unsigned ToWidth) const { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 89 | bool FromLegal = DL.isLegalInteger(FromWidth); |
| 90 | bool ToLegal = DL.isLegalInteger(ToWidth); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 91 | |
Chris Lattner | 1559bed | 2009-11-10 07:23:37 +0000 | [diff] [blame] | 92 | // If this is a legal integer from type, and the result would be an illegal |
| 93 | // type, don't do the transformation. |
| 94 | if (FromLegal && !ToLegal) |
| 95 | return false; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 96 | |
Chris Lattner | 1559bed | 2009-11-10 07:23:37 +0000 | [diff] [blame] | 97 | // Otherwise, if both are illegal, do not increase the size of the result. We |
| 98 | // do allow things like i160 -> i64, but not i64 -> i160. |
| 99 | if (!FromLegal && !ToLegal && ToWidth > FromWidth) |
| 100 | return false; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 101 | |
Chris Lattner | 1559bed | 2009-11-10 07:23:37 +0000 | [diff] [blame] | 102 | return true; |
| 103 | } |
| 104 | |
Sanjay Patel | 55dcd40 | 2015-09-21 16:09:37 +0000 | [diff] [blame] | 105 | /// Return true if it is desirable to convert a computation from 'From' to 'To'. |
| 106 | /// We don't want to convert from a legal to an illegal type for example or from |
| 107 | /// a smaller to a larger illegal type. |
| 108 | bool InstCombiner::ShouldChangeType(Type *From, Type *To) const { |
| 109 | assert(From->isIntegerTy() && To->isIntegerTy()); |
| 110 | |
| 111 | unsigned FromWidth = From->getPrimitiveSizeInBits(); |
| 112 | unsigned ToWidth = To->getPrimitiveSizeInBits(); |
| 113 | return ShouldChangeType(FromWidth, ToWidth); |
| 114 | } |
| 115 | |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 116 | // Return true, if No Signed Wrap should be maintained for I. |
| 117 | // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", |
| 118 | // where both B and C should be ConstantInts, results in a constant that does |
| 119 | // not overflow. This function only handles the Add and Sub opcodes. For |
| 120 | // all other opcodes, the function conservatively returns false. |
| 121 | static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { |
| 122 | OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I); |
| 123 | if (!OBO || !OBO->hasNoSignedWrap()) { |
| 124 | return false; |
| 125 | } |
| 126 | |
| 127 | // We reason about Add and Sub Only. |
| 128 | Instruction::BinaryOps Opcode = I.getOpcode(); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 129 | if (Opcode != Instruction::Add && |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 130 | Opcode != Instruction::Sub) { |
| 131 | return false; |
| 132 | } |
| 133 | |
| 134 | ConstantInt *CB = dyn_cast<ConstantInt>(B); |
| 135 | ConstantInt *CC = dyn_cast<ConstantInt>(C); |
| 136 | |
| 137 | if (!CB || !CC) { |
| 138 | return false; |
| 139 | } |
| 140 | |
| 141 | const APInt &BVal = CB->getValue(); |
| 142 | const APInt &CVal = CC->getValue(); |
| 143 | bool Overflow = false; |
| 144 | |
| 145 | if (Opcode == Instruction::Add) { |
| 146 | BVal.sadd_ov(CVal, Overflow); |
| 147 | } else { |
| 148 | BVal.ssub_ov(CVal, Overflow); |
| 149 | } |
| 150 | |
| 151 | return !Overflow; |
| 152 | } |
| 153 | |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 154 | /// Conservatively clears subclassOptionalData after a reassociation or |
| 155 | /// commutation. We preserve fast-math flags when applicable as they can be |
| 156 | /// preserved. |
| 157 | static void ClearSubclassDataAfterReassociation(BinaryOperator &I) { |
| 158 | FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I); |
| 159 | if (!FPMO) { |
| 160 | I.clearSubclassOptionalData(); |
| 161 | return; |
| 162 | } |
| 163 | |
| 164 | FastMathFlags FMF = I.getFastMathFlags(); |
| 165 | I.clearSubclassOptionalData(); |
| 166 | I.setFastMathFlags(FMF); |
| 167 | } |
| 168 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 169 | /// This performs a few simplifications for operators that are associative or |
| 170 | /// commutative: |
| 171 | /// |
| 172 | /// Commutative operators: |
| 173 | /// |
| 174 | /// 1. Order operands such that they are listed from right (least complex) to |
| 175 | /// left (most complex). This puts constants before unary operators before |
| 176 | /// binary operators. |
| 177 | /// |
| 178 | /// Associative operators: |
| 179 | /// |
| 180 | /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. |
| 181 | /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. |
| 182 | /// |
| 183 | /// Associative and commutative operators: |
| 184 | /// |
| 185 | /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. |
| 186 | /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. |
| 187 | /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" |
| 188 | /// if C1 and C2 are constants. |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 189 | bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) { |
Chris Lattner | dcf240a | 2003-03-10 21:43:22 +0000 | [diff] [blame] | 190 | Instruction::BinaryOps Opcode = I.getOpcode(); |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 191 | bool Changed = false; |
Chris Lattner | 7fb29e1 | 2003-03-11 00:12:48 +0000 | [diff] [blame] | 192 | |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 193 | do { |
| 194 | // Order operands such that they are listed from right (least complex) to |
| 195 | // left (most complex). This puts constants before unary operators before |
| 196 | // binary operators. |
| 197 | if (I.isCommutative() && getComplexity(I.getOperand(0)) < |
| 198 | getComplexity(I.getOperand(1))) |
| 199 | Changed = !I.swapOperands(); |
| 200 | |
| 201 | BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); |
| 202 | BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); |
| 203 | |
| 204 | if (I.isAssociative()) { |
| 205 | // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. |
| 206 | if (Op0 && Op0->getOpcode() == Opcode) { |
| 207 | Value *A = Op0->getOperand(0); |
| 208 | Value *B = Op0->getOperand(1); |
| 209 | Value *C = I.getOperand(1); |
| 210 | |
| 211 | // Does "B op C" simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 212 | if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) { |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 213 | // It simplifies to V. Form "A op V". |
| 214 | I.setOperand(0, A); |
| 215 | I.setOperand(1, V); |
Dan Gohman | c6f0bda | 2011-02-02 02:05:46 +0000 | [diff] [blame] | 216 | // Conservatively clear the optional flags, since they may not be |
| 217 | // preserved by the reassociation. |
Nick Lewycky | ae13df6 | 2011-08-14 03:41:33 +0000 | [diff] [blame] | 218 | if (MaintainNoSignedWrap(I, B, C) && |
Bill Wendling | ea6397f | 2012-07-19 00:11:40 +0000 | [diff] [blame] | 219 | (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) { |
Nick Lewycky | ae13df6 | 2011-08-14 03:41:33 +0000 | [diff] [blame] | 220 | // Note: this is only valid because SimplifyBinOp doesn't look at |
| 221 | // the operands to Op0. |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 222 | I.clearSubclassOptionalData(); |
| 223 | I.setHasNoSignedWrap(true); |
| 224 | } else { |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 225 | ClearSubclassDataAfterReassociation(I); |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 226 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 227 | |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 228 | Changed = true; |
Duncan Sands | 3547d2e | 2010-12-22 09:40:51 +0000 | [diff] [blame] | 229 | ++NumReassoc; |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 230 | continue; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 231 | } |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 232 | } |
| 233 | |
| 234 | // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. |
| 235 | if (Op1 && Op1->getOpcode() == Opcode) { |
| 236 | Value *A = I.getOperand(0); |
| 237 | Value *B = Op1->getOperand(0); |
| 238 | Value *C = Op1->getOperand(1); |
| 239 | |
| 240 | // Does "A op B" simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 241 | if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) { |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 242 | // It simplifies to V. Form "V op C". |
| 243 | I.setOperand(0, V); |
| 244 | I.setOperand(1, C); |
Dan Gohman | c6f0bda | 2011-02-02 02:05:46 +0000 | [diff] [blame] | 245 | // Conservatively clear the optional flags, since they may not be |
| 246 | // preserved by the reassociation. |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 247 | ClearSubclassDataAfterReassociation(I); |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 248 | Changed = true; |
Duncan Sands | 3547d2e | 2010-12-22 09:40:51 +0000 | [diff] [blame] | 249 | ++NumReassoc; |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 250 | continue; |
| 251 | } |
| 252 | } |
Chris Lattner | dcf240a | 2003-03-10 21:43:22 +0000 | [diff] [blame] | 253 | } |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 254 | |
| 255 | if (I.isAssociative() && I.isCommutative()) { |
| 256 | // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. |
| 257 | if (Op0 && Op0->getOpcode() == Opcode) { |
| 258 | Value *A = Op0->getOperand(0); |
| 259 | Value *B = Op0->getOperand(1); |
| 260 | Value *C = I.getOperand(1); |
| 261 | |
| 262 | // Does "C op A" simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 263 | if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) { |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 264 | // It simplifies to V. Form "V op B". |
| 265 | I.setOperand(0, V); |
| 266 | I.setOperand(1, B); |
Dan Gohman | c6f0bda | 2011-02-02 02:05:46 +0000 | [diff] [blame] | 267 | // Conservatively clear the optional flags, since they may not be |
| 268 | // preserved by the reassociation. |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 269 | ClearSubclassDataAfterReassociation(I); |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 270 | Changed = true; |
Duncan Sands | 3547d2e | 2010-12-22 09:40:51 +0000 | [diff] [blame] | 271 | ++NumReassoc; |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 272 | continue; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. |
| 277 | if (Op1 && Op1->getOpcode() == Opcode) { |
| 278 | Value *A = I.getOperand(0); |
| 279 | Value *B = Op1->getOperand(0); |
| 280 | Value *C = Op1->getOperand(1); |
| 281 | |
| 282 | // Does "C op A" simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 283 | if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) { |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 284 | // It simplifies to V. Form "B op V". |
| 285 | I.setOperand(0, B); |
| 286 | I.setOperand(1, V); |
Dan Gohman | c6f0bda | 2011-02-02 02:05:46 +0000 | [diff] [blame] | 287 | // Conservatively clear the optional flags, since they may not be |
| 288 | // preserved by the reassociation. |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 289 | ClearSubclassDataAfterReassociation(I); |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 290 | Changed = true; |
Duncan Sands | 3547d2e | 2010-12-22 09:40:51 +0000 | [diff] [blame] | 291 | ++NumReassoc; |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 292 | continue; |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" |
| 297 | // if C1 and C2 are constants. |
| 298 | if (Op0 && Op1 && |
| 299 | Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && |
| 300 | isa<Constant>(Op0->getOperand(1)) && |
| 301 | isa<Constant>(Op1->getOperand(1)) && |
| 302 | Op0->hasOneUse() && Op1->hasOneUse()) { |
| 303 | Value *A = Op0->getOperand(0); |
| 304 | Constant *C1 = cast<Constant>(Op0->getOperand(1)); |
| 305 | Value *B = Op1->getOperand(0); |
| 306 | Constant *C2 = cast<Constant>(Op1->getOperand(1)); |
| 307 | |
| 308 | Constant *Folded = ConstantExpr::get(Opcode, C1, C2); |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 309 | BinaryOperator *New = BinaryOperator::Create(Opcode, A, B); |
Owen Anderson | 1664dc8 | 2014-01-20 07:44:53 +0000 | [diff] [blame] | 310 | if (isa<FPMathOperator>(New)) { |
| 311 | FastMathFlags Flags = I.getFastMathFlags(); |
| 312 | Flags &= Op0->getFastMathFlags(); |
| 313 | Flags &= Op1->getFastMathFlags(); |
| 314 | New->setFastMathFlags(Flags); |
| 315 | } |
Eli Friedman | 35211c6 | 2011-05-27 00:19:40 +0000 | [diff] [blame] | 316 | InsertNewInstWith(New, I); |
Eli Friedman | 41e509a | 2011-05-18 23:58:37 +0000 | [diff] [blame] | 317 | New->takeName(Op1); |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 318 | I.setOperand(0, New); |
| 319 | I.setOperand(1, Folded); |
Dan Gohman | c6f0bda | 2011-02-02 02:05:46 +0000 | [diff] [blame] | 320 | // Conservatively clear the optional flags, since they may not be |
| 321 | // preserved by the reassociation. |
Michael Ilseman | 1dd6f2a | 2013-02-07 01:40:15 +0000 | [diff] [blame] | 322 | ClearSubclassDataAfterReassociation(I); |
Nick Lewycky | de49278 | 2011-08-14 01:45:19 +0000 | [diff] [blame] | 323 | |
Duncan Sands | 641baf1 | 2010-11-13 15:10:37 +0000 | [diff] [blame] | 324 | Changed = true; |
| 325 | continue; |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // No further simplifications. |
| 330 | return Changed; |
| 331 | } while (1); |
Chris Lattner | 260ab20 | 2002-04-18 17:39:14 +0000 | [diff] [blame] | 332 | } |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 333 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 334 | /// Return whether "X LOp (Y ROp Z)" is always equal to |
Duncan Sands | 22df741 | 2010-11-23 15:25:34 +0000 | [diff] [blame] | 335 | /// "(X LOp Y) ROp (X LOp Z)". |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 336 | static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, |
| 337 | Instruction::BinaryOps ROp) { |
| 338 | switch (LOp) { |
| 339 | default: |
| 340 | return false; |
| 341 | |
| 342 | case Instruction::And: |
| 343 | // And distributes over Or and Xor. |
| 344 | switch (ROp) { |
| 345 | default: |
| 346 | return false; |
| 347 | case Instruction::Or: |
| 348 | case Instruction::Xor: |
| 349 | return true; |
| 350 | } |
| 351 | |
| 352 | case Instruction::Mul: |
| 353 | // Multiplication distributes over addition and subtraction. |
| 354 | switch (ROp) { |
| 355 | default: |
| 356 | return false; |
| 357 | case Instruction::Add: |
| 358 | case Instruction::Sub: |
| 359 | return true; |
| 360 | } |
| 361 | |
| 362 | case Instruction::Or: |
| 363 | // Or distributes over And. |
| 364 | switch (ROp) { |
| 365 | default: |
| 366 | return false; |
| 367 | case Instruction::And: |
| 368 | return true; |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 373 | /// Return whether "(X LOp Y) ROp Z" is always equal to |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 374 | /// "(X ROp Z) LOp (Y ROp Z)". |
| 375 | static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, |
| 376 | Instruction::BinaryOps ROp) { |
| 377 | if (Instruction::isCommutative(ROp)) |
| 378 | return LeftDistributesOverRight(ROp, LOp); |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 379 | |
| 380 | switch (LOp) { |
| 381 | default: |
| 382 | return false; |
| 383 | // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts. |
| 384 | // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts. |
| 385 | // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts. |
| 386 | case Instruction::And: |
| 387 | case Instruction::Or: |
| 388 | case Instruction::Xor: |
| 389 | switch (ROp) { |
| 390 | default: |
| 391 | return false; |
| 392 | case Instruction::Shl: |
| 393 | case Instruction::LShr: |
| 394 | case Instruction::AShr: |
| 395 | return true; |
| 396 | } |
| 397 | } |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 398 | // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", |
| 399 | // but this requires knowing that the addition does not overflow and other |
| 400 | // such subtleties. |
| 401 | return false; |
| 402 | } |
| 403 | |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 404 | /// This function returns identity value for given opcode, which can be used to |
| 405 | /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1). |
| 406 | static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) { |
| 407 | if (isa<Constant>(V)) |
| 408 | return nullptr; |
| 409 | |
| 410 | if (OpCode == Instruction::Mul) |
| 411 | return ConstantInt::get(V->getType(), 1); |
| 412 | |
| 413 | // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc. |
| 414 | |
| 415 | return nullptr; |
| 416 | } |
| 417 | |
| 418 | /// This function factors binary ops which can be combined using distributive |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 419 | /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable |
| 420 | /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called |
| 421 | /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms |
| 422 | /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and |
| 423 | /// RHS to 4. |
Benjamin Kramer | 6cbe670 | 2014-07-07 14:47:51 +0000 | [diff] [blame] | 424 | static Instruction::BinaryOps |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 425 | getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode, |
| 426 | BinaryOperator *Op, Value *&LHS, Value *&RHS) { |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 427 | if (!Op) |
| 428 | return Instruction::BinaryOpsEnd; |
| 429 | |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 430 | LHS = Op->getOperand(0); |
| 431 | RHS = Op->getOperand(1); |
| 432 | |
| 433 | switch (TopLevelOpcode) { |
| 434 | default: |
| 435 | return Op->getOpcode(); |
| 436 | |
| 437 | case Instruction::Add: |
| 438 | case Instruction::Sub: |
| 439 | if (Op->getOpcode() == Instruction::Shl) { |
| 440 | if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) { |
| 441 | // The multiplier is really 1 << CST. |
| 442 | RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST); |
| 443 | return Instruction::Mul; |
| 444 | } |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 445 | } |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 446 | return Op->getOpcode(); |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 447 | } |
| 448 | |
| 449 | // TODO: We can add other conversions e.g. shr => div etc. |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 450 | } |
| 451 | |
| 452 | /// This tries to simplify binary operations by factorizing out common terms |
| 453 | /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)"). |
| 454 | static Value *tryFactorization(InstCombiner::BuilderTy *Builder, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 455 | const DataLayout &DL, BinaryOperator &I, |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 456 | Instruction::BinaryOps InnerOpcode, Value *A, |
| 457 | Value *B, Value *C, Value *D) { |
| 458 | |
| 459 | // If any of A, B, C, D are null, we can not factor I, return early. |
| 460 | // Checking A and C should be enough. |
| 461 | if (!A || !C || !B || !D) |
| 462 | return nullptr; |
| 463 | |
David Majnemer | 4c3753c | 2015-05-22 23:02:11 +0000 | [diff] [blame] | 464 | Value *V = nullptr; |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 465 | Value *SimplifiedInst = nullptr; |
| 466 | Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); |
| 467 | Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); |
| 468 | |
| 469 | // Does "X op' Y" always equal "Y op' X"? |
| 470 | bool InnerCommutative = Instruction::isCommutative(InnerOpcode); |
| 471 | |
| 472 | // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? |
| 473 | if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode)) |
| 474 | // Does the instruction have the form "(A op' B) op (A op' D)" or, in the |
| 475 | // commutative case, "(A op' B) op (C op' A)"? |
| 476 | if (A == C || (InnerCommutative && A == D)) { |
| 477 | if (A != C) |
| 478 | std::swap(C, D); |
| 479 | // Consider forming "A op' (B op D)". |
| 480 | // If "B op D" simplifies then it can be formed with no cost. |
David Majnemer | 4c3753c | 2015-05-22 23:02:11 +0000 | [diff] [blame] | 481 | V = SimplifyBinOp(TopLevelOpcode, B, D, DL); |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 482 | // If "B op D" doesn't simplify then only go on if both of the existing |
| 483 | // operations "A op' B" and "C op' D" will be zapped as no longer used. |
| 484 | if (!V && LHS->hasOneUse() && RHS->hasOneUse()) |
| 485 | V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName()); |
| 486 | if (V) { |
| 487 | SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? |
| 492 | if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) |
| 493 | // Does the instruction have the form "(A op' B) op (C op' B)" or, in the |
| 494 | // commutative case, "(A op' B) op (B op' D)"? |
| 495 | if (B == D || (InnerCommutative && B == C)) { |
| 496 | if (B != D) |
| 497 | std::swap(C, D); |
| 498 | // Consider forming "(A op C) op' B". |
| 499 | // If "A op C" simplifies then it can be formed with no cost. |
David Majnemer | 4c3753c | 2015-05-22 23:02:11 +0000 | [diff] [blame] | 500 | V = SimplifyBinOp(TopLevelOpcode, A, C, DL); |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 501 | |
| 502 | // If "A op C" doesn't simplify then only go on if both of the existing |
| 503 | // operations "A op' B" and "C op' D" will be zapped as no longer used. |
| 504 | if (!V && LHS->hasOneUse() && RHS->hasOneUse()) |
| 505 | V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName()); |
| 506 | if (V) { |
| 507 | SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B); |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | if (SimplifiedInst) { |
| 512 | ++NumFactor; |
| 513 | SimplifiedInst->takeName(&I); |
| 514 | |
| 515 | // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag. |
| 516 | // TODO: Check for NUW. |
| 517 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) { |
| 518 | if (isa<OverflowingBinaryOperator>(SimplifiedInst)) { |
| 519 | bool HasNSW = false; |
| 520 | if (isa<OverflowingBinaryOperator>(&I)) |
| 521 | HasNSW = I.hasNoSignedWrap(); |
| 522 | |
| 523 | if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) |
| 524 | if (isa<OverflowingBinaryOperator>(Op0)) |
| 525 | HasNSW &= Op0->hasNoSignedWrap(); |
| 526 | |
| 527 | if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) |
| 528 | if (isa<OverflowingBinaryOperator>(Op1)) |
| 529 | HasNSW &= Op1->hasNoSignedWrap(); |
David Majnemer | 4c3753c | 2015-05-22 23:02:11 +0000 | [diff] [blame] | 530 | |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 531 | // We can propagate 'nsw' if we know that |
David Majnemer | 4c3753c | 2015-05-22 23:02:11 +0000 | [diff] [blame] | 532 | // %Y = mul nsw i16 %X, C |
| 533 | // %Z = add nsw i16 %Y, %X |
| 534 | // => |
| 535 | // %Z = mul nsw i16 %X, C+1 |
| 536 | // |
| 537 | // iff C+1 isn't INT_MIN |
| 538 | const APInt *CInt; |
| 539 | if (TopLevelOpcode == Instruction::Add && |
| 540 | InnerOpcode == Instruction::Mul) |
| 541 | if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue()) |
| 542 | BO->setHasNoSignedWrap(HasNSW); |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 543 | } |
| 544 | } |
| 545 | } |
| 546 | return SimplifiedInst; |
| 547 | } |
| 548 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 549 | /// This tries to simplify binary operations which some other binary operation |
| 550 | /// distributes over either by factorizing out common terms |
| 551 | /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in |
| 552 | /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win). |
| 553 | /// Returns the simplified value, or null if it didn't simplify. |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 554 | Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) { |
| 555 | Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); |
| 556 | BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); |
| 557 | BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 558 | |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 559 | // Factorization. |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 560 | Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; |
Dinesh Dwivedi | 4919bbe | 2014-08-26 08:53:32 +0000 | [diff] [blame] | 561 | auto TopLevelOpcode = I.getOpcode(); |
| 562 | auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B); |
| 563 | auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D); |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 564 | |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 565 | // The instruction has the form "(A op' B) op (C op' D)". Try to factorize |
| 566 | // a common term. |
| 567 | if (LHSOpcode == RHSOpcode) { |
| 568 | if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D)) |
| 569 | return V; |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 570 | } |
| 571 | |
Dinesh Dwivedi | b62e52e | 2014-06-19 08:29:18 +0000 | [diff] [blame] | 572 | // The instruction has the form "(A op' B) op (C)". Try to factorize common |
| 573 | // term. |
| 574 | if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS, |
| 575 | getIdentityValue(LHSOpcode, RHS))) |
| 576 | return V; |
| 577 | |
| 578 | // The instruction has the form "(B) op (C op' D)". Try to factorize common |
| 579 | // term. |
| 580 | if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS, |
| 581 | getIdentityValue(RHSOpcode, LHS), C, D)) |
| 582 | return V; |
| 583 | |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 584 | // Expansion. |
| 585 | if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { |
| 586 | // The instruction has the form "(A op' B) op C". See if expanding it out |
| 587 | // to "(A op C) op' (B op C)" results in simplifications. |
| 588 | Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; |
| 589 | Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' |
| 590 | |
| 591 | // Do "A op C" and "B op C" both simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 592 | if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL)) |
| 593 | if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) { |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 594 | // They do! Return "L op' R". |
| 595 | ++NumExpand; |
| 596 | // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. |
| 597 | if ((L == A && R == B) || |
| 598 | (Instruction::isCommutative(InnerOpcode) && L == B && R == A)) |
| 599 | return Op0; |
| 600 | // Otherwise return "L op' R" if it simplifies. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 601 | if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL)) |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 602 | return V; |
| 603 | // Otherwise, create a new instruction. |
| 604 | C = Builder->CreateBinOp(InnerOpcode, L, R); |
| 605 | C->takeName(&I); |
| 606 | return C; |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { |
| 611 | // The instruction has the form "A op (B op' C)". See if expanding it out |
| 612 | // to "(A op B) op' (A op C)" results in simplifications. |
| 613 | Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); |
| 614 | Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' |
| 615 | |
| 616 | // Do "A op B" and "A op C" both simplify? |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 617 | if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL)) |
| 618 | if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) { |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 619 | // They do! Return "L op' R". |
| 620 | ++NumExpand; |
| 621 | // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. |
| 622 | if ((L == B && R == C) || |
| 623 | (Instruction::isCommutative(InnerOpcode) && L == C && R == B)) |
| 624 | return Op1; |
| 625 | // Otherwise return "L op' R" if it simplifies. |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 626 | if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL)) |
Duncan Sands | fbb9ac3 | 2010-12-22 13:36:08 +0000 | [diff] [blame] | 627 | return V; |
| 628 | // Otherwise, create a new instruction. |
| 629 | A = Builder->CreateBinOp(InnerOpcode, L, R); |
| 630 | A->takeName(&I); |
| 631 | return A; |
| 632 | } |
| 633 | } |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 634 | |
David Majnemer | 33b6f82 | 2015-07-14 22:39:23 +0000 | [diff] [blame] | 635 | // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0)) |
| 636 | // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d))) |
| 637 | if (auto *SI0 = dyn_cast<SelectInst>(LHS)) { |
| 638 | if (auto *SI1 = dyn_cast<SelectInst>(RHS)) { |
| 639 | if (SI0->getCondition() == SI1->getCondition()) { |
| 640 | Value *SI = nullptr; |
| 641 | if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(), |
| 642 | SI1->getFalseValue(), DL, TLI, DT, AC)) |
| 643 | SI = Builder->CreateSelect(SI0->getCondition(), |
| 644 | Builder->CreateBinOp(TopLevelOpcode, |
| 645 | SI0->getTrueValue(), |
| 646 | SI1->getTrueValue()), |
| 647 | V); |
| 648 | if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(), |
| 649 | SI1->getTrueValue(), DL, TLI, DT, AC)) |
| 650 | SI = Builder->CreateSelect( |
| 651 | SI0->getCondition(), V, |
| 652 | Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(), |
| 653 | SI1->getFalseValue())); |
| 654 | if (SI) { |
| 655 | SI->takeName(&I); |
| 656 | return SI; |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 662 | return nullptr; |
Duncan Sands | adc7771f | 2010-11-23 14:23:47 +0000 | [diff] [blame] | 663 | } |
| 664 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 665 | /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a |
| 666 | /// constant zero (which is the 'negate' form). |
Chris Lattner | 2188e40 | 2010-01-04 07:37:31 +0000 | [diff] [blame] | 667 | Value *InstCombiner::dyn_castNegVal(Value *V) const { |
Owen Anderson | bb2501b | 2009-07-13 22:18:28 +0000 | [diff] [blame] | 668 | if (BinaryOperator::isNeg(V)) |
Chris Lattner | d6f636a | 2005-04-24 07:30:14 +0000 | [diff] [blame] | 669 | return BinaryOperator::getNegArgument(V); |
Chris Lattner | bb74e22 | 2003-03-10 23:06:50 +0000 | [diff] [blame] | 670 | |
Chris Lattner | 9ad0d55 | 2004-12-14 20:08:06 +0000 | [diff] [blame] | 671 | // Constants can be considered to be negated values if they can be folded. |
| 672 | if (ConstantInt *C = dyn_cast<ConstantInt>(V)) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 673 | return ConstantExpr::getNeg(C); |
Nick Lewycky | 3bf5512 | 2008-05-23 04:54:45 +0000 | [diff] [blame] | 674 | |
Chris Lattner | 8213c8a | 2012-02-06 21:56:39 +0000 | [diff] [blame] | 675 | if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) |
| 676 | if (C->getType()->getElementType()->isIntegerTy()) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 677 | return ConstantExpr::getNeg(C); |
Nick Lewycky | 3bf5512 | 2008-05-23 04:54:45 +0000 | [diff] [blame] | 678 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 679 | return nullptr; |
Chris Lattner | 9fa53de | 2002-05-06 16:49:18 +0000 | [diff] [blame] | 680 | } |
| 681 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 682 | /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is |
| 683 | /// a constant negative zero (which is the 'negate' form). |
Shuxin Yang | f0537ab | 2013-01-09 00:13:41 +0000 | [diff] [blame] | 684 | Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const { |
| 685 | if (BinaryOperator::isFNeg(V, IgnoreZeroSign)) |
Dan Gohman | a5b9645 | 2009-06-04 22:49:04 +0000 | [diff] [blame] | 686 | return BinaryOperator::getFNegArgument(V); |
| 687 | |
| 688 | // Constants can be considered to be negated values if they can be folded. |
| 689 | if (ConstantFP *C = dyn_cast<ConstantFP>(V)) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 690 | return ConstantExpr::getFNeg(C); |
Dan Gohman | a5b9645 | 2009-06-04 22:49:04 +0000 | [diff] [blame] | 691 | |
Chris Lattner | 8213c8a | 2012-02-06 21:56:39 +0000 | [diff] [blame] | 692 | if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) |
| 693 | if (C->getType()->getElementType()->isFloatingPointTy()) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 694 | return ConstantExpr::getFNeg(C); |
Dan Gohman | a5b9645 | 2009-06-04 22:49:04 +0000 | [diff] [blame] | 695 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 696 | return nullptr; |
Dan Gohman | a5b9645 | 2009-06-04 22:49:04 +0000 | [diff] [blame] | 697 | } |
| 698 | |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 699 | static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO, |
Chris Lattner | 183b336 | 2004-04-09 19:05:30 +0000 | [diff] [blame] | 700 | InstCombiner *IC) { |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 701 | if (CastInst *CI = dyn_cast<CastInst>(&I)) { |
Chris Lattner | c856539 | 2009-08-30 20:01:10 +0000 | [diff] [blame] | 702 | return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType()); |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 703 | } |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 704 | |
Chris Lattner | 183b336 | 2004-04-09 19:05:30 +0000 | [diff] [blame] | 705 | // Figure out if the constant is the left or the right argument. |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 706 | bool ConstIsRHS = isa<Constant>(I.getOperand(1)); |
| 707 | Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); |
Chris Lattner | b8b9750 | 2003-08-13 19:01:45 +0000 | [diff] [blame] | 708 | |
Chris Lattner | 183b336 | 2004-04-09 19:05:30 +0000 | [diff] [blame] | 709 | if (Constant *SOC = dyn_cast<Constant>(SO)) { |
| 710 | if (ConstIsRHS) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 711 | return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); |
| 712 | return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); |
Chris Lattner | 183b336 | 2004-04-09 19:05:30 +0000 | [diff] [blame] | 713 | } |
| 714 | |
| 715 | Value *Op0 = SO, *Op1 = ConstOperand; |
| 716 | if (!ConstIsRHS) |
| 717 | std::swap(Op0, Op1); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 718 | |
Owen Anderson | 1664dc8 | 2014-01-20 07:44:53 +0000 | [diff] [blame] | 719 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) { |
| 720 | Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1, |
Chris Lattner | 022a582 | 2009-08-30 07:44:24 +0000 | [diff] [blame] | 721 | SO->getName()+".op"); |
Owen Anderson | 1664dc8 | 2014-01-20 07:44:53 +0000 | [diff] [blame] | 722 | Instruction *FPInst = dyn_cast<Instruction>(RI); |
| 723 | if (FPInst && isa<FPMathOperator>(FPInst)) |
| 724 | FPInst->copyFastMathFlags(BO); |
| 725 | return RI; |
| 726 | } |
Chris Lattner | 022a582 | 2009-08-30 07:44:24 +0000 | [diff] [blame] | 727 | if (ICmpInst *CI = dyn_cast<ICmpInst>(&I)) |
| 728 | return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, |
| 729 | SO->getName()+".cmp"); |
| 730 | if (FCmpInst *CI = dyn_cast<FCmpInst>(&I)) |
| 731 | return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, |
| 732 | SO->getName()+".cmp"); |
| 733 | llvm_unreachable("Unknown binary instruction type!"); |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 734 | } |
| 735 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 736 | /// Given an instruction with a select as one operand and a constant as the |
| 737 | /// other operand, try to fold the binary operator into the select arguments. |
| 738 | /// This also works for Cast instructions, which obviously do not have a second |
| 739 | /// operand. |
Chris Lattner | 2b295a0 | 2010-01-04 07:53:58 +0000 | [diff] [blame] | 740 | Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) { |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 741 | // Don't modify shared select instructions |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 742 | if (!SI->hasOneUse()) return nullptr; |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 743 | Value *TV = SI->getOperand(1); |
| 744 | Value *FV = SI->getOperand(2); |
| 745 | |
| 746 | if (isa<Constant>(TV) || isa<Constant>(FV)) { |
Chris Lattner | 374e659 | 2005-04-21 05:43:13 +0000 | [diff] [blame] | 747 | // Bool selects with constant operands can be folded to logical ops. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 748 | if (SI->getType()->isIntegerTy(1)) return nullptr; |
Chris Lattner | 374e659 | 2005-04-21 05:43:13 +0000 | [diff] [blame] | 749 | |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 750 | // If it's a bitcast involving vectors, make sure it has the same number of |
| 751 | // elements on both sides. |
| 752 | if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 753 | VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); |
| 754 | VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 755 | |
| 756 | // Verify that either both or neither are vectors. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 757 | if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr; |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 758 | // If vectors, verify that they have the same number of elements. |
| 759 | if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 760 | return nullptr; |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 761 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 762 | |
James Molloy | 2b21a7c | 2015-05-20 18:41:25 +0000 | [diff] [blame] | 763 | // Test if a CmpInst instruction is used exclusively by a select as |
| 764 | // part of a minimum or maximum operation. If so, refrain from doing |
| 765 | // any other folding. This helps out other analyses which understand |
| 766 | // non-obfuscated minimum and maximum idioms, such as ScalarEvolution |
| 767 | // and CodeGen. And in this case, at least one of the comparison |
| 768 | // operands has at least one user besides the compare (the select), |
| 769 | // which would often largely negate the benefit of folding anyway. |
| 770 | if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) { |
| 771 | if (CI->hasOneUse()) { |
| 772 | Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); |
| 773 | if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || |
| 774 | (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) |
| 775 | return nullptr; |
| 776 | } |
| 777 | } |
| 778 | |
Chris Lattner | 2b295a0 | 2010-01-04 07:53:58 +0000 | [diff] [blame] | 779 | Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this); |
| 780 | Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this); |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 781 | |
Nick Lewycky | 6a083cf | 2011-01-21 02:30:43 +0000 | [diff] [blame] | 782 | return SelectInst::Create(SI->getCondition(), |
| 783 | SelectTrueVal, SelectFalseVal); |
Chris Lattner | 86102b8 | 2005-01-01 16:22:27 +0000 | [diff] [blame] | 784 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 785 | return nullptr; |
Chris Lattner | 183b336 | 2004-04-09 19:05:30 +0000 | [diff] [blame] | 786 | } |
| 787 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 788 | /// Given a binary operator, cast instruction, or select which has a PHI node as |
| 789 | /// operand #0, see if we can fold the instruction into the PHI (which is only |
| 790 | /// possible if all operands to the PHI are constants). |
Chris Lattner | ea7131a | 2011-01-16 05:14:26 +0000 | [diff] [blame] | 791 | Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) { |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 792 | PHINode *PN = cast<PHINode>(I.getOperand(0)); |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 793 | unsigned NumPHIValues = PN->getNumIncomingValues(); |
Chris Lattner | 25ce280 | 2011-01-16 04:37:29 +0000 | [diff] [blame] | 794 | if (NumPHIValues == 0) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 795 | return nullptr; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 796 | |
Chris Lattner | f4ca47b | 2011-01-21 05:08:26 +0000 | [diff] [blame] | 797 | // We normally only transform phis with a single use. However, if a PHI has |
| 798 | // multiple uses and they are all the same operation, we can fold *all* of the |
| 799 | // uses into the PHI. |
Chris Lattner | d55581d | 2011-01-16 05:28:59 +0000 | [diff] [blame] | 800 | if (!PN->hasOneUse()) { |
| 801 | // Walk the use list for the instruction, comparing them to I. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 802 | for (User *U : PN->users()) { |
| 803 | Instruction *UI = cast<Instruction>(U); |
| 804 | if (UI != &I && !I.isIdenticalTo(UI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 805 | return nullptr; |
Chris Lattner | b5e15d1 | 2011-01-21 05:29:50 +0000 | [diff] [blame] | 806 | } |
Chris Lattner | d55581d | 2011-01-16 05:28:59 +0000 | [diff] [blame] | 807 | // Otherwise, we can replace *all* users with the new PHI we form. |
| 808 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 809 | |
Chris Lattner | facb867 | 2009-09-27 19:57:57 +0000 | [diff] [blame] | 810 | // Check to see if all of the operands of the PHI are simple constants |
| 811 | // (constantint/constantfp/undef). If there is one non-constant value, |
Chris Lattner | ae28963 | 2009-09-27 20:18:49 +0000 | [diff] [blame] | 812 | // remember the BB it is in. If there is more than one or if *it* is a PHI, |
| 813 | // bail out. We don't do arbitrary constant expressions here because moving |
| 814 | // their computation can be expensive without a cost model. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 815 | BasicBlock *NonConstBB = nullptr; |
Chris Lattner | 25ce280 | 2011-01-16 04:37:29 +0000 | [diff] [blame] | 816 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
| 817 | Value *InVal = PN->getIncomingValue(i); |
| 818 | if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal)) |
| 819 | continue; |
| 820 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 821 | if (isa<PHINode>(InVal)) return nullptr; // Itself a phi. |
| 822 | if (NonConstBB) return nullptr; // More than one non-const value. |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 823 | |
Chris Lattner | 25ce280 | 2011-01-16 04:37:29 +0000 | [diff] [blame] | 824 | NonConstBB = PN->getIncomingBlock(i); |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 825 | |
| 826 | // If the InVal is an invoke at the end of the pred block, then we can't |
| 827 | // insert a computation after it without breaking the edge. |
| 828 | if (InvokeInst *II = dyn_cast<InvokeInst>(InVal)) |
| 829 | if (II->getParent() == NonConstBB) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 830 | return nullptr; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 831 | |
Chris Lattner | b5e15d1 | 2011-01-21 05:29:50 +0000 | [diff] [blame] | 832 | // If the incoming non-constant value is in I's block, we will remove one |
| 833 | // instruction, but insert another equivalent one, leading to infinite |
| 834 | // instcombine. |
Chandler Carruth | 5175b9a | 2015-01-20 08:35:24 +0000 | [diff] [blame] | 835 | if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 836 | return nullptr; |
Chris Lattner | 25ce280 | 2011-01-16 04:37:29 +0000 | [diff] [blame] | 837 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 838 | |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 839 | // If there is exactly one non-constant value, we can insert a copy of the |
| 840 | // operation in that block. However, if this is a critical edge, we would be |
David Majnemer | 7e2b988 | 2014-11-03 21:55:12 +0000 | [diff] [blame] | 841 | // inserting the computation on some other paths (e.g. inside a loop). Only |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 842 | // do this if the pred block is unconditionally branching into the phi block. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 843 | if (NonConstBB != nullptr) { |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 844 | BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 845 | if (!BI || !BI->isUnconditional()) return nullptr; |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 846 | } |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 847 | |
| 848 | // Okay, we can do the transformation: create the new PHI node. |
Eli Friedman | 41e509a | 2011-05-18 23:58:37 +0000 | [diff] [blame] | 849 | PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); |
Chris Lattner | 966526c | 2009-10-21 23:41:58 +0000 | [diff] [blame] | 850 | InsertNewInstBefore(NewPN, *PN); |
| 851 | NewPN->takeName(PN); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 852 | |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 853 | // If we are going to have to insert a new computation, do so right before the |
Sanjay Patel | 41c739b | 2015-09-11 19:29:18 +0000 | [diff] [blame] | 854 | // predecessor's terminator. |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 855 | if (NonConstBB) |
| 856 | Builder->SetInsertPoint(NonConstBB->getTerminator()); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 857 | |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 858 | // Next, add all of the operands to the PHI. |
Chris Lattner | facb867 | 2009-09-27 19:57:57 +0000 | [diff] [blame] | 859 | if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { |
| 860 | // We only currently try to fold the condition of a select when it is a phi, |
| 861 | // not the true/false values. |
Chris Lattner | ae28963 | 2009-09-27 20:18:49 +0000 | [diff] [blame] | 862 | Value *TrueV = SI->getTrueValue(); |
| 863 | Value *FalseV = SI->getFalseValue(); |
Chris Lattner | 0261b5d | 2009-09-28 06:49:44 +0000 | [diff] [blame] | 864 | BasicBlock *PhiTransBB = PN->getParent(); |
Chris Lattner | facb867 | 2009-09-27 19:57:57 +0000 | [diff] [blame] | 865 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
Chris Lattner | ae28963 | 2009-09-27 20:18:49 +0000 | [diff] [blame] | 866 | BasicBlock *ThisBB = PN->getIncomingBlock(i); |
Chris Lattner | 0261b5d | 2009-09-28 06:49:44 +0000 | [diff] [blame] | 867 | Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); |
| 868 | Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 869 | Value *InV = nullptr; |
Duncan P. N. Exon Smith | ce5f93e | 2013-12-06 21:48:36 +0000 | [diff] [blame] | 870 | // Beware of ConstantExpr: it may eventually evaluate to getNullValue, |
| 871 | // even if currently isNullValue gives false. |
| 872 | Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 873 | if (InC && !isa<ConstantExpr>(InC)) |
Chris Lattner | ae28963 | 2009-09-27 20:18:49 +0000 | [diff] [blame] | 874 | InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 875 | else |
| 876 | InV = Builder->CreateSelect(PN->getIncomingValue(i), |
| 877 | TrueVInPred, FalseVInPred, "phitmp"); |
Chris Lattner | ae28963 | 2009-09-27 20:18:49 +0000 | [diff] [blame] | 878 | NewPN->addIncoming(InV, ThisBB); |
Chris Lattner | facb867 | 2009-09-27 19:57:57 +0000 | [diff] [blame] | 879 | } |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 880 | } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { |
| 881 | Constant *C = cast<Constant>(I.getOperand(1)); |
| 882 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 883 | Value *InV = nullptr; |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 884 | if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) |
| 885 | InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); |
| 886 | else if (isa<ICmpInst>(CI)) |
| 887 | InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i), |
| 888 | C, "phitmp"); |
| 889 | else |
| 890 | InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i), |
| 891 | C, "phitmp"); |
| 892 | NewPN->addIncoming(InV, PN->getIncomingBlock(i)); |
| 893 | } |
Chris Lattner | facb867 | 2009-09-27 19:57:57 +0000 | [diff] [blame] | 894 | } else if (I.getNumOperands() == 2) { |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 895 | Constant *C = cast<Constant>(I.getOperand(1)); |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 896 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 897 | Value *InV = nullptr; |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 898 | if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) |
| 899 | InV = ConstantExpr::get(I.getOpcode(), InC, C); |
| 900 | else |
| 901 | InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(), |
| 902 | PN->getIncomingValue(i), C, "phitmp"); |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 903 | NewPN->addIncoming(InV, PN->getIncomingBlock(i)); |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 904 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 905 | } else { |
Reid Spencer | 6c38f0b | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 906 | CastInst *CI = cast<CastInst>(&I); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 907 | Type *RetTy = CI->getType(); |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 908 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 909 | Value *InV; |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 910 | if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 911 | InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 912 | else |
Chris Lattner | ff2e737 | 2011-01-16 05:08:00 +0000 | [diff] [blame] | 913 | InV = Builder->CreateCast(CI->getOpcode(), |
| 914 | PN->getIncomingValue(i), I.getType(), "phitmp"); |
Chris Lattner | 0468987 | 2006-09-09 22:02:56 +0000 | [diff] [blame] | 915 | NewPN->addIncoming(InV, PN->getIncomingBlock(i)); |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 916 | } |
| 917 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 918 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 919 | for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) { |
Chris Lattner | d55581d | 2011-01-16 05:28:59 +0000 | [diff] [blame] | 920 | Instruction *User = cast<Instruction>(*UI++); |
| 921 | if (User == &I) continue; |
| 922 | ReplaceInstUsesWith(*User, NewPN); |
| 923 | EraseInstFromFunction(*User); |
| 924 | } |
Chris Lattner | 6a4adcd | 2004-09-29 05:07:12 +0000 | [diff] [blame] | 925 | return ReplaceInstUsesWith(I, NewPN); |
| 926 | } |
| 927 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 928 | /// Given a pointer type and a constant offset, determine whether or not there |
| 929 | /// is a sequence of GEP indices into the pointed type that will land us at the |
| 930 | /// specified offset. If so, fill them into NewIndices and return the resultant |
| 931 | /// element type, otherwise return null. |
David Blaikie | 87ca1b6 | 2015-03-27 20:56:11 +0000 | [diff] [blame] | 932 | Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 933 | SmallVectorImpl<Value *> &NewIndices) { |
David Blaikie | 87ca1b6 | 2015-03-27 20:56:11 +0000 | [diff] [blame] | 934 | Type *Ty = PtrTy->getElementType(); |
Matt Arsenault | d79f7d9 | 2013-08-19 22:17:40 +0000 | [diff] [blame] | 935 | if (!Ty->isSized()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 936 | return nullptr; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 937 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 938 | // Start with the index over the outer type. Note that the type size |
| 939 | // might be zero (even if the offset isn't zero) if the indexed type |
| 940 | // is something like [0 x {int, int}] |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 941 | Type *IntPtrTy = DL.getIntPtrType(PtrTy); |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 942 | int64_t FirstIdx = 0; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 943 | if (int64_t TySize = DL.getTypeAllocSize(Ty)) { |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 944 | FirstIdx = Offset/TySize; |
Chris Lattner | bd3c7c8 | 2009-01-11 20:41:36 +0000 | [diff] [blame] | 945 | Offset -= FirstIdx*TySize; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 946 | |
Benjamin Kramer | e4c46fe | 2013-01-23 17:52:29 +0000 | [diff] [blame] | 947 | // Handle hosts where % returns negative instead of values [0..TySize). |
| 948 | if (Offset < 0) { |
| 949 | --FirstIdx; |
| 950 | Offset += TySize; |
| 951 | assert(Offset >= 0); |
| 952 | } |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 953 | assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); |
| 954 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 955 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 956 | NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx)); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 957 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 958 | // Index into the types. If we fail, set OrigBase to null. |
| 959 | while (Offset) { |
Chris Lattner | 171d2d4 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 960 | // Indexing into tail padding between struct/array elements. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 961 | if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 962 | return nullptr; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 963 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 964 | if (StructType *STy = dyn_cast<StructType>(Ty)) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 965 | const StructLayout *SL = DL.getStructLayout(STy); |
Chris Lattner | 171d2d4 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 966 | assert(Offset < (int64_t)SL->getSizeInBytes() && |
| 967 | "Offset must stay within the indexed type"); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 968 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 969 | unsigned Elt = SL->getElementContainingOffset(Offset); |
Chris Lattner | b8906bd | 2010-01-04 07:02:48 +0000 | [diff] [blame] | 970 | NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), |
| 971 | Elt)); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 972 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 973 | Offset -= SL->getElementOffset(Elt); |
| 974 | Ty = STy->getElementType(Elt); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 975 | } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 976 | uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType()); |
Chris Lattner | 171d2d4 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 977 | assert(EltSize && "Cannot index into a zero-sized array"); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 978 | NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize)); |
Chris Lattner | 171d2d4 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 979 | Offset %= EltSize; |
Chris Lattner | b191516 | 2009-01-11 20:23:52 +0000 | [diff] [blame] | 980 | Ty = AT->getElementType(); |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 981 | } else { |
Chris Lattner | 171d2d4 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 982 | // Otherwise, we can't index into the middle of this atomic type, bail. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 983 | return nullptr; |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 984 | } |
| 985 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 986 | |
Chris Lattner | 72cd68f | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 987 | return Ty; |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 988 | } |
| 989 | |
Rafael Espindola | a3a44f3f | 2011-07-31 04:43:41 +0000 | [diff] [blame] | 990 | static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { |
| 991 | // If this GEP has only 0 indices, it is the same pointer as |
| 992 | // Src. If Src is not a trivial GEP too, don't combine |
| 993 | // the indices. |
| 994 | if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && |
| 995 | !Src.hasOneUse()) |
| 996 | return false; |
| 997 | return true; |
| 998 | } |
Chris Lattner | bbbdd85 | 2002-05-06 18:06:38 +0000 | [diff] [blame] | 999 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 1000 | /// Return a value X such that Val = X * Scale, or null if none. |
| 1001 | /// If the multiplication is known not to overflow, then NoSignedWrap is set. |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1002 | Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) { |
| 1003 | assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!"); |
| 1004 | assert(cast<IntegerType>(Val->getType())->getBitWidth() == |
| 1005 | Scale.getBitWidth() && "Scale not compatible with value!"); |
| 1006 | |
| 1007 | // If Val is zero or Scale is one then Val = Val * Scale. |
| 1008 | if (match(Val, m_Zero()) || Scale == 1) { |
| 1009 | NoSignedWrap = true; |
| 1010 | return Val; |
| 1011 | } |
| 1012 | |
| 1013 | // If Scale is zero then it does not divide Val. |
| 1014 | if (Scale.isMinValue()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1015 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1016 | |
| 1017 | // Look through chains of multiplications, searching for a constant that is |
| 1018 | // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4 |
| 1019 | // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by |
| 1020 | // a factor of 4 will produce X*(Y*2). The principle of operation is to bore |
| 1021 | // down from Val: |
| 1022 | // |
| 1023 | // Val = M1 * X || Analysis starts here and works down |
| 1024 | // M1 = M2 * Y || Doesn't descend into terms with more |
| 1025 | // M2 = Z * 4 \/ than one use |
| 1026 | // |
| 1027 | // Then to modify a term at the bottom: |
| 1028 | // |
| 1029 | // Val = M1 * X |
| 1030 | // M1 = Z * Y || Replaced M2 with Z |
| 1031 | // |
| 1032 | // Then to work back up correcting nsw flags. |
| 1033 | |
| 1034 | // Op - the term we are currently analyzing. Starts at Val then drills down. |
| 1035 | // Replaced with its descaled value before exiting from the drill down loop. |
| 1036 | Value *Op = Val; |
| 1037 | |
| 1038 | // Parent - initially null, but after drilling down notes where Op came from. |
| 1039 | // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the |
| 1040 | // 0'th operand of Val. |
| 1041 | std::pair<Instruction*, unsigned> Parent; |
| 1042 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 1043 | // Set if the transform requires a descaling at deeper levels that doesn't |
| 1044 | // overflow. |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1045 | bool RequireNoSignedWrap = false; |
| 1046 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 1047 | // Log base 2 of the scale. Negative if not a power of 2. |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1048 | int32_t logScale = Scale.exactLogBase2(); |
| 1049 | |
| 1050 | for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down |
| 1051 | |
| 1052 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { |
| 1053 | // If Op is a constant divisible by Scale then descale to the quotient. |
| 1054 | APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth. |
| 1055 | APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder); |
| 1056 | if (!Remainder.isMinValue()) |
| 1057 | // Not divisible by Scale. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1058 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1059 | // Replace with the quotient in the parent. |
| 1060 | Op = ConstantInt::get(CI->getType(), Quotient); |
| 1061 | NoSignedWrap = true; |
| 1062 | break; |
| 1063 | } |
| 1064 | |
| 1065 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) { |
| 1066 | |
| 1067 | if (BO->getOpcode() == Instruction::Mul) { |
| 1068 | // Multiplication. |
| 1069 | NoSignedWrap = BO->hasNoSignedWrap(); |
| 1070 | if (RequireNoSignedWrap && !NoSignedWrap) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1071 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1072 | |
| 1073 | // There are three cases for multiplication: multiplication by exactly |
| 1074 | // the scale, multiplication by a constant different to the scale, and |
| 1075 | // multiplication by something else. |
| 1076 | Value *LHS = BO->getOperand(0); |
| 1077 | Value *RHS = BO->getOperand(1); |
| 1078 | |
| 1079 | if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { |
| 1080 | // Multiplication by a constant. |
| 1081 | if (CI->getValue() == Scale) { |
| 1082 | // Multiplication by exactly the scale, replace the multiplication |
| 1083 | // by its left-hand side in the parent. |
| 1084 | Op = LHS; |
| 1085 | break; |
| 1086 | } |
| 1087 | |
| 1088 | // Otherwise drill down into the constant. |
| 1089 | if (!Op->hasOneUse()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1090 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1091 | |
| 1092 | Parent = std::make_pair(BO, 1); |
| 1093 | continue; |
| 1094 | } |
| 1095 | |
| 1096 | // Multiplication by something else. Drill down into the left-hand side |
| 1097 | // since that's where the reassociate pass puts the good stuff. |
| 1098 | if (!Op->hasOneUse()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1099 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1100 | |
| 1101 | Parent = std::make_pair(BO, 0); |
| 1102 | continue; |
| 1103 | } |
| 1104 | |
| 1105 | if (logScale > 0 && BO->getOpcode() == Instruction::Shl && |
| 1106 | isa<ConstantInt>(BO->getOperand(1))) { |
| 1107 | // Multiplication by a power of 2. |
| 1108 | NoSignedWrap = BO->hasNoSignedWrap(); |
| 1109 | if (RequireNoSignedWrap && !NoSignedWrap) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1110 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1111 | |
| 1112 | Value *LHS = BO->getOperand(0); |
| 1113 | int32_t Amt = cast<ConstantInt>(BO->getOperand(1))-> |
| 1114 | getLimitedValue(Scale.getBitWidth()); |
| 1115 | // Op = LHS << Amt. |
| 1116 | |
| 1117 | if (Amt == logScale) { |
| 1118 | // Multiplication by exactly the scale, replace the multiplication |
| 1119 | // by its left-hand side in the parent. |
| 1120 | Op = LHS; |
| 1121 | break; |
| 1122 | } |
| 1123 | if (Amt < logScale || !Op->hasOneUse()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1124 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1125 | |
| 1126 | // Multiplication by more than the scale. Reduce the multiplying amount |
| 1127 | // by the scale in the parent. |
| 1128 | Parent = std::make_pair(BO, 1); |
| 1129 | Op = ConstantInt::get(BO->getType(), Amt - logScale); |
| 1130 | break; |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | if (!Op->hasOneUse()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1135 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1136 | |
| 1137 | if (CastInst *Cast = dyn_cast<CastInst>(Op)) { |
| 1138 | if (Cast->getOpcode() == Instruction::SExt) { |
| 1139 | // Op is sign-extended from a smaller type, descale in the smaller type. |
| 1140 | unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); |
| 1141 | APInt SmallScale = Scale.trunc(SmallSize); |
| 1142 | // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to |
| 1143 | // descale Op as (sext Y) * Scale. In order to have |
| 1144 | // sext (Y * SmallScale) = (sext Y) * Scale |
| 1145 | // some conditions need to hold however: SmallScale must sign-extend to |
| 1146 | // Scale and the multiplication Y * SmallScale should not overflow. |
| 1147 | if (SmallScale.sext(Scale.getBitWidth()) != Scale) |
| 1148 | // SmallScale does not sign-extend to Scale. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1149 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1150 | assert(SmallScale.exactLogBase2() == logScale); |
| 1151 | // Require that Y * SmallScale must not overflow. |
| 1152 | RequireNoSignedWrap = true; |
| 1153 | |
| 1154 | // Drill down through the cast. |
| 1155 | Parent = std::make_pair(Cast, 0); |
| 1156 | Scale = SmallScale; |
| 1157 | continue; |
| 1158 | } |
| 1159 | |
Duncan Sands | 5ed3900 | 2012-10-23 09:07:02 +0000 | [diff] [blame] | 1160 | if (Cast->getOpcode() == Instruction::Trunc) { |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1161 | // Op is truncated from a larger type, descale in the larger type. |
| 1162 | // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then |
| 1163 | // trunc (Y * sext Scale) = (trunc Y) * Scale |
| 1164 | // always holds. However (trunc Y) * Scale may overflow even if |
| 1165 | // trunc (Y * sext Scale) does not, so nsw flags need to be cleared |
| 1166 | // from this point up in the expression (see later). |
| 1167 | if (RequireNoSignedWrap) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1168 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1169 | |
| 1170 | // Drill down through the cast. |
| 1171 | unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); |
| 1172 | Parent = std::make_pair(Cast, 0); |
| 1173 | Scale = Scale.sext(LargeSize); |
| 1174 | if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits()) |
| 1175 | logScale = -1; |
| 1176 | assert(Scale.exactLogBase2() == logScale); |
| 1177 | continue; |
| 1178 | } |
| 1179 | } |
| 1180 | |
| 1181 | // Unsupported expression, bail out. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1182 | return nullptr; |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1183 | } |
| 1184 | |
Duncan P. N. Exon Smith | 04934b0 | 2014-07-10 17:13:27 +0000 | [diff] [blame] | 1185 | // If Op is zero then Val = Op * Scale. |
| 1186 | if (match(Op, m_Zero())) { |
| 1187 | NoSignedWrap = true; |
| 1188 | return Op; |
| 1189 | } |
| 1190 | |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1191 | // We know that we can successfully descale, so from here on we can safely |
| 1192 | // modify the IR. Op holds the descaled version of the deepest term in the |
| 1193 | // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known |
| 1194 | // not to overflow. |
| 1195 | |
| 1196 | if (!Parent.first) |
| 1197 | // The expression only had one term. |
| 1198 | return Op; |
| 1199 | |
| 1200 | // Rewrite the parent using the descaled version of its operand. |
| 1201 | assert(Parent.first->hasOneUse() && "Drilled down when more than one use!"); |
| 1202 | assert(Op != Parent.first->getOperand(Parent.second) && |
| 1203 | "Descaling was a no-op?"); |
| 1204 | Parent.first->setOperand(Parent.second, Op); |
| 1205 | Worklist.Add(Parent.first); |
| 1206 | |
| 1207 | // Now work back up the expression correcting nsw flags. The logic is based |
| 1208 | // on the following observation: if X * Y is known not to overflow as a signed |
| 1209 | // multiplication, and Y is replaced by a value Z with smaller absolute value, |
| 1210 | // then X * Z will not overflow as a signed multiplication either. As we work |
| 1211 | // our way up, having NoSignedWrap 'true' means that the descaled value at the |
| 1212 | // current level has strictly smaller absolute value than the original. |
| 1213 | Instruction *Ancestor = Parent.first; |
| 1214 | do { |
| 1215 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) { |
| 1216 | // If the multiplication wasn't nsw then we can't say anything about the |
| 1217 | // value of the descaled multiplication, and we have to clear nsw flags |
| 1218 | // from this point on up. |
| 1219 | bool OpNoSignedWrap = BO->hasNoSignedWrap(); |
| 1220 | NoSignedWrap &= OpNoSignedWrap; |
| 1221 | if (NoSignedWrap != OpNoSignedWrap) { |
| 1222 | BO->setHasNoSignedWrap(NoSignedWrap); |
| 1223 | Worklist.Add(Ancestor); |
| 1224 | } |
| 1225 | } else if (Ancestor->getOpcode() == Instruction::Trunc) { |
| 1226 | // The fact that the descaled input to the trunc has smaller absolute |
| 1227 | // value than the original input doesn't tell us anything useful about |
| 1228 | // the absolute values of the truncations. |
| 1229 | NoSignedWrap = false; |
| 1230 | } |
| 1231 | assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && |
| 1232 | "Failed to keep proper track of nsw flags while drilling down?"); |
| 1233 | |
| 1234 | if (Ancestor == Val) |
| 1235 | // Got to the top, all done! |
| 1236 | return Val; |
| 1237 | |
| 1238 | // Move up one level in the expression. |
| 1239 | assert(Ancestor->hasOneUse() && "Drilled down when more than one use!"); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1240 | Ancestor = Ancestor->user_back(); |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1241 | } while (1); |
| 1242 | } |
| 1243 | |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1244 | /// \brief Creates node of binary operation with the same attributes as the |
| 1245 | /// specified one but with other operands. |
Serge Pavlov | e6de9e3 | 2014-05-14 09:05:09 +0000 | [diff] [blame] | 1246 | static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS, |
| 1247 | InstCombiner::BuilderTy *B) { |
| 1248 | Value *BORes = B->CreateBinOp(Inst.getOpcode(), LHS, RHS); |
| 1249 | if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BORes)) { |
| 1250 | if (isa<OverflowingBinaryOperator>(NewBO)) { |
| 1251 | NewBO->setHasNoSignedWrap(Inst.hasNoSignedWrap()); |
| 1252 | NewBO->setHasNoUnsignedWrap(Inst.hasNoUnsignedWrap()); |
| 1253 | } |
| 1254 | if (isa<PossiblyExactOperator>(NewBO)) |
| 1255 | NewBO->setIsExact(Inst.isExact()); |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1256 | } |
Serge Pavlov | e6de9e3 | 2014-05-14 09:05:09 +0000 | [diff] [blame] | 1257 | return BORes; |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1258 | } |
| 1259 | |
| 1260 | /// \brief Makes transformation of binary operation specific for vector types. |
| 1261 | /// \param Inst Binary operator to transform. |
| 1262 | /// \return Pointer to node that must replace the original binary operator, or |
| 1263 | /// null pointer if no transformation was made. |
| 1264 | Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) { |
| 1265 | if (!Inst.getType()->isVectorTy()) return nullptr; |
| 1266 | |
Sanjay Patel | 5881444 | 2014-07-09 16:34:54 +0000 | [diff] [blame] | 1267 | // It may not be safe to reorder shuffles and things like div, urem, etc. |
| 1268 | // because we may trap when executing those ops on unknown vector elements. |
| 1269 | // See PR20059. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1270 | if (!isSafeToSpeculativelyExecute(&Inst)) |
| 1271 | return nullptr; |
Sanjay Patel | 5881444 | 2014-07-09 16:34:54 +0000 | [diff] [blame] | 1272 | |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1273 | unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements(); |
| 1274 | Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); |
| 1275 | assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth); |
| 1276 | assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth); |
| 1277 | |
| 1278 | // If both arguments of binary operation are shuffles, which use the same |
| 1279 | // mask and shuffle within a single vector, it is worthwhile to move the |
| 1280 | // shuffle after binary operation: |
| 1281 | // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m) |
| 1282 | if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) { |
| 1283 | ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS); |
| 1284 | ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS); |
| 1285 | if (isa<UndefValue>(LShuf->getOperand(1)) && |
| 1286 | isa<UndefValue>(RShuf->getOperand(1)) && |
Serge Pavlov | 0581109 | 2014-05-12 05:44:53 +0000 | [diff] [blame] | 1287 | LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() && |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1288 | LShuf->getMask() == RShuf->getMask()) { |
Serge Pavlov | e6de9e3 | 2014-05-14 09:05:09 +0000 | [diff] [blame] | 1289 | Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0), |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1290 | RShuf->getOperand(0), Builder); |
| 1291 | Value *Res = Builder->CreateShuffleVector(NewBO, |
Serge Pavlov | 02ff620 | 2014-05-12 10:11:27 +0000 | [diff] [blame] | 1292 | UndefValue::get(NewBO->getType()), LShuf->getMask()); |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1293 | return Res; |
| 1294 | } |
| 1295 | } |
| 1296 | |
| 1297 | // If one argument is a shuffle within one vector, the other is a constant, |
| 1298 | // try moving the shuffle after the binary operation. |
| 1299 | ShuffleVectorInst *Shuffle = nullptr; |
| 1300 | Constant *C1 = nullptr; |
| 1301 | if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS); |
| 1302 | if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS); |
| 1303 | if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS); |
| 1304 | if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS); |
Benjamin Kramer | 6de7866 | 2014-06-24 10:38:10 +0000 | [diff] [blame] | 1305 | if (Shuffle && C1 && |
| 1306 | (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) && |
| 1307 | isa<UndefValue>(Shuffle->getOperand(1)) && |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1308 | Shuffle->getType() == Shuffle->getOperand(0)->getType()) { |
| 1309 | SmallVector<int, 16> ShMask = Shuffle->getShuffleMask(); |
| 1310 | // Find constant C2 that has property: |
| 1311 | // shuffle(C2, ShMask) = C1 |
| 1312 | // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>) |
| 1313 | // reorder is not possible. |
| 1314 | SmallVector<Constant*, 16> C2M(VWidth, |
| 1315 | UndefValue::get(C1->getType()->getScalarType())); |
| 1316 | bool MayChange = true; |
| 1317 | for (unsigned I = 0; I < VWidth; ++I) { |
| 1318 | if (ShMask[I] >= 0) { |
| 1319 | assert(ShMask[I] < (int)VWidth); |
| 1320 | if (!isa<UndefValue>(C2M[ShMask[I]])) { |
| 1321 | MayChange = false; |
| 1322 | break; |
| 1323 | } |
| 1324 | C2M[ShMask[I]] = C1->getAggregateElement(I); |
| 1325 | } |
| 1326 | } |
| 1327 | if (MayChange) { |
| 1328 | Constant *C2 = ConstantVector::get(C2M); |
| 1329 | Value *NewLHS, *NewRHS; |
| 1330 | if (isa<Constant>(LHS)) { |
| 1331 | NewLHS = C2; |
| 1332 | NewRHS = Shuffle->getOperand(0); |
| 1333 | } else { |
| 1334 | NewLHS = Shuffle->getOperand(0); |
| 1335 | NewRHS = C2; |
| 1336 | } |
Serge Pavlov | e6de9e3 | 2014-05-14 09:05:09 +0000 | [diff] [blame] | 1337 | Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder); |
Serge Pavlov | 9ef66a8 | 2014-05-11 08:46:12 +0000 | [diff] [blame] | 1338 | Value *Res = Builder->CreateShuffleVector(NewBO, |
| 1339 | UndefValue::get(Inst.getType()), Shuffle->getMask()); |
| 1340 | return Res; |
| 1341 | } |
| 1342 | } |
| 1343 | |
| 1344 | return nullptr; |
| 1345 | } |
| 1346 | |
Chris Lattner | 113f4f4 | 2002-06-25 16:13:24 +0000 | [diff] [blame] | 1347 | Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { |
Chris Lattner | 8574aba | 2009-11-27 00:29:05 +0000 | [diff] [blame] | 1348 | SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); |
| 1349 | |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 1350 | if (Value *V = SimplifyGEPInst(Ops, DL, TLI, DT, AC)) |
Chris Lattner | 8574aba | 2009-11-27 00:29:05 +0000 | [diff] [blame] | 1351 | return ReplaceInstUsesWith(GEP, V); |
| 1352 | |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1353 | Value *PtrOp = GEP.getOperand(0); |
Chris Lattner | 8d0bacb | 2004-02-22 05:25:17 +0000 | [diff] [blame] | 1354 | |
Duncan Sands | c133c54 | 2010-11-22 16:32:50 +0000 | [diff] [blame] | 1355 | // Eliminate unneeded casts for indices, and replace indices which displace |
| 1356 | // by multiples of a zero size type with zero. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1357 | bool MadeChange = false; |
Elena Demikhovsky | 121d49b | 2015-11-15 08:19:35 +0000 | [diff] [blame] | 1358 | Type *IntPtrTy = |
| 1359 | DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType()); |
Duncan Sands | c133c54 | 2010-11-22 16:32:50 +0000 | [diff] [blame] | 1360 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1361 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 1362 | for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; |
| 1363 | ++I, ++GTI) { |
| 1364 | // Skip indices into struct types. |
| 1365 | SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI); |
| 1366 | if (!SeqTy) |
| 1367 | continue; |
Duncan Sands | c133c54 | 2010-11-22 16:32:50 +0000 | [diff] [blame] | 1368 | |
Elena Demikhovsky | 121d49b | 2015-11-15 08:19:35 +0000 | [diff] [blame] | 1369 | // Index type should have the same width as IntPtr |
| 1370 | Type *IndexTy = (*I)->getType(); |
| 1371 | Type *NewIndexType = IndexTy->isVectorTy() ? |
| 1372 | VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy; |
| 1373 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1374 | // If the element type has zero size then any index over it is equivalent |
| 1375 | // to an index of zero, so replace it with zero if it is not zero already. |
| 1376 | if (SeqTy->getElementType()->isSized() && |
| 1377 | DL.getTypeAllocSize(SeqTy->getElementType()) == 0) |
| 1378 | if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) { |
Elena Demikhovsky | 121d49b | 2015-11-15 08:19:35 +0000 | [diff] [blame] | 1379 | *I = Constant::getNullValue(NewIndexType); |
Duncan Sands | c133c54 | 2010-11-22 16:32:50 +0000 | [diff] [blame] | 1380 | MadeChange = true; |
| 1381 | } |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1382 | |
Elena Demikhovsky | 121d49b | 2015-11-15 08:19:35 +0000 | [diff] [blame] | 1383 | if (IndexTy != NewIndexType) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1384 | // If we are using a wider index than needed for this platform, shrink |
| 1385 | // it to what we need. If narrower, sign-extend it to what we need. |
| 1386 | // This explicit cast can make subsequent optimizations more obvious. |
Elena Demikhovsky | 121d49b | 2015-11-15 08:19:35 +0000 | [diff] [blame] | 1387 | *I = Builder->CreateIntCast(*I, NewIndexType, true); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1388 | MadeChange = true; |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1389 | } |
Chris Lattner | 9bf53ff | 2007-03-25 20:43:09 +0000 | [diff] [blame] | 1390 | } |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1391 | if (MadeChange) |
| 1392 | return &GEP; |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1393 | |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1394 | // Check to see if the inputs to the PHI node are getelementptr instructions. |
| 1395 | if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) { |
| 1396 | GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); |
| 1397 | if (!Op1) |
| 1398 | return nullptr; |
| 1399 | |
Daniel Jasper | 5add63f | 2015-03-19 11:05:08 +0000 | [diff] [blame] | 1400 | // Don't fold a GEP into itself through a PHI node. This can only happen |
| 1401 | // through the back-edge of a loop. Folding a GEP into itself means that |
| 1402 | // the value of the previous iteration needs to be stored in the meantime, |
| 1403 | // thus requiring an additional register variable to be live, but not |
| 1404 | // actually achieving anything (the GEP still needs to be executed once per |
| 1405 | // loop iteration). |
| 1406 | if (Op1 == &GEP) |
| 1407 | return nullptr; |
| 1408 | |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1409 | signed DI = -1; |
| 1410 | |
| 1411 | for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { |
| 1412 | GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I); |
| 1413 | if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) |
| 1414 | return nullptr; |
| 1415 | |
Daniel Jasper | 5add63f | 2015-03-19 11:05:08 +0000 | [diff] [blame] | 1416 | // As for Op1 above, don't try to fold a GEP into itself. |
| 1417 | if (Op2 == &GEP) |
| 1418 | return nullptr; |
| 1419 | |
Chandler Carruth | 3012a1b | 2014-05-29 23:05:52 +0000 | [diff] [blame] | 1420 | // Keep track of the type as we walk the GEP. |
| 1421 | Type *CurTy = Op1->getOperand(0)->getType()->getScalarType(); |
| 1422 | |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1423 | for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { |
| 1424 | if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) |
| 1425 | return nullptr; |
| 1426 | |
| 1427 | if (Op1->getOperand(J) != Op2->getOperand(J)) { |
| 1428 | if (DI == -1) { |
| 1429 | // We have not seen any differences yet in the GEPs feeding the |
| 1430 | // PHI yet, so we record this one if it is allowed to be a |
| 1431 | // variable. |
| 1432 | |
| 1433 | // The first two arguments can vary for any GEP, the rest have to be |
| 1434 | // static for struct slots |
Chandler Carruth | 3012a1b | 2014-05-29 23:05:52 +0000 | [diff] [blame] | 1435 | if (J > 1 && CurTy->isStructTy()) |
| 1436 | return nullptr; |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1437 | |
| 1438 | DI = J; |
| 1439 | } else { |
| 1440 | // The GEP is different by more than one input. While this could be |
| 1441 | // extended to support GEPs that vary by more than one variable it |
| 1442 | // doesn't make sense since it greatly increases the complexity and |
| 1443 | // would result in an R+R+R addressing mode which no backend |
| 1444 | // directly supports and would need to be broken into several |
| 1445 | // simpler instructions anyway. |
| 1446 | return nullptr; |
| 1447 | } |
| 1448 | } |
Chandler Carruth | fdc0e0b | 2014-05-29 23:21:12 +0000 | [diff] [blame] | 1449 | |
| 1450 | // Sink down a layer of the type for the next iteration. |
| 1451 | if (J > 0) { |
| 1452 | if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) { |
| 1453 | CurTy = CT->getTypeAtIndex(Op1->getOperand(J)); |
| 1454 | } else { |
| 1455 | CurTy = nullptr; |
| 1456 | } |
| 1457 | } |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1458 | } |
| 1459 | } |
| 1460 | |
Silviu Baranga | b892e35 | 2015-10-26 10:25:05 +0000 | [diff] [blame] | 1461 | // If not all GEPs are identical we'll have to create a new PHI node. |
| 1462 | // Check that the old PHI node has only one use so that it will get |
| 1463 | // removed. |
| 1464 | if (DI != -1 && !PN->hasOneUse()) |
| 1465 | return nullptr; |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1466 | |
Silviu Baranga | b892e35 | 2015-10-26 10:25:05 +0000 | [diff] [blame] | 1467 | GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone()); |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1468 | if (DI == -1) { |
| 1469 | // All the GEPs feeding the PHI are identical. Clone one down into our |
| 1470 | // BB so that it can be merged with the current GEP. |
Akira Hatanaka | 1defd5a | 2015-02-18 03:30:11 +0000 | [diff] [blame] | 1471 | GEP.getParent()->getInstList().insert( |
| 1472 | GEP.getParent()->getFirstInsertionPt(), NewGEP); |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1473 | } else { |
| 1474 | // All the GEPs feeding the PHI differ at a single offset. Clone a GEP |
| 1475 | // into the current block so it can be merged, and create a new PHI to |
| 1476 | // set that index. |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 1477 | PHINode *NewPN; |
| 1478 | { |
| 1479 | IRBuilderBase::InsertPointGuard Guard(*Builder); |
| 1480 | Builder->SetInsertPoint(PN); |
| 1481 | NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(), |
| 1482 | PN->getNumOperands()); |
| 1483 | } |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1484 | |
| 1485 | for (auto &I : PN->operands()) |
| 1486 | NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), |
| 1487 | PN->getIncomingBlock(I)); |
| 1488 | |
| 1489 | NewGEP->setOperand(DI, NewPN); |
Akira Hatanaka | 1defd5a | 2015-02-18 03:30:11 +0000 | [diff] [blame] | 1490 | GEP.getParent()->getInstList().insert( |
| 1491 | GEP.getParent()->getFirstInsertionPt(), NewGEP); |
Louis Gerbarg | c6b506a | 2014-05-29 20:29:47 +0000 | [diff] [blame] | 1492 | NewGEP->setOperand(DI, NewPN); |
| 1493 | } |
| 1494 | |
| 1495 | GEP.setOperand(0, NewGEP); |
| 1496 | PtrOp = NewGEP; |
| 1497 | } |
| 1498 | |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 1499 | // Combine Indices - If the source pointer to this getelementptr instruction |
| 1500 | // is a getelementptr instruction, combine the indices of the two |
| 1501 | // getelementptr instructions into a single instruction. |
| 1502 | // |
Dan Gohman | 31a9b98 | 2009-07-28 01:40:03 +0000 | [diff] [blame] | 1503 | if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) { |
Rafael Espindola | a3a44f3f | 2011-07-31 04:43:41 +0000 | [diff] [blame] | 1504 | if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1505 | return nullptr; |
Rafael Espindola | 4032567 | 2011-07-11 03:43:47 +0000 | [diff] [blame] | 1506 | |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1507 | // Note that if our source is a gep chain itself then we wait for that |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1508 | // chain to be resolved before we perform this transformation. This |
| 1509 | // avoids us creating a TON of code in some cases. |
Rafael Espindola | a3a44f3f | 2011-07-31 04:43:41 +0000 | [diff] [blame] | 1510 | if (GEPOperator *SrcGEP = |
| 1511 | dyn_cast<GEPOperator>(Src->getOperand(0))) |
| 1512 | if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1513 | return nullptr; // Wait until our source is folded to completion. |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1514 | |
Chris Lattner | af6094f | 2007-02-15 22:48:32 +0000 | [diff] [blame] | 1515 | SmallVector<Value*, 8> Indices; |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1516 | |
| 1517 | // Find out whether the last index in the source GEP is a sequential idx. |
| 1518 | bool EndsWithSequential = false; |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1519 | for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); |
| 1520 | I != E; ++I) |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 1521 | EndsWithSequential = !(*I)->isStructTy(); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1522 | |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 1523 | // Can we combine the two pointer arithmetics offsets? |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1524 | if (EndsWithSequential) { |
Chris Lattner | 235af56 | 2003-03-05 22:33:14 +0000 | [diff] [blame] | 1525 | // Replace: gep (gep %P, long B), long A, ... |
| 1526 | // With: T = long A+B; gep %P, T, ... |
| 1527 | // |
Chris Lattner | 06c687b | 2009-08-30 05:08:50 +0000 | [diff] [blame] | 1528 | Value *Sum; |
| 1529 | Value *SO1 = Src->getOperand(Src->getNumOperands()-1); |
| 1530 | Value *GO1 = GEP.getOperand(1); |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 1531 | if (SO1 == Constant::getNullValue(SO1->getType())) { |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1532 | Sum = GO1; |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 1533 | } else if (GO1 == Constant::getNullValue(GO1->getType())) { |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1534 | Sum = SO1; |
| 1535 | } else { |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1536 | // If they aren't the same type, then the input hasn't been processed |
| 1537 | // by the loop above yet (which canonicalizes sequential index types to |
| 1538 | // intptr_t). Just avoid transforming this until the input has been |
| 1539 | // normalized. |
| 1540 | if (SO1->getType() != GO1->getType()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1541 | return nullptr; |
Wei Mi | a0adf9f | 2015-04-21 23:02:15 +0000 | [diff] [blame] | 1542 | // Only do the combine when GO1 and SO1 are both constants. Only in |
| 1543 | // this case, we are sure the cost after the merge is never more than |
| 1544 | // that before the merge. |
| 1545 | if (!isa<Constant>(GO1) || !isa<Constant>(SO1)) |
| 1546 | return nullptr; |
Chris Lattner | 5966341 | 2009-08-30 18:50:58 +0000 | [diff] [blame] | 1547 | Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum"); |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1548 | } |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1549 | |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1550 | // Update the GEP in place if possible. |
Chris Lattner | 06c687b | 2009-08-30 05:08:50 +0000 | [diff] [blame] | 1551 | if (Src->getNumOperands() == 2) { |
| 1552 | GEP.setOperand(0, Src->getOperand(0)); |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1553 | GEP.setOperand(1, Sum); |
| 1554 | return &GEP; |
Chris Lattner | 5f667a6 | 2004-05-07 22:09:22 +0000 | [diff] [blame] | 1555 | } |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1556 | Indices.append(Src->op_begin()+1, Src->op_end()-1); |
Chris Lattner | d7b6e91 | 2009-08-30 04:49:01 +0000 | [diff] [blame] | 1557 | Indices.push_back(Sum); |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1558 | Indices.append(GEP.op_begin()+2, GEP.op_end()); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1559 | } else if (isa<Constant>(*GEP.idx_begin()) && |
Chris Lattner | 69193f9 | 2004-04-05 01:30:19 +0000 | [diff] [blame] | 1560 | cast<Constant>(*GEP.idx_begin())->isNullValue() && |
Chris Lattner | 06c687b | 2009-08-30 05:08:50 +0000 | [diff] [blame] | 1561 | Src->getNumOperands() != 1) { |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 1562 | // Otherwise we can do the fold if the first index of the GEP is a zero |
Chris Lattner | b2995e1 | 2009-08-30 05:30:55 +0000 | [diff] [blame] | 1563 | Indices.append(Src->op_begin()+1, Src->op_end()); |
| 1564 | Indices.append(GEP.idx_begin()+1, GEP.idx_end()); |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 1565 | } |
| 1566 | |
Dan Gohman | 1b84908 | 2009-09-07 23:54:19 +0000 | [diff] [blame] | 1567 | if (!Indices.empty()) |
David Blaikie | 096b1da | 2015-03-14 19:53:33 +0000 | [diff] [blame] | 1568 | return GEP.isInBounds() && Src->isInBounds() |
| 1569 | ? GetElementPtrInst::CreateInBounds( |
| 1570 | Src->getSourceElementType(), Src->getOperand(0), Indices, |
| 1571 | GEP.getName()) |
| 1572 | : GetElementPtrInst::Create(Src->getSourceElementType(), |
| 1573 | Src->getOperand(0), Indices, |
| 1574 | GEP.getName()); |
Chris Lattner | e26bf17 | 2009-08-30 05:00:50 +0000 | [diff] [blame] | 1575 | } |
Nadav Rotem | a069c6c | 2011-04-05 14:29:52 +0000 | [diff] [blame] | 1576 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1577 | if (GEP.getNumIndices() == 1) { |
Matt Arsenault | bfa37e5 | 2013-10-03 18:15:57 +0000 | [diff] [blame] | 1578 | unsigned AS = GEP.getPointerAddressSpace(); |
David Majnemer | d2df501 | 2014-09-01 21:10:02 +0000 | [diff] [blame] | 1579 | if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1580 | DL.getPointerSizeInBits(AS)) { |
David Majnemer | d2df501 | 2014-09-01 21:10:02 +0000 | [diff] [blame] | 1581 | Type *PtrTy = GEP.getPointerOperandType(); |
| 1582 | Type *Ty = PtrTy->getPointerElementType(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1583 | uint64_t TyAllocSize = DL.getTypeAllocSize(Ty); |
David Majnemer | d2df501 | 2014-09-01 21:10:02 +0000 | [diff] [blame] | 1584 | |
| 1585 | bool Matched = false; |
| 1586 | uint64_t C; |
| 1587 | Value *V = nullptr; |
| 1588 | if (TyAllocSize == 1) { |
| 1589 | V = GEP.getOperand(1); |
| 1590 | Matched = true; |
| 1591 | } else if (match(GEP.getOperand(1), |
| 1592 | m_AShr(m_Value(V), m_ConstantInt(C)))) { |
| 1593 | if (TyAllocSize == 1ULL << C) |
| 1594 | Matched = true; |
| 1595 | } else if (match(GEP.getOperand(1), |
| 1596 | m_SDiv(m_Value(V), m_ConstantInt(C)))) { |
| 1597 | if (TyAllocSize == C) |
| 1598 | Matched = true; |
| 1599 | } |
| 1600 | |
| 1601 | if (Matched) { |
| 1602 | // Canonicalize (gep i8* X, -(ptrtoint Y)) |
| 1603 | // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) |
| 1604 | // The GEP pattern is emitted by the SCEV expander for certain kinds of |
| 1605 | // pointer arithmetic. |
| 1606 | if (match(V, m_Neg(m_PtrToInt(m_Value())))) { |
| 1607 | Operator *Index = cast<Operator>(V); |
| 1608 | Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType()); |
| 1609 | Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1)); |
| 1610 | return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType()); |
| 1611 | } |
| 1612 | // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) |
| 1613 | // to (bitcast Y) |
| 1614 | Value *Y; |
| 1615 | if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), |
| 1616 | m_PtrToInt(m_Specific(GEP.getOperand(0)))))) { |
| 1617 | return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, |
| 1618 | GEP.getType()); |
| 1619 | } |
| 1620 | } |
Matt Arsenault | bfa37e5 | 2013-10-03 18:15:57 +0000 | [diff] [blame] | 1621 | } |
Benjamin Kramer | e6461e3 | 2013-09-20 14:38:44 +0000 | [diff] [blame] | 1622 | } |
| 1623 | |
Chris Lattner | 06c687b | 2009-08-30 05:08:50 +0000 | [diff] [blame] | 1624 | // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). |
Chris Lattner | e903f38 | 2010-01-05 07:42:10 +0000 | [diff] [blame] | 1625 | Value *StrippedPtr = PtrOp->stripPointerCasts(); |
Nadav Rotem | e63e59c | 2012-03-26 20:39:18 +0000 | [diff] [blame] | 1626 | PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType()); |
| 1627 | |
Nadav Rotem | a8f3562 | 2012-03-26 21:00:53 +0000 | [diff] [blame] | 1628 | // We do not handle pointer-vector geps here. |
| 1629 | if (!StrippedPtrTy) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1630 | return nullptr; |
Nadav Rotem | a8f3562 | 2012-03-26 21:00:53 +0000 | [diff] [blame] | 1631 | |
Matt Arsenault | aa689f5 | 2014-02-14 00:49:12 +0000 | [diff] [blame] | 1632 | if (StrippedPtr != PtrOp) { |
Chris Lattner | 8574aba | 2009-11-27 00:29:05 +0000 | [diff] [blame] | 1633 | bool HasZeroPointerIndex = false; |
| 1634 | if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) |
| 1635 | HasZeroPointerIndex = C->isZero(); |
Nadav Rotem | a069c6c | 2011-04-05 14:29:52 +0000 | [diff] [blame] | 1636 | |
Chris Lattner | c2f2cf8 | 2009-08-30 20:36:46 +0000 | [diff] [blame] | 1637 | // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... |
| 1638 | // into : GEP [10 x i8]* X, i32 0, ... |
| 1639 | // |
| 1640 | // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... |
| 1641 | // into : GEP i8* X, ... |
Nadav Rotem | a069c6c | 2011-04-05 14:29:52 +0000 | [diff] [blame] | 1642 | // |
Chris Lattner | c2f2cf8 | 2009-08-30 20:36:46 +0000 | [diff] [blame] | 1643 | // This occurs when the program declares an array extern like "int X[];" |
Chris Lattner | e26bf17 | 2009-08-30 05:00:50 +0000 | [diff] [blame] | 1644 | if (HasZeroPointerIndex) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1645 | PointerType *CPTy = cast<PointerType>(PtrOp->getType()); |
| 1646 | if (ArrayType *CATy = |
Duncan Sands | 5795a60 | 2009-03-02 09:18:21 +0000 | [diff] [blame] | 1647 | dyn_cast<ArrayType>(CPTy->getElementType())) { |
| 1648 | // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? |
Chris Lattner | e903f38 | 2010-01-05 07:42:10 +0000 | [diff] [blame] | 1649 | if (CATy->getElementType() == StrippedPtrTy->getElementType()) { |
Duncan Sands | 5795a60 | 2009-03-02 09:18:21 +0000 | [diff] [blame] | 1650 | // -> GEP i8* X, ... |
Chris Lattner | e903f38 | 2010-01-05 07:42:10 +0000 | [diff] [blame] | 1651 | SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); |
David Blaikie | 096b1da | 2015-03-14 19:53:33 +0000 | [diff] [blame] | 1652 | GetElementPtrInst *Res = GetElementPtrInst::Create( |
| 1653 | StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName()); |
Chris Lattner | e903f38 | 2010-01-05 07:42:10 +0000 | [diff] [blame] | 1654 | Res->setIsInBounds(GEP.isInBounds()); |
Eli Bendersky | 9966b26 | 2014-04-03 17:51:58 +0000 | [diff] [blame] | 1655 | if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) |
| 1656 | return Res; |
| 1657 | // Insert Res, and create an addrspacecast. |
| 1658 | // e.g., |
| 1659 | // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... |
| 1660 | // -> |
| 1661 | // %0 = GEP i8 addrspace(1)* X, ... |
| 1662 | // addrspacecast i8 addrspace(1)* %0 to i8* |
| 1663 | return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType()); |
Chris Lattner | c2f2cf8 | 2009-08-30 20:36:46 +0000 | [diff] [blame] | 1664 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1665 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1666 | if (ArrayType *XATy = |
Chris Lattner | e903f38 | 2010-01-05 07:42:10 +0000 | [diff] [blame] | 1667 | dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){ |
Duncan Sands | 5795a60 | 2009-03-02 09:18:21 +0000 | [diff] [blame] | 1668 | // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? |
Chris Lattner | 567b81f | 2005-09-13 00:40:14 +0000 | [diff] [blame] | 1669 | if (CATy->getElementType() == XATy->getElementType()) { |
Duncan Sands | 5795a60 | 2009-03-02 09:18:21 +0000 | [diff] [blame] | 1670 | // -> GEP [10 x i8]* X, i32 0, ... |
Chris Lattner | 567b81f | 2005-09-13 00:40:14 +0000 | [diff] [blame] | 1671 | // At this point, we know that the cast source type is a pointer |
| 1672 | // to an array of the same type as the destination pointer |
| 1673 | // array. Because the array type is never stepped over (there |
| 1674 | // is a leading zero) we can fold the cast into this GEP. |
Eli Bendersky | 9966b26 | 2014-04-03 17:51:58 +0000 | [diff] [blame] | 1675 | if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { |
| 1676 | GEP.setOperand(0, StrippedPtr); |
David Blaikie | 73cf872 | 2015-05-05 18:03:48 +0000 | [diff] [blame] | 1677 | GEP.setSourceElementType(XATy); |
Eli Bendersky | 9966b26 | 2014-04-03 17:51:58 +0000 | [diff] [blame] | 1678 | return &GEP; |
| 1679 | } |
| 1680 | // Cannot replace the base pointer directly because StrippedPtr's |
| 1681 | // address space is different. Instead, create a new GEP followed by |
| 1682 | // an addrspacecast. |
| 1683 | // e.g., |
| 1684 | // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), |
| 1685 | // i32 0, ... |
| 1686 | // -> |
| 1687 | // %0 = GEP [10 x i8] addrspace(1)* X, ... |
| 1688 | // addrspacecast i8 addrspace(1)* %0 to i8* |
| 1689 | SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1690 | Value *NewGEP = GEP.isInBounds() |
| 1691 | ? Builder->CreateInBoundsGEP( |
| 1692 | nullptr, StrippedPtr, Idx, GEP.getName()) |
| 1693 | : Builder->CreateGEP(nullptr, StrippedPtr, Idx, |
| 1694 | GEP.getName()); |
Eli Bendersky | 9966b26 | 2014-04-03 17:51:58 +0000 | [diff] [blame] | 1695 | return new AddrSpaceCastInst(NewGEP, GEP.getType()); |
Chris Lattner | 567b81f | 2005-09-13 00:40:14 +0000 | [diff] [blame] | 1696 | } |
Duncan Sands | 5795a60 | 2009-03-02 09:18:21 +0000 | [diff] [blame] | 1697 | } |
| 1698 | } |
Chris Lattner | 567b81f | 2005-09-13 00:40:14 +0000 | [diff] [blame] | 1699 | } else if (GEP.getNumOperands() == 2) { |
| 1700 | // Transform things like: |
Wojciech Matyjewicz | 309e5a7 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 1701 | // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V |
| 1702 | // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1703 | Type *SrcElTy = StrippedPtrTy->getElementType(); |
Matt Arsenault | fc00f7e | 2013-08-14 00:24:34 +0000 | [diff] [blame] | 1704 | Type *ResElTy = PtrOp->getType()->getPointerElementType(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1705 | if (SrcElTy->isArrayTy() && |
| 1706 | DL.getTypeAllocSize(SrcElTy->getArrayElementType()) == |
| 1707 | DL.getTypeAllocSize(ResElTy)) { |
| 1708 | Type *IdxType = DL.getIntPtrType(GEP.getType()); |
Matt Arsenault | 9e3a6ca | 2013-08-14 00:24:38 +0000 | [diff] [blame] | 1709 | Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 1710 | Value *NewGEP = |
| 1711 | GEP.isInBounds() |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1712 | ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx, |
| 1713 | GEP.getName()) |
| 1714 | : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName()); |
Matt Arsenault | aa689f5 | 2014-02-14 00:49:12 +0000 | [diff] [blame] | 1715 | |
Reid Spencer | 6c38f0b | 2006-11-27 01:05:10 +0000 | [diff] [blame] | 1716 | // V and GEP are both pointer types --> BitCast |
Manuel Jacob | 405fb18 | 2014-07-16 20:13:45 +0000 | [diff] [blame] | 1717 | return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, |
| 1718 | GEP.getType()); |
Chris Lattner | 8d0bacb | 2004-02-22 05:25:17 +0000 | [diff] [blame] | 1719 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1720 | |
Chris Lattner | 2a89329 | 2005-09-13 18:36:04 +0000 | [diff] [blame] | 1721 | // Transform things like: |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1722 | // %V = mul i64 %N, 4 |
| 1723 | // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V |
| 1724 | // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1725 | if (ResElTy->isSized() && SrcElTy->isSized()) { |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1726 | // Check that changing the type amounts to dividing the index by a scale |
| 1727 | // factor. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1728 | uint64_t ResSize = DL.getTypeAllocSize(ResElTy); |
| 1729 | uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy); |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1730 | if (ResSize && SrcSize % ResSize == 0) { |
| 1731 | Value *Idx = GEP.getOperand(1); |
| 1732 | unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); |
| 1733 | uint64_t Scale = SrcSize / ResSize; |
| 1734 | |
| 1735 | // Earlier transforms ensure that the index has type IntPtrType, which |
| 1736 | // considerably simplifies the logic by eliminating implicit casts. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1737 | assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) && |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1738 | "Index not cast to pointer width?"); |
| 1739 | |
| 1740 | bool NSW; |
| 1741 | if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { |
| 1742 | // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. |
| 1743 | // If the multiplication NewIdx * Scale may overflow then the new |
| 1744 | // GEP may not be "inbounds". |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 1745 | Value *NewGEP = |
| 1746 | GEP.isInBounds() && NSW |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1747 | ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx, |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 1748 | GEP.getName()) |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1749 | : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx, |
| 1750 | GEP.getName()); |
Matt Arsenault | aa689f5 | 2014-02-14 00:49:12 +0000 | [diff] [blame] | 1751 | |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1752 | // The NewGEP must be pointer typed, so must the old one -> BitCast |
Manuel Jacob | 405fb18 | 2014-07-16 20:13:45 +0000 | [diff] [blame] | 1753 | return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, |
| 1754 | GEP.getType()); |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1755 | } |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | // Similarly, transform things like: |
Wojciech Matyjewicz | 309e5a7 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 1760 | // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp |
Chris Lattner | 2a89329 | 2005-09-13 18:36:04 +0000 | [diff] [blame] | 1761 | // (where tmp = 8*tmp2) into: |
Wojciech Matyjewicz | 309e5a7 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 1762 | // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1763 | if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) { |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1764 | // Check that changing to the array element type amounts to dividing the |
| 1765 | // index by a scale factor. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1766 | uint64_t ResSize = DL.getTypeAllocSize(ResElTy); |
| 1767 | uint64_t ArrayEltSize = |
| 1768 | DL.getTypeAllocSize(SrcElTy->getArrayElementType()); |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1769 | if (ResSize && ArrayEltSize % ResSize == 0) { |
| 1770 | Value *Idx = GEP.getOperand(1); |
| 1771 | unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); |
| 1772 | uint64_t Scale = ArrayEltSize / ResSize; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1773 | |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1774 | // Earlier transforms ensure that the index has type IntPtrType, which |
| 1775 | // considerably simplifies the logic by eliminating implicit casts. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1776 | assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) && |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1777 | "Index not cast to pointer width?"); |
| 1778 | |
| 1779 | bool NSW; |
| 1780 | if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { |
| 1781 | // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. |
| 1782 | // If the multiplication NewIdx * Scale may overflow then the new |
| 1783 | // GEP may not be "inbounds". |
Matt Arsenault | 9e3a6ca | 2013-08-14 00:24:38 +0000 | [diff] [blame] | 1784 | Value *Off[2] = { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1785 | Constant::getNullValue(DL.getIntPtrType(GEP.getType())), |
| 1786 | NewIdx}; |
Matt Arsenault | 9e3a6ca | 2013-08-14 00:24:38 +0000 | [diff] [blame] | 1787 | |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1788 | Value *NewGEP = GEP.isInBounds() && NSW |
| 1789 | ? Builder->CreateInBoundsGEP( |
| 1790 | SrcElTy, StrippedPtr, Off, GEP.getName()) |
| 1791 | : Builder->CreateGEP(SrcElTy, StrippedPtr, Off, |
| 1792 | GEP.getName()); |
Duncan Sands | 533c8ae | 2012-10-23 08:28:26 +0000 | [diff] [blame] | 1793 | // The NewGEP must be pointer typed, so must the old one -> BitCast |
Manuel Jacob | 405fb18 | 2014-07-16 20:13:45 +0000 | [diff] [blame] | 1794 | return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, |
| 1795 | GEP.getType()); |
Chris Lattner | 2a89329 | 2005-09-13 18:36:04 +0000 | [diff] [blame] | 1796 | } |
| 1797 | } |
Chris Lattner | 2a89329 | 2005-09-13 18:36:04 +0000 | [diff] [blame] | 1798 | } |
Chris Lattner | 8d0bacb | 2004-02-22 05:25:17 +0000 | [diff] [blame] | 1799 | } |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 1800 | } |
Nadav Rotem | a069c6c | 2011-04-05 14:29:52 +0000 | [diff] [blame] | 1801 | |
Matt Arsenault | 4815f09 | 2014-08-12 19:46:13 +0000 | [diff] [blame] | 1802 | // addrspacecast between types is canonicalized as a bitcast, then an |
| 1803 | // addrspacecast. To take advantage of the below bitcast + struct GEP, look |
| 1804 | // through the addrspacecast. |
| 1805 | if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { |
| 1806 | // X = bitcast A addrspace(1)* to B addrspace(1)* |
| 1807 | // Y = addrspacecast A addrspace(1)* to B addrspace(2)* |
| 1808 | // Z = gep Y, <...constant indices...> |
| 1809 | // Into an addrspacecasted GEP of the struct. |
| 1810 | if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) |
| 1811 | PtrOp = BC; |
| 1812 | } |
| 1813 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1814 | /// See if we can simplify: |
Chris Lattner | 97fd359 | 2009-08-30 05:55:36 +0000 | [diff] [blame] | 1815 | /// X = bitcast A* to B* |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1816 | /// Y = gep X, <...constant indices...> |
| 1817 | /// into a gep of the original struct. This is important for SROA and alias |
| 1818 | /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. |
Chris Lattner | a784a2c | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 1819 | if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) { |
Matt Arsenault | 98f34e3 | 2013-08-19 22:17:34 +0000 | [diff] [blame] | 1820 | Value *Operand = BCI->getOperand(0); |
| 1821 | PointerType *OpType = cast<PointerType>(Operand->getType()); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1822 | unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType()); |
Matt Arsenault | 98f34e3 | 2013-08-19 22:17:34 +0000 | [diff] [blame] | 1823 | APInt Offset(OffsetBits, 0); |
| 1824 | if (!isa<BitCastInst>(Operand) && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1825 | GEP.accumulateConstantOffset(DL, Offset)) { |
Nadav Rotem | a069c6c | 2011-04-05 14:29:52 +0000 | [diff] [blame] | 1826 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1827 | // If this GEP instruction doesn't move the pointer, just replace the GEP |
| 1828 | // with a bitcast of the real input to the dest type. |
Nuno Lopes | b6ad982 | 2012-12-30 16:25:48 +0000 | [diff] [blame] | 1829 | if (!Offset) { |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1830 | // If the bitcast is of an allocation, and the allocation will be |
| 1831 | // converted to match the type of the cast, don't touch this. |
Matt Arsenault | 98f34e3 | 2013-08-19 22:17:34 +0000 | [diff] [blame] | 1832 | if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) { |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1833 | // See if the bitcast simplifies, if so, don't nuke this GEP yet. |
| 1834 | if (Instruction *I = visitBitCast(*BCI)) { |
| 1835 | if (I != BCI) { |
| 1836 | I->takeName(BCI); |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 1837 | BCI->getParent()->getInstList().insert(BCI->getIterator(), I); |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1838 | ReplaceInstUsesWith(*BCI, I); |
| 1839 | } |
| 1840 | return &GEP; |
Chris Lattner | a784a2c | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 1841 | } |
Chris Lattner | a784a2c | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 1842 | } |
Matt Arsenault | 4815f09 | 2014-08-12 19:46:13 +0000 | [diff] [blame] | 1843 | |
| 1844 | if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) |
| 1845 | return new AddrSpaceCastInst(Operand, GEP.getType()); |
Matt Arsenault | 98f34e3 | 2013-08-19 22:17:34 +0000 | [diff] [blame] | 1846 | return new BitCastInst(Operand, GEP.getType()); |
Chris Lattner | a784a2c | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 1847 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1848 | |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1849 | // Otherwise, if the offset is non-zero, we need to find out if there is a |
| 1850 | // field at Offset in 'A's type. If so, we can pull the cast through the |
| 1851 | // GEP. |
| 1852 | SmallVector<Value*, 8> NewIndices; |
Matt Arsenault | d79f7d9 | 2013-08-19 22:17:40 +0000 | [diff] [blame] | 1853 | if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) { |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1854 | Value *NGEP = |
| 1855 | GEP.isInBounds() |
| 1856 | ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices) |
| 1857 | : Builder->CreateGEP(nullptr, Operand, NewIndices); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1858 | |
Chris Lattner | 5966341 | 2009-08-30 18:50:58 +0000 | [diff] [blame] | 1859 | if (NGEP->getType() == GEP.getType()) |
| 1860 | return ReplaceInstUsesWith(GEP, NGEP); |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1861 | NGEP->takeName(&GEP); |
Matt Arsenault | 4815f09 | 2014-08-12 19:46:13 +0000 | [diff] [blame] | 1862 | |
| 1863 | if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) |
| 1864 | return new AddrSpaceCastInst(NGEP, GEP.getType()); |
Chris Lattner | fef138b | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 1865 | return new BitCastInst(NGEP, GEP.getType()); |
| 1866 | } |
Chris Lattner | a784a2c | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 1867 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 1868 | } |
| 1869 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1870 | return nullptr; |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 1871 | } |
| 1872 | |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1873 | static bool |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 1874 | isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users, |
| 1875 | const TargetLibraryInfo *TLI) { |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1876 | SmallVector<Instruction*, 4> Worklist; |
| 1877 | Worklist.push_back(AI); |
Nick Lewycky | e8ae02d | 2011-08-02 22:08:01 +0000 | [diff] [blame] | 1878 | |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1879 | do { |
| 1880 | Instruction *PI = Worklist.pop_back_val(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1881 | for (User *U : PI->users()) { |
| 1882 | Instruction *I = cast<Instruction>(U); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1883 | switch (I->getOpcode()) { |
| 1884 | default: |
| 1885 | // Give up the moment we see something we can't handle. |
Nuno Lopes | fa0dffc | 2012-07-06 23:09:25 +0000 | [diff] [blame] | 1886 | return false; |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1887 | |
| 1888 | case Instruction::BitCast: |
| 1889 | case Instruction::GetElementPtr: |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1890 | Users.emplace_back(I); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1891 | Worklist.push_back(I); |
| 1892 | continue; |
| 1893 | |
| 1894 | case Instruction::ICmp: { |
| 1895 | ICmpInst *ICI = cast<ICmpInst>(I); |
| 1896 | // We can fold eq/ne comparisons with null to false/true, respectively. |
| 1897 | if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1))) |
| 1898 | return false; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1899 | Users.emplace_back(I); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1900 | continue; |
| 1901 | } |
| 1902 | |
| 1903 | case Instruction::Call: |
| 1904 | // Ignore no-op and store intrinsics. |
| 1905 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 1906 | switch (II->getIntrinsicID()) { |
| 1907 | default: |
| 1908 | return false; |
| 1909 | |
| 1910 | case Intrinsic::memmove: |
| 1911 | case Intrinsic::memcpy: |
| 1912 | case Intrinsic::memset: { |
| 1913 | MemIntrinsic *MI = cast<MemIntrinsic>(II); |
| 1914 | if (MI->isVolatile() || MI->getRawDest() != PI) |
| 1915 | return false; |
| 1916 | } |
| 1917 | // fall through |
| 1918 | case Intrinsic::dbg_declare: |
| 1919 | case Intrinsic::dbg_value: |
| 1920 | case Intrinsic::invariant_start: |
| 1921 | case Intrinsic::invariant_end: |
| 1922 | case Intrinsic::lifetime_start: |
| 1923 | case Intrinsic::lifetime_end: |
| 1924 | case Intrinsic::objectsize: |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1925 | Users.emplace_back(I); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1926 | continue; |
| 1927 | } |
| 1928 | } |
| 1929 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 1930 | if (isFreeCall(I, TLI)) { |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1931 | Users.emplace_back(I); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1932 | continue; |
| 1933 | } |
| 1934 | return false; |
| 1935 | |
| 1936 | case Instruction::Store: { |
| 1937 | StoreInst *SI = cast<StoreInst>(I); |
| 1938 | if (SI->isVolatile() || SI->getPointerOperand() != PI) |
| 1939 | return false; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 1940 | Users.emplace_back(I); |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1941 | continue; |
| 1942 | } |
| 1943 | } |
| 1944 | llvm_unreachable("missing a return?"); |
Nuno Lopes | fa0dffc | 2012-07-06 23:09:25 +0000 | [diff] [blame] | 1945 | } |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1946 | } while (!Worklist.empty()); |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1947 | return true; |
| 1948 | } |
| 1949 | |
Nuno Lopes | 95cc4f3 | 2012-07-09 18:38:20 +0000 | [diff] [blame] | 1950 | Instruction *InstCombiner::visitAllocSite(Instruction &MI) { |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1951 | // If we have a malloc call which is only used in any amount of comparisons |
| 1952 | // to null and free calls, delete the calls and replace the comparisons with |
| 1953 | // true or false as appropriate. |
Nick Lewycky | 50f4966 | 2011-08-03 00:43:35 +0000 | [diff] [blame] | 1954 | SmallVector<WeakVH, 64> Users; |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 1955 | if (isAllocSiteRemovable(&MI, Users, TLI)) { |
Nick Lewycky | 50f4966 | 2011-08-03 00:43:35 +0000 | [diff] [blame] | 1956 | for (unsigned i = 0, e = Users.size(); i != e; ++i) { |
| 1957 | Instruction *I = cast_or_null<Instruction>(&*Users[i]); |
| 1958 | if (!I) continue; |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1959 | |
Nick Lewycky | 50f4966 | 2011-08-03 00:43:35 +0000 | [diff] [blame] | 1960 | if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { |
Nick Lewycky | e8ae02d | 2011-08-02 22:08:01 +0000 | [diff] [blame] | 1961 | ReplaceInstUsesWith(*C, |
| 1962 | ConstantInt::get(Type::getInt1Ty(C->getContext()), |
| 1963 | C->isFalseWhenEqual())); |
Nick Lewycky | 50f4966 | 2011-08-03 00:43:35 +0000 | [diff] [blame] | 1964 | } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) { |
Nick Lewycky | e8ae02d | 2011-08-02 22:08:01 +0000 | [diff] [blame] | 1965 | ReplaceInstUsesWith(*I, UndefValue::get(I->getType())); |
Nuno Lopes | fa0dffc | 2012-07-06 23:09:25 +0000 | [diff] [blame] | 1966 | } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 1967 | if (II->getIntrinsicID() == Intrinsic::objectsize) { |
| 1968 | ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1)); |
| 1969 | uint64_t DontKnow = CI->isZero() ? -1ULL : 0; |
| 1970 | ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow)); |
| 1971 | } |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1972 | } |
Nick Lewycky | 50f4966 | 2011-08-03 00:43:35 +0000 | [diff] [blame] | 1973 | EraseInstFromFunction(*I); |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1974 | } |
Nuno Lopes | dc6085e | 2012-06-21 21:25:05 +0000 | [diff] [blame] | 1975 | |
| 1976 | if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { |
Nuno Lopes | 9ac4661 | 2012-06-28 22:31:24 +0000 | [diff] [blame] | 1977 | // Replace invoke with a NOP intrinsic to maintain the original CFG |
Nuno Lopes | 07594cb | 2012-06-25 17:11:47 +0000 | [diff] [blame] | 1978 | Module *M = II->getParent()->getParent()->getParent(); |
Nuno Lopes | 9ac4661 | 2012-06-28 22:31:24 +0000 | [diff] [blame] | 1979 | Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); |
| 1980 | InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), |
Dmitri Gribenko | 3238fb7 | 2013-05-05 00:40:33 +0000 | [diff] [blame] | 1981 | None, "", II->getParent()); |
Nuno Lopes | dc6085e | 2012-06-21 21:25:05 +0000 | [diff] [blame] | 1982 | } |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1983 | return EraseInstFromFunction(MI); |
| 1984 | } |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1985 | return nullptr; |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 1986 | } |
| 1987 | |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 1988 | /// \brief Move the call to free before a NULL test. |
| 1989 | /// |
| 1990 | /// Check if this free is accessed after its argument has been test |
| 1991 | /// against NULL (property 0). |
| 1992 | /// If yes, it is legal to move this call in its predecessor block. |
| 1993 | /// |
| 1994 | /// The move is performed only if the block containing the call to free |
| 1995 | /// will be removed, i.e.: |
| 1996 | /// 1. it has only one predecessor P, and P has two successors |
| 1997 | /// 2. it contains the call and an unconditional branch |
| 1998 | /// 3. its successor is the same as its predecessor's successor |
| 1999 | /// |
| 2000 | /// The profitability is out-of concern here and this function should |
| 2001 | /// be called only if the caller knows this transformation would be |
| 2002 | /// profitable (e.g., for code size). |
| 2003 | static Instruction * |
| 2004 | tryToMoveFreeBeforeNullTest(CallInst &FI) { |
| 2005 | Value *Op = FI.getArgOperand(0); |
| 2006 | BasicBlock *FreeInstrBB = FI.getParent(); |
| 2007 | BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); |
| 2008 | |
| 2009 | // Validate part of constraint #1: Only one predecessor |
| 2010 | // FIXME: We can extend the number of predecessor, but in that case, we |
| 2011 | // would duplicate the call to free in each predecessor and it may |
| 2012 | // not be profitable even for code size. |
| 2013 | if (!PredBB) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2014 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2015 | |
| 2016 | // Validate constraint #2: Does this block contains only the call to |
| 2017 | // free and an unconditional branch? |
| 2018 | // FIXME: We could check if we can speculate everything in the |
| 2019 | // predecessor block |
| 2020 | if (FreeInstrBB->size() != 2) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2021 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2022 | BasicBlock *SuccBB; |
| 2023 | if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2024 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2025 | |
| 2026 | // Validate the rest of constraint #1 by matching on the pred branch. |
| 2027 | TerminatorInst *TI = PredBB->getTerminator(); |
| 2028 | BasicBlock *TrueBB, *FalseBB; |
| 2029 | ICmpInst::Predicate Pred; |
| 2030 | if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2031 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2032 | if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2033 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2034 | |
| 2035 | // Validate constraint #3: Ensure the null case just falls through. |
| 2036 | if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2037 | return nullptr; |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2038 | assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && |
| 2039 | "Broken CFG: missing edge from predecessor to successor"); |
| 2040 | |
| 2041 | FI.moveBefore(TI); |
| 2042 | return &FI; |
| 2043 | } |
Duncan Sands | f162eac | 2010-05-27 19:09:06 +0000 | [diff] [blame] | 2044 | |
| 2045 | |
Gabor Greif | 75f6943 | 2010-06-24 12:21:15 +0000 | [diff] [blame] | 2046 | Instruction *InstCombiner::visitFree(CallInst &FI) { |
| 2047 | Value *Op = FI.getArgOperand(0); |
Victor Hernandez | e297149 | 2009-10-24 04:23:03 +0000 | [diff] [blame] | 2048 | |
| 2049 | // free undef -> unreachable. |
| 2050 | if (isa<UndefValue>(Op)) { |
| 2051 | // Insert a new store to null because we cannot modify the CFG here. |
Eli Friedman | 41e509a | 2011-05-18 23:58:37 +0000 | [diff] [blame] | 2052 | Builder->CreateStore(ConstantInt::getTrue(FI.getContext()), |
| 2053 | UndefValue::get(Type::getInt1PtrTy(FI.getContext()))); |
Victor Hernandez | e297149 | 2009-10-24 04:23:03 +0000 | [diff] [blame] | 2054 | return EraseInstFromFunction(FI); |
| 2055 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2056 | |
Victor Hernandez | e297149 | 2009-10-24 04:23:03 +0000 | [diff] [blame] | 2057 | // If we have 'free null' delete the instruction. This can happen in stl code |
| 2058 | // when lots of inlining happens. |
| 2059 | if (isa<ConstantPointerNull>(Op)) |
| 2060 | return EraseInstFromFunction(FI); |
| 2061 | |
Quentin Colombet | 3b2db0b | 2013-01-07 18:37:41 +0000 | [diff] [blame] | 2062 | // If we optimize for code size, try to move the call to free before the null |
| 2063 | // test so that simplify cfg can remove the empty block and dead code |
| 2064 | // elimination the branch. I.e., helps to turn something like: |
| 2065 | // if (foo) free(foo); |
| 2066 | // into |
| 2067 | // free(foo); |
| 2068 | if (MinimizeSize) |
| 2069 | if (Instruction *I = tryToMoveFreeBeforeNullTest(FI)) |
| 2070 | return I; |
| 2071 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2072 | return nullptr; |
Victor Hernandez | e297149 | 2009-10-24 04:23:03 +0000 | [diff] [blame] | 2073 | } |
Chris Lattner | 8427bff | 2003-12-07 01:24:23 +0000 | [diff] [blame] | 2074 | |
Hal Finkel | 93873cc1 | 2014-09-07 21:28:34 +0000 | [diff] [blame] | 2075 | Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) { |
| 2076 | if (RI.getNumOperands() == 0) // ret void |
| 2077 | return nullptr; |
Chris Lattner | 14a251b | 2007-04-15 00:07:55 +0000 | [diff] [blame] | 2078 | |
Hal Finkel | 93873cc1 | 2014-09-07 21:28:34 +0000 | [diff] [blame] | 2079 | Value *ResultOp = RI.getOperand(0); |
| 2080 | Type *VTy = ResultOp->getType(); |
| 2081 | if (!VTy->isIntegerTy()) |
| 2082 | return nullptr; |
| 2083 | |
| 2084 | // There might be assume intrinsics dominating this return that completely |
| 2085 | // determine the value. If so, constant fold it. |
| 2086 | unsigned BitWidth = VTy->getPrimitiveSizeInBits(); |
| 2087 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 2088 | computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI); |
| 2089 | if ((KnownZero|KnownOne).isAllOnesValue()) |
| 2090 | RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne)); |
| 2091 | |
| 2092 | return nullptr; |
| 2093 | } |
Chris Lattner | 31f486c | 2005-01-31 05:36:43 +0000 | [diff] [blame] | 2094 | |
Chris Lattner | 9eef8a7 | 2003-06-04 04:46:00 +0000 | [diff] [blame] | 2095 | Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { |
| 2096 | // Change br (not X), label True, label False to: br X, label False, True |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2097 | Value *X = nullptr; |
Chris Lattner | d4252a7 | 2004-07-30 07:50:03 +0000 | [diff] [blame] | 2098 | BasicBlock *TrueDest; |
| 2099 | BasicBlock *FalseDest; |
Dan Gohman | 5476cfd | 2009-08-12 16:23:25 +0000 | [diff] [blame] | 2100 | if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && |
Chris Lattner | d4252a7 | 2004-07-30 07:50:03 +0000 | [diff] [blame] | 2101 | !isa<Constant>(X)) { |
| 2102 | // Swap Destinations and condition... |
| 2103 | BI.setCondition(X); |
Chandler Carruth | 3e8aa65 | 2011-10-17 01:11:57 +0000 | [diff] [blame] | 2104 | BI.swapSuccessors(); |
Chris Lattner | d4252a7 | 2004-07-30 07:50:03 +0000 | [diff] [blame] | 2105 | return &BI; |
| 2106 | } |
| 2107 | |
Philip Reames | 71c4035 | 2015-03-10 22:52:37 +0000 | [diff] [blame] | 2108 | // If the condition is irrelevant, remove the use so that other |
| 2109 | // transforms on the condition become more effective. |
| 2110 | if (BI.isConditional() && |
| 2111 | BI.getSuccessor(0) == BI.getSuccessor(1) && |
| 2112 | !isa<UndefValue>(BI.getCondition())) { |
| 2113 | BI.setCondition(UndefValue::get(BI.getCondition()->getType())); |
| 2114 | return &BI; |
| 2115 | } |
| 2116 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 2117 | // Canonicalize fcmp_one -> fcmp_oeq |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2118 | FCmpInst::Predicate FPred; Value *Y; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2119 | if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2120 | TrueDest, FalseDest)) && |
| 2121 | BI.getCondition()->hasOneUse()) |
| 2122 | if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || |
| 2123 | FPred == FCmpInst::FCMP_OGE) { |
| 2124 | FCmpInst *Cond = cast<FCmpInst>(BI.getCondition()); |
| 2125 | Cond->setPredicate(FCmpInst::getInversePredicate(FPred)); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2126 | |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2127 | // Swap Destinations and condition. |
Chandler Carruth | 3e8aa65 | 2011-10-17 01:11:57 +0000 | [diff] [blame] | 2128 | BI.swapSuccessors(); |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2129 | Worklist.Add(Cond); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2130 | return &BI; |
| 2131 | } |
| 2132 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 2133 | // Canonicalize icmp_ne -> icmp_eq |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2134 | ICmpInst::Predicate IPred; |
| 2135 | if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2136 | TrueDest, FalseDest)) && |
| 2137 | BI.getCondition()->hasOneUse()) |
| 2138 | if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || |
| 2139 | IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || |
| 2140 | IPred == ICmpInst::ICMP_SGE) { |
| 2141 | ICmpInst *Cond = cast<ICmpInst>(BI.getCondition()); |
| 2142 | Cond->setPredicate(ICmpInst::getInversePredicate(IPred)); |
| 2143 | // Swap Destinations and condition. |
Chandler Carruth | 3e8aa65 | 2011-10-17 01:11:57 +0000 | [diff] [blame] | 2144 | BI.swapSuccessors(); |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2145 | Worklist.Add(Cond); |
Chris Lattner | e967b34 | 2003-06-04 05:10:11 +0000 | [diff] [blame] | 2146 | return &BI; |
| 2147 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2148 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2149 | return nullptr; |
Chris Lattner | 9eef8a7 | 2003-06-04 04:46:00 +0000 | [diff] [blame] | 2150 | } |
Chris Lattner | 1085bdf | 2002-11-04 16:18:53 +0000 | [diff] [blame] | 2151 | |
Chris Lattner | 4c9c20a | 2004-07-03 00:26:11 +0000 | [diff] [blame] | 2152 | Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { |
| 2153 | Value *Cond = SI.getCondition(); |
Akira Hatanaka | 5c221ef | 2014-10-16 06:00:46 +0000 | [diff] [blame] | 2154 | unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth(); |
| 2155 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2156 | computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI); |
Akira Hatanaka | 5c221ef | 2014-10-16 06:00:46 +0000 | [diff] [blame] | 2157 | unsigned LeadingKnownZeros = KnownZero.countLeadingOnes(); |
| 2158 | unsigned LeadingKnownOnes = KnownOne.countLeadingOnes(); |
| 2159 | |
| 2160 | // Compute the number of leading bits we can ignore. |
| 2161 | for (auto &C : SI.cases()) { |
| 2162 | LeadingKnownZeros = std::min( |
| 2163 | LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); |
| 2164 | LeadingKnownOnes = std::min( |
| 2165 | LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); |
| 2166 | } |
| 2167 | |
| 2168 | unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes); |
| 2169 | |
| 2170 | // Truncate the condition operand if the new type is equal to or larger than |
| 2171 | // the largest legal integer type. We need to be conservative here since |
Sanjay Patel | 6a24811 | 2015-06-23 23:26:22 +0000 | [diff] [blame] | 2172 | // x86 generates redundant zero-extension instructions if the operand is |
Akira Hatanaka | 5c221ef | 2014-10-16 06:00:46 +0000 | [diff] [blame] | 2173 | // truncated to i8 or i16. |
Bruno Cardoso Lopes | f6cf8ad | 2014-12-19 17:12:35 +0000 | [diff] [blame] | 2174 | bool TruncCond = false; |
Owen Anderson | 58364dc | 2015-03-10 06:51:39 +0000 | [diff] [blame] | 2175 | if (NewWidth > 0 && BitWidth > NewWidth && |
| 2176 | NewWidth >= DL.getLargestLegalIntTypeSize()) { |
Bruno Cardoso Lopes | f6cf8ad | 2014-12-19 17:12:35 +0000 | [diff] [blame] | 2177 | TruncCond = true; |
Akira Hatanaka | 5c221ef | 2014-10-16 06:00:46 +0000 | [diff] [blame] | 2178 | IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); |
| 2179 | Builder->SetInsertPoint(&SI); |
| 2180 | Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc"); |
| 2181 | SI.setCondition(NewCond); |
| 2182 | |
| 2183 | for (auto &C : SI.cases()) |
| 2184 | static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get( |
| 2185 | SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth))); |
| 2186 | } |
| 2187 | |
Chris Lattner | 4c9c20a | 2004-07-03 00:26:11 +0000 | [diff] [blame] | 2188 | if (Instruction *I = dyn_cast<Instruction>(Cond)) { |
| 2189 | if (I->getOpcode() == Instruction::Add) |
| 2190 | if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 2191 | // change 'switch (X+4) case 1:' into 'switch (X) case -3' |
Eli Friedman | 95031ed | 2011-09-29 20:21:17 +0000 | [diff] [blame] | 2192 | // Skip the first item since that's the default case. |
Stepan Dyatkovskiy | 97b02fc | 2012-03-11 06:09:17 +0000 | [diff] [blame] | 2193 | for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 2194 | i != e; ++i) { |
| 2195 | ConstantInt* CaseVal = i.getCaseValue(); |
Bruno Cardoso Lopes | f6cf8ad | 2014-12-19 17:12:35 +0000 | [diff] [blame] | 2196 | Constant *LHS = CaseVal; |
| 2197 | if (TruncCond) |
| 2198 | LHS = LeadingKnownZeros |
| 2199 | ? ConstantExpr::getZExt(CaseVal, Cond->getType()) |
| 2200 | : ConstantExpr::getSExt(CaseVal, Cond->getType()); |
| 2201 | Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS); |
Eli Friedman | 95031ed | 2011-09-29 20:21:17 +0000 | [diff] [blame] | 2202 | assert(isa<ConstantInt>(NewCaseVal) && |
| 2203 | "Result of expression should be constant"); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 2204 | i.setValue(cast<ConstantInt>(NewCaseVal)); |
Eli Friedman | 95031ed | 2011-09-29 20:21:17 +0000 | [diff] [blame] | 2205 | } |
| 2206 | SI.setCondition(I->getOperand(0)); |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2207 | Worklist.Add(I); |
Chris Lattner | 4c9c20a | 2004-07-03 00:26:11 +0000 | [diff] [blame] | 2208 | return &SI; |
| 2209 | } |
| 2210 | } |
Bruno Cardoso Lopes | f6cf8ad | 2014-12-19 17:12:35 +0000 | [diff] [blame] | 2211 | |
| 2212 | return TruncCond ? &SI : nullptr; |
Chris Lattner | 4c9c20a | 2004-07-03 00:26:11 +0000 | [diff] [blame] | 2213 | } |
| 2214 | |
Matthijs Kooijman | b2fc72b | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 2215 | Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2216 | Value *Agg = EV.getAggregateOperand(); |
Matthijs Kooijman | b2fc72b | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 2217 | |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2218 | if (!EV.hasIndices()) |
| 2219 | return ReplaceInstUsesWith(EV, Agg); |
| 2220 | |
David Majnemer | 25a796e | 2015-07-13 01:15:46 +0000 | [diff] [blame] | 2221 | if (Value *V = |
| 2222 | SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC)) |
| 2223 | return ReplaceInstUsesWith(EV, V); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2224 | |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2225 | if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { |
| 2226 | // We're extracting from an insertvalue instruction, compare the indices |
| 2227 | const unsigned *exti, *exte, *insi, *inse; |
| 2228 | for (exti = EV.idx_begin(), insi = IV->idx_begin(), |
| 2229 | exte = EV.idx_end(), inse = IV->idx_end(); |
| 2230 | exti != exte && insi != inse; |
| 2231 | ++exti, ++insi) { |
| 2232 | if (*insi != *exti) |
| 2233 | // The insert and extract both reference distinctly different elements. |
| 2234 | // This means the extract is not influenced by the insert, and we can |
| 2235 | // replace the aggregate operand of the extract with the aggregate |
| 2236 | // operand of the insert. i.e., replace |
| 2237 | // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 |
| 2238 | // %E = extractvalue { i32, { i32 } } %I, 0 |
| 2239 | // with |
| 2240 | // %E = extractvalue { i32, { i32 } } %A, 0 |
| 2241 | return ExtractValueInst::Create(IV->getAggregateOperand(), |
Jay Foad | 57aa636 | 2011-07-13 10:26:04 +0000 | [diff] [blame] | 2242 | EV.getIndices()); |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2243 | } |
| 2244 | if (exti == exte && insi == inse) |
| 2245 | // Both iterators are at the end: Index lists are identical. Replace |
| 2246 | // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 |
| 2247 | // %C = extractvalue { i32, { i32 } } %B, 1, 0 |
| 2248 | // with "i32 42" |
| 2249 | return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand()); |
| 2250 | if (exti == exte) { |
| 2251 | // The extract list is a prefix of the insert list. i.e. replace |
| 2252 | // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 |
| 2253 | // %E = extractvalue { i32, { i32 } } %I, 1 |
| 2254 | // with |
| 2255 | // %X = extractvalue { i32, { i32 } } %A, 1 |
| 2256 | // %E = insertvalue { i32 } %X, i32 42, 0 |
| 2257 | // by switching the order of the insert and extract (though the |
| 2258 | // insertvalue should be left in, since it may have other uses). |
Chris Lattner | 5966341 | 2009-08-30 18:50:58 +0000 | [diff] [blame] | 2259 | Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(), |
Jay Foad | 57aa636 | 2011-07-13 10:26:04 +0000 | [diff] [blame] | 2260 | EV.getIndices()); |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2261 | return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), |
Frits van Bommel | 717d7ed | 2011-07-18 12:00:32 +0000 | [diff] [blame] | 2262 | makeArrayRef(insi, inse)); |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2263 | } |
| 2264 | if (insi == inse) |
| 2265 | // The insert list is a prefix of the extract list |
| 2266 | // We can simply remove the common indices from the extract and make it |
| 2267 | // operate on the inserted value instead of the insertvalue result. |
| 2268 | // i.e., replace |
| 2269 | // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 |
| 2270 | // %E = extractvalue { i32, { i32 } } %I, 1, 0 |
| 2271 | // with |
| 2272 | // %E extractvalue { i32 } { i32 42 }, 0 |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2273 | return ExtractValueInst::Create(IV->getInsertedValueOperand(), |
Frits van Bommel | 717d7ed | 2011-07-18 12:00:32 +0000 | [diff] [blame] | 2274 | makeArrayRef(exti, exte)); |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2275 | } |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2276 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { |
| 2277 | // We're extracting from an intrinsic, see if we're the only user, which |
| 2278 | // allows us to simplify multiple result intrinsics to simpler things that |
Gabor Greif | 75f6943 | 2010-06-24 12:21:15 +0000 | [diff] [blame] | 2279 | // just get one value. |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2280 | if (II->hasOneUse()) { |
| 2281 | // Check if we're grabbing the overflow bit or the result of a 'with |
| 2282 | // overflow' intrinsic. If it's the latter we can remove the intrinsic |
| 2283 | // and replace it with a traditional binary instruction. |
| 2284 | switch (II->getIntrinsicID()) { |
| 2285 | case Intrinsic::uadd_with_overflow: |
| 2286 | case Intrinsic::sadd_with_overflow: |
| 2287 | if (*EV.idx_begin() == 0) { // Normal result. |
Gabor Greif | 75f6943 | 2010-06-24 12:21:15 +0000 | [diff] [blame] | 2288 | Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); |
Eli Friedman | b9ed18f | 2011-05-18 00:32:01 +0000 | [diff] [blame] | 2289 | ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2290 | EraseInstFromFunction(*II); |
| 2291 | return BinaryOperator::CreateAdd(LHS, RHS); |
| 2292 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2293 | |
Chris Lattner | 3e635d2 | 2010-12-19 19:43:52 +0000 | [diff] [blame] | 2294 | // If the normal result of the add is dead, and the RHS is a constant, |
| 2295 | // we can transform this into a range comparison. |
| 2296 | // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 |
Chris Lattner | 4fb9dd4 | 2010-12-19 23:24:04 +0000 | [diff] [blame] | 2297 | if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) |
| 2298 | if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) |
| 2299 | return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), |
| 2300 | ConstantExpr::getNot(CI)); |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2301 | break; |
| 2302 | case Intrinsic::usub_with_overflow: |
| 2303 | case Intrinsic::ssub_with_overflow: |
| 2304 | if (*EV.idx_begin() == 0) { // Normal result. |
Gabor Greif | 75f6943 | 2010-06-24 12:21:15 +0000 | [diff] [blame] | 2305 | Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); |
Eli Friedman | b9ed18f | 2011-05-18 00:32:01 +0000 | [diff] [blame] | 2306 | ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2307 | EraseInstFromFunction(*II); |
| 2308 | return BinaryOperator::CreateSub(LHS, RHS); |
| 2309 | } |
| 2310 | break; |
| 2311 | case Intrinsic::umul_with_overflow: |
| 2312 | case Intrinsic::smul_with_overflow: |
| 2313 | if (*EV.idx_begin() == 0) { // Normal result. |
Gabor Greif | 75f6943 | 2010-06-24 12:21:15 +0000 | [diff] [blame] | 2314 | Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); |
Eli Friedman | b9ed18f | 2011-05-18 00:32:01 +0000 | [diff] [blame] | 2315 | ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); |
Chris Lattner | 39c07b2 | 2009-11-09 07:07:56 +0000 | [diff] [blame] | 2316 | EraseInstFromFunction(*II); |
| 2317 | return BinaryOperator::CreateMul(LHS, RHS); |
| 2318 | } |
| 2319 | break; |
| 2320 | default: |
| 2321 | break; |
| 2322 | } |
| 2323 | } |
| 2324 | } |
Frits van Bommel | 28218aa | 2010-11-29 21:56:20 +0000 | [diff] [blame] | 2325 | if (LoadInst *L = dyn_cast<LoadInst>(Agg)) |
| 2326 | // If the (non-volatile) load only has one use, we can rewrite this to a |
| 2327 | // load from a GEP. This reduces the size of the load. |
| 2328 | // FIXME: If a load is used only by extractvalue instructions then this |
| 2329 | // could be done regardless of having multiple uses. |
Eli Friedman | 8bc586e | 2011-08-15 22:09:40 +0000 | [diff] [blame] | 2330 | if (L->isSimple() && L->hasOneUse()) { |
Frits van Bommel | 28218aa | 2010-11-29 21:56:20 +0000 | [diff] [blame] | 2331 | // extractvalue has integer indices, getelementptr has Value*s. Convert. |
| 2332 | SmallVector<Value*, 4> Indices; |
| 2333 | // Prefix an i32 0 since we need the first element. |
| 2334 | Indices.push_back(Builder->getInt32(0)); |
| 2335 | for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); |
| 2336 | I != E; ++I) |
| 2337 | Indices.push_back(Builder->getInt32(*I)); |
| 2338 | |
| 2339 | // We need to insert these at the location of the old load, not at that of |
| 2340 | // the extractvalue. |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2341 | Builder->SetInsertPoint(L); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 2342 | Value *GEP = Builder->CreateInBoundsGEP(L->getType(), |
| 2343 | L->getPointerOperand(), Indices); |
Frits van Bommel | 28218aa | 2010-11-29 21:56:20 +0000 | [diff] [blame] | 2344 | // Returning the load directly will cause the main loop to insert it in |
| 2345 | // the wrong spot, so use ReplaceInstUsesWith(). |
| 2346 | return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP)); |
| 2347 | } |
| 2348 | // We could simplify extracts from other values. Note that nested extracts may |
| 2349 | // already be simplified implicitly by the above: extract (extract (insert) ) |
Matthijs Kooijman | c1d7477 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 2350 | // will be translated into extract ( insert ( extract ) ) first and then just |
Frits van Bommel | 28218aa | 2010-11-29 21:56:20 +0000 | [diff] [blame] | 2351 | // the value inserted, if appropriate. Similarly for extracts from single-use |
| 2352 | // loads: extract (extract (load)) will be translated to extract (load (gep)) |
| 2353 | // and if again single-use then via load (gep (gep)) to load (gep). |
| 2354 | // However, double extracts from e.g. function arguments or return values |
| 2355 | // aren't handled yet. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2356 | return nullptr; |
Matthijs Kooijman | b2fc72b | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 2357 | } |
| 2358 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 2359 | /// Return 'true' if the given typeinfo will match anything. |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2360 | static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2361 | switch (Personality) { |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2362 | case EHPersonality::GNU_C: |
| 2363 | // The GCC C EH personality only exists to support cleanups, so it's not |
| 2364 | // clear what the semantics of catch clauses are. |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2365 | return false; |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2366 | case EHPersonality::Unknown: |
| 2367 | return false; |
| 2368 | case EHPersonality::GNU_Ada: |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2369 | // While __gnat_all_others_value will match any Ada exception, it doesn't |
| 2370 | // match foreign exceptions (or didn't, before gcc-4.7). |
| 2371 | return false; |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2372 | case EHPersonality::GNU_CXX: |
| 2373 | case EHPersonality::GNU_ObjC: |
Reid Kleckner | 96d0113 | 2015-02-11 01:23:16 +0000 | [diff] [blame] | 2374 | case EHPersonality::MSVC_X86SEH: |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2375 | case EHPersonality::MSVC_Win64SEH: |
| 2376 | case EHPersonality::MSVC_CXX: |
Joseph Tremoulet | 2afea54 | 2015-10-06 20:28:16 +0000 | [diff] [blame] | 2377 | case EHPersonality::CoreCLR: |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2378 | return TypeInfo->isNullValue(); |
| 2379 | } |
Reid Kleckner | 4af6415 | 2015-01-28 01:17:38 +0000 | [diff] [blame] | 2380 | llvm_unreachable("invalid enum"); |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2381 | } |
| 2382 | |
| 2383 | static bool shorter_filter(const Value *LHS, const Value *RHS) { |
| 2384 | return |
| 2385 | cast<ArrayType>(LHS->getType())->getNumElements() |
| 2386 | < |
| 2387 | cast<ArrayType>(RHS->getType())->getNumElements(); |
| 2388 | } |
| 2389 | |
| 2390 | Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) { |
| 2391 | // The logic here should be correct for any real-world personality function. |
| 2392 | // However if that turns out not to be true, the offending logic can always |
| 2393 | // be conditioned on the personality function, like the catch-all logic is. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 2394 | EHPersonality Personality = |
| 2395 | classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2396 | |
| 2397 | // Simplify the list of clauses, eg by removing repeated catch clauses |
| 2398 | // (these are often created by inlining). |
| 2399 | bool MakeNewInstruction = false; // If true, recreate using the following: |
Rafael Espindola | 4dc5dfc | 2014-06-04 18:51:31 +0000 | [diff] [blame] | 2400 | SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2401 | bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. |
| 2402 | |
| 2403 | SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. |
| 2404 | for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { |
| 2405 | bool isLastClause = i + 1 == e; |
| 2406 | if (LI.isCatch(i)) { |
| 2407 | // A catch clause. |
Rafael Espindola | 4dc5dfc | 2014-06-04 18:51:31 +0000 | [diff] [blame] | 2408 | Constant *CatchClause = LI.getClause(i); |
Rafael Espindola | 78598d9 | 2014-06-04 19:01:48 +0000 | [diff] [blame] | 2409 | Constant *TypeInfo = CatchClause->stripPointerCasts(); |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2410 | |
| 2411 | // If we already saw this clause, there is no point in having a second |
| 2412 | // copy of it. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 2413 | if (AlreadyCaught.insert(TypeInfo).second) { |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2414 | // This catch clause was not already seen. |
| 2415 | NewClauses.push_back(CatchClause); |
| 2416 | } else { |
| 2417 | // Repeated catch clause - drop the redundant copy. |
| 2418 | MakeNewInstruction = true; |
| 2419 | } |
| 2420 | |
| 2421 | // If this is a catch-all then there is no point in keeping any following |
| 2422 | // clauses or marking the landingpad as having a cleanup. |
| 2423 | if (isCatchAll(Personality, TypeInfo)) { |
| 2424 | if (!isLastClause) |
| 2425 | MakeNewInstruction = true; |
| 2426 | CleanupFlag = false; |
| 2427 | break; |
| 2428 | } |
| 2429 | } else { |
| 2430 | // A filter clause. If any of the filter elements were already caught |
| 2431 | // then they can be dropped from the filter. It is tempting to try to |
| 2432 | // exploit the filter further by saying that any typeinfo that does not |
| 2433 | // occur in the filter can't be caught later (and thus can be dropped). |
| 2434 | // However this would be wrong, since typeinfos can match without being |
| 2435 | // equal (for example if one represents a C++ class, and the other some |
| 2436 | // class derived from it). |
| 2437 | assert(LI.isFilter(i) && "Unsupported landingpad clause!"); |
Rafael Espindola | 4dc5dfc | 2014-06-04 18:51:31 +0000 | [diff] [blame] | 2438 | Constant *FilterClause = LI.getClause(i); |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2439 | ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); |
| 2440 | unsigned NumTypeInfos = FilterType->getNumElements(); |
| 2441 | |
| 2442 | // An empty filter catches everything, so there is no point in keeping any |
| 2443 | // following clauses or marking the landingpad as having a cleanup. By |
| 2444 | // dealing with this case here the following code is made a bit simpler. |
| 2445 | if (!NumTypeInfos) { |
| 2446 | NewClauses.push_back(FilterClause); |
| 2447 | if (!isLastClause) |
| 2448 | MakeNewInstruction = true; |
| 2449 | CleanupFlag = false; |
| 2450 | break; |
| 2451 | } |
| 2452 | |
| 2453 | bool MakeNewFilter = false; // If true, make a new filter. |
| 2454 | SmallVector<Constant *, 16> NewFilterElts; // New elements. |
| 2455 | if (isa<ConstantAggregateZero>(FilterClause)) { |
| 2456 | // Not an empty filter - it contains at least one null typeinfo. |
| 2457 | assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); |
| 2458 | Constant *TypeInfo = |
| 2459 | Constant::getNullValue(FilterType->getElementType()); |
| 2460 | // If this typeinfo is a catch-all then the filter can never match. |
| 2461 | if (isCatchAll(Personality, TypeInfo)) { |
| 2462 | // Throw the filter away. |
| 2463 | MakeNewInstruction = true; |
| 2464 | continue; |
| 2465 | } |
| 2466 | |
| 2467 | // There is no point in having multiple copies of this typeinfo, so |
| 2468 | // discard all but the first copy if there is more than one. |
| 2469 | NewFilterElts.push_back(TypeInfo); |
| 2470 | if (NumTypeInfos > 1) |
| 2471 | MakeNewFilter = true; |
| 2472 | } else { |
| 2473 | ConstantArray *Filter = cast<ConstantArray>(FilterClause); |
| 2474 | SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. |
| 2475 | NewFilterElts.reserve(NumTypeInfos); |
| 2476 | |
| 2477 | // Remove any filter elements that were already caught or that already |
| 2478 | // occurred in the filter. While there, see if any of the elements are |
| 2479 | // catch-alls. If so, the filter can be discarded. |
| 2480 | bool SawCatchAll = false; |
| 2481 | for (unsigned j = 0; j != NumTypeInfos; ++j) { |
Rafael Espindola | 78598d9 | 2014-06-04 19:01:48 +0000 | [diff] [blame] | 2482 | Constant *Elt = Filter->getOperand(j); |
| 2483 | Constant *TypeInfo = Elt->stripPointerCasts(); |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2484 | if (isCatchAll(Personality, TypeInfo)) { |
| 2485 | // This element is a catch-all. Bail out, noting this fact. |
| 2486 | SawCatchAll = true; |
| 2487 | break; |
| 2488 | } |
| 2489 | if (AlreadyCaught.count(TypeInfo)) |
| 2490 | // Already caught by an earlier clause, so having it in the filter |
| 2491 | // is pointless. |
| 2492 | continue; |
| 2493 | // There is no point in having multiple copies of the same typeinfo in |
| 2494 | // a filter, so only add it if we didn't already. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 2495 | if (SeenInFilter.insert(TypeInfo).second) |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2496 | NewFilterElts.push_back(cast<Constant>(Elt)); |
| 2497 | } |
| 2498 | // A filter containing a catch-all cannot match anything by definition. |
| 2499 | if (SawCatchAll) { |
| 2500 | // Throw the filter away. |
| 2501 | MakeNewInstruction = true; |
| 2502 | continue; |
| 2503 | } |
| 2504 | |
| 2505 | // If we dropped something from the filter, make a new one. |
| 2506 | if (NewFilterElts.size() < NumTypeInfos) |
| 2507 | MakeNewFilter = true; |
| 2508 | } |
| 2509 | if (MakeNewFilter) { |
| 2510 | FilterType = ArrayType::get(FilterType->getElementType(), |
| 2511 | NewFilterElts.size()); |
| 2512 | FilterClause = ConstantArray::get(FilterType, NewFilterElts); |
| 2513 | MakeNewInstruction = true; |
| 2514 | } |
| 2515 | |
| 2516 | NewClauses.push_back(FilterClause); |
| 2517 | |
| 2518 | // If the new filter is empty then it will catch everything so there is |
| 2519 | // no point in keeping any following clauses or marking the landingpad |
| 2520 | // as having a cleanup. The case of the original filter being empty was |
| 2521 | // already handled above. |
| 2522 | if (MakeNewFilter && !NewFilterElts.size()) { |
| 2523 | assert(MakeNewInstruction && "New filter but not a new instruction!"); |
| 2524 | CleanupFlag = false; |
| 2525 | break; |
| 2526 | } |
| 2527 | } |
| 2528 | } |
| 2529 | |
| 2530 | // If several filters occur in a row then reorder them so that the shortest |
| 2531 | // filters come first (those with the smallest number of elements). This is |
| 2532 | // advantageous because shorter filters are more likely to match, speeding up |
| 2533 | // unwinding, but mostly because it increases the effectiveness of the other |
| 2534 | // filter optimizations below. |
| 2535 | for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { |
| 2536 | unsigned j; |
| 2537 | // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. |
| 2538 | for (j = i; j != e; ++j) |
| 2539 | if (!isa<ArrayType>(NewClauses[j]->getType())) |
| 2540 | break; |
| 2541 | |
| 2542 | // Check whether the filters are already sorted by length. We need to know |
| 2543 | // if sorting them is actually going to do anything so that we only make a |
| 2544 | // new landingpad instruction if it does. |
| 2545 | for (unsigned k = i; k + 1 < j; ++k) |
| 2546 | if (shorter_filter(NewClauses[k+1], NewClauses[k])) { |
| 2547 | // Not sorted, so sort the filters now. Doing an unstable sort would be |
| 2548 | // correct too but reordering filters pointlessly might confuse users. |
| 2549 | std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, |
| 2550 | shorter_filter); |
| 2551 | MakeNewInstruction = true; |
| 2552 | break; |
| 2553 | } |
| 2554 | |
| 2555 | // Look for the next batch of filters. |
| 2556 | i = j + 1; |
| 2557 | } |
| 2558 | |
| 2559 | // If typeinfos matched if and only if equal, then the elements of a filter L |
| 2560 | // that occurs later than a filter F could be replaced by the intersection of |
| 2561 | // the elements of F and L. In reality two typeinfos can match without being |
| 2562 | // equal (for example if one represents a C++ class, and the other some class |
| 2563 | // derived from it) so it would be wrong to perform this transform in general. |
| 2564 | // However the transform is correct and useful if F is a subset of L. In that |
| 2565 | // case L can be replaced by F, and thus removed altogether since repeating a |
| 2566 | // filter is pointless. So here we look at all pairs of filters F and L where |
| 2567 | // L follows F in the list of clauses, and remove L if every element of F is |
| 2568 | // an element of L. This can occur when inlining C++ functions with exception |
| 2569 | // specifications. |
| 2570 | for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { |
| 2571 | // Examine each filter in turn. |
| 2572 | Value *Filter = NewClauses[i]; |
| 2573 | ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); |
| 2574 | if (!FTy) |
| 2575 | // Not a filter - skip it. |
| 2576 | continue; |
| 2577 | unsigned FElts = FTy->getNumElements(); |
| 2578 | // Examine each filter following this one. Doing this backwards means that |
| 2579 | // we don't have to worry about filters disappearing under us when removed. |
| 2580 | for (unsigned j = NewClauses.size() - 1; j != i; --j) { |
| 2581 | Value *LFilter = NewClauses[j]; |
| 2582 | ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); |
| 2583 | if (!LTy) |
| 2584 | // Not a filter - skip it. |
| 2585 | continue; |
| 2586 | // If Filter is a subset of LFilter, i.e. every element of Filter is also |
| 2587 | // an element of LFilter, then discard LFilter. |
Rafael Espindola | 4dc5dfc | 2014-06-04 18:51:31 +0000 | [diff] [blame] | 2588 | SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2589 | // If Filter is empty then it is a subset of LFilter. |
| 2590 | if (!FElts) { |
| 2591 | // Discard LFilter. |
| 2592 | NewClauses.erase(J); |
| 2593 | MakeNewInstruction = true; |
| 2594 | // Move on to the next filter. |
| 2595 | continue; |
| 2596 | } |
| 2597 | unsigned LElts = LTy->getNumElements(); |
| 2598 | // If Filter is longer than LFilter then it cannot be a subset of it. |
| 2599 | if (FElts > LElts) |
| 2600 | // Move on to the next filter. |
| 2601 | continue; |
| 2602 | // At this point we know that LFilter has at least one element. |
| 2603 | if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 2604 | // Filter is a subset of LFilter iff Filter contains only zeros (as we |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2605 | // already know that Filter is not longer than LFilter). |
| 2606 | if (isa<ConstantAggregateZero>(Filter)) { |
| 2607 | assert(FElts <= LElts && "Should have handled this case earlier!"); |
| 2608 | // Discard LFilter. |
| 2609 | NewClauses.erase(J); |
| 2610 | MakeNewInstruction = true; |
| 2611 | } |
| 2612 | // Move on to the next filter. |
| 2613 | continue; |
| 2614 | } |
| 2615 | ConstantArray *LArray = cast<ConstantArray>(LFilter); |
| 2616 | if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. |
| 2617 | // Since Filter is non-empty and contains only zeros, it is a subset of |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 2618 | // LFilter iff LFilter contains a zero. |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2619 | assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); |
| 2620 | for (unsigned l = 0; l != LElts; ++l) |
| 2621 | if (LArray->getOperand(l)->isNullValue()) { |
| 2622 | // LFilter contains a zero - discard it. |
| 2623 | NewClauses.erase(J); |
| 2624 | MakeNewInstruction = true; |
| 2625 | break; |
| 2626 | } |
| 2627 | // Move on to the next filter. |
| 2628 | continue; |
| 2629 | } |
| 2630 | // At this point we know that both filters are ConstantArrays. Loop over |
| 2631 | // operands to see whether every element of Filter is also an element of |
| 2632 | // LFilter. Since filters tend to be short this is probably faster than |
| 2633 | // using a method that scales nicely. |
| 2634 | ConstantArray *FArray = cast<ConstantArray>(Filter); |
| 2635 | bool AllFound = true; |
| 2636 | for (unsigned f = 0; f != FElts; ++f) { |
| 2637 | Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); |
| 2638 | AllFound = false; |
| 2639 | for (unsigned l = 0; l != LElts; ++l) { |
| 2640 | Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); |
| 2641 | if (LTypeInfo == FTypeInfo) { |
| 2642 | AllFound = true; |
| 2643 | break; |
| 2644 | } |
| 2645 | } |
| 2646 | if (!AllFound) |
| 2647 | break; |
| 2648 | } |
| 2649 | if (AllFound) { |
| 2650 | // Discard LFilter. |
| 2651 | NewClauses.erase(J); |
| 2652 | MakeNewInstruction = true; |
| 2653 | } |
| 2654 | // Move on to the next filter. |
| 2655 | } |
| 2656 | } |
| 2657 | |
| 2658 | // If we changed any of the clauses, replace the old landingpad instruction |
| 2659 | // with a new one. |
| 2660 | if (MakeNewInstruction) { |
| 2661 | LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2662 | NewClauses.size()); |
| 2663 | for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) |
| 2664 | NLI->addClause(NewClauses[i]); |
| 2665 | // A landing pad with no clauses must have the cleanup flag set. It is |
| 2666 | // theoretically possible, though highly unlikely, that we eliminated all |
| 2667 | // clauses. If so, force the cleanup flag to true. |
| 2668 | if (NewClauses.empty()) |
| 2669 | CleanupFlag = true; |
| 2670 | NLI->setCleanup(CleanupFlag); |
| 2671 | return NLI; |
| 2672 | } |
| 2673 | |
| 2674 | // Even if none of the clauses changed, we may nonetheless have understood |
| 2675 | // that the cleanup flag is pointless. Clear it if so. |
| 2676 | if (LI.isCleanup() != CleanupFlag) { |
| 2677 | assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); |
| 2678 | LI.setCleanup(CleanupFlag); |
| 2679 | return &LI; |
| 2680 | } |
| 2681 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2682 | return nullptr; |
Duncan Sands | 5c05579 | 2011-09-30 13:12:16 +0000 | [diff] [blame] | 2683 | } |
| 2684 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 2685 | /// Try to move the specified instruction from its current block into the |
| 2686 | /// beginning of DestBlock, which can only happen if it's safe to move the |
| 2687 | /// instruction past all of the instructions between it and the end of its |
| 2688 | /// block. |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2689 | static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { |
| 2690 | assert(I->hasOneUse() && "Invariants didn't hold!"); |
| 2691 | |
Bill Wendling | e86965e | 2011-08-15 21:14:31 +0000 | [diff] [blame] | 2692 | // Cannot move control-flow-involving, volatile loads, vaarg, etc. |
David Majnemer | 60c994b | 2015-08-08 03:51:49 +0000 | [diff] [blame] | 2693 | if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || |
Bill Wendling | a9ee09f | 2011-08-17 20:36:44 +0000 | [diff] [blame] | 2694 | isa<TerminatorInst>(I)) |
Chris Lattner | a4ee1f5 | 2008-05-09 15:07:33 +0000 | [diff] [blame] | 2695 | return false; |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2696 | |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2697 | // Do not sink alloca instructions out of the entry block. |
Dan Gohman | dcb291f | 2007-03-22 16:38:57 +0000 | [diff] [blame] | 2698 | if (isa<AllocaInst>(I) && I->getParent() == |
| 2699 | &DestBlock->getParent()->getEntryBlock()) |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2700 | return false; |
| 2701 | |
Fiona Glaser | a8b653a | 2015-11-03 22:23:39 +0000 | [diff] [blame] | 2702 | // Do not sink convergent call instructions. |
| 2703 | if (auto *CI = dyn_cast<CallInst>(I)) { |
| 2704 | if (CI->isConvergent()) |
| 2705 | return false; |
| 2706 | } |
| 2707 | |
Chris Lattner | f17a2fb | 2004-12-09 07:14:34 +0000 | [diff] [blame] | 2708 | // We can only sink load instructions if there is nothing between the load and |
| 2709 | // the end of block that could change the value. |
Chris Lattner | 49a594e | 2008-05-08 17:37:37 +0000 | [diff] [blame] | 2710 | if (I->mayReadFromMemory()) { |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2711 | for (BasicBlock::iterator Scan = I->getIterator(), |
| 2712 | E = I->getParent()->end(); |
Chris Lattner | f17a2fb | 2004-12-09 07:14:34 +0000 | [diff] [blame] | 2713 | Scan != E; ++Scan) |
| 2714 | if (Scan->mayWriteToMemory()) |
| 2715 | return false; |
Chris Lattner | f17a2fb | 2004-12-09 07:14:34 +0000 | [diff] [blame] | 2716 | } |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2717 | |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 2718 | BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2719 | I->moveBefore(&*InsertPos); |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2720 | ++NumSunkInst; |
| 2721 | return true; |
| 2722 | } |
| 2723 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2724 | bool InstCombiner::run() { |
Chris Lattner | 97fd359 | 2009-08-30 05:55:36 +0000 | [diff] [blame] | 2725 | while (!Worklist.isEmpty()) { |
| 2726 | Instruction *I = Worklist.RemoveOne(); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 2727 | if (I == nullptr) continue; // skip null values. |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 2728 | |
Chris Lattner | 1443bc5 | 2006-05-11 17:11:52 +0000 | [diff] [blame] | 2729 | // Check to see if we can DCE the instruction. |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 2730 | if (isInstructionTriviallyDead(I, TLI)) { |
Matt Arsenault | e6db760 | 2013-09-05 19:48:28 +0000 | [diff] [blame] | 2731 | DEBUG(dbgs() << "IC: DCE: " << *I << '\n'); |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2732 | EraseInstFromFunction(*I); |
| 2733 | ++NumDeadInst; |
Chris Lattner | ff5f1e4 | 2009-08-31 06:57:37 +0000 | [diff] [blame] | 2734 | MadeIRChange = true; |
Chris Lattner | e8ed4ef | 2003-10-06 17:11:01 +0000 | [diff] [blame] | 2735 | continue; |
| 2736 | } |
Chris Lattner | 99f48c6 | 2002-09-02 04:59:56 +0000 | [diff] [blame] | 2737 | |
Chris Lattner | 1443bc5 | 2006-05-11 17:11:52 +0000 | [diff] [blame] | 2738 | // Instruction isn't dead, see if we can constant propagate it. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 2739 | if (!I->use_empty() && |
| 2740 | (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 2741 | if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) { |
Matt Arsenault | e6db760 | 2013-09-05 19:48:28 +0000 | [diff] [blame] | 2742 | DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n'); |
Chris Lattner | cd517ff | 2005-01-28 19:32:01 +0000 | [diff] [blame] | 2743 | |
Chris Lattner | dd1f68a | 2009-10-15 04:13:44 +0000 | [diff] [blame] | 2744 | // Add operands to the worklist. |
| 2745 | ReplaceInstUsesWith(*I, C); |
| 2746 | ++NumConstProp; |
| 2747 | EraseInstFromFunction(*I); |
| 2748 | MadeIRChange = true; |
| 2749 | continue; |
| 2750 | } |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2751 | } |
Chris Lattner | e8ed4ef | 2003-10-06 17:11:01 +0000 | [diff] [blame] | 2752 | |
Hal Finkel | f2199b2 | 2015-10-23 20:37:08 +0000 | [diff] [blame] | 2753 | // In general, it is possible for computeKnownBits to determine all bits in a |
| 2754 | // value even when the operands are not all constants. |
| 2755 | if (!I->use_empty() && I->getType()->isIntegerTy()) { |
| 2756 | unsigned BitWidth = I->getType()->getScalarSizeInBits(); |
| 2757 | APInt KnownZero(BitWidth, 0); |
| 2758 | APInt KnownOne(BitWidth, 0); |
| 2759 | computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I); |
| 2760 | if ((KnownZero | KnownOne).isAllOnesValue()) { |
| 2761 | Constant *C = ConstantInt::get(I->getContext(), KnownOne); |
| 2762 | DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C << |
| 2763 | " from: " << *I << '\n'); |
| 2764 | |
| 2765 | // Add operands to the worklist. |
| 2766 | ReplaceInstUsesWith(*I, C); |
| 2767 | ++NumConstProp; |
| 2768 | EraseInstFromFunction(*I); |
| 2769 | MadeIRChange = true; |
| 2770 | continue; |
| 2771 | } |
| 2772 | } |
| 2773 | |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2774 | // See if we can trivially sink this instruction to a successor basic block. |
Dan Gohman | fa1211f | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 2775 | if (I->hasOneUse()) { |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2776 | BasicBlock *BB = I->getParent(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2777 | Instruction *UserInst = cast<Instruction>(*I->user_begin()); |
Chris Lattner | 6b9044d | 2009-10-14 15:21:58 +0000 | [diff] [blame] | 2778 | BasicBlock *UserParent; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2779 | |
Chris Lattner | 6b9044d | 2009-10-14 15:21:58 +0000 | [diff] [blame] | 2780 | // Get the block the use occurs in. |
| 2781 | if (PHINode *PN = dyn_cast<PHINode>(UserInst)) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2782 | UserParent = PN->getIncomingBlock(*I->use_begin()); |
Chris Lattner | 6b9044d | 2009-10-14 15:21:58 +0000 | [diff] [blame] | 2783 | else |
| 2784 | UserParent = UserInst->getParent(); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2785 | |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2786 | if (UserParent != BB) { |
| 2787 | bool UserIsSuccessor = false; |
| 2788 | // See if the user is one of our successors. |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2789 | for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) |
| 2790 | if (*SI == UserParent) { |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2791 | UserIsSuccessor = true; |
| 2792 | break; |
| 2793 | } |
| 2794 | |
| 2795 | // If the user is one of our immediate successors, and if that successor |
| 2796 | // only has us as a predecessors (we'd have to split the critical edge |
| 2797 | // otherwise), we can keep going. |
Aditya Nandakumar | 0b5a674 | 2014-07-11 21:49:39 +0000 | [diff] [blame] | 2798 | if (UserIsSuccessor && UserParent->getSinglePredecessor()) { |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2799 | // Okay, the CFG is simple enough, try to sink this instruction. |
Aditya Nandakumar | 0b5a674 | 2014-07-11 21:49:39 +0000 | [diff] [blame] | 2800 | if (TryToSinkInstruction(I, UserParent)) { |
| 2801 | MadeIRChange = true; |
| 2802 | // We'll add uses of the sunk instruction below, but since sinking |
| 2803 | // can expose opportunities for it's *operands* add them to the |
| 2804 | // worklist |
| 2805 | for (Use &U : I->operands()) |
| 2806 | if (Instruction *OpI = dyn_cast<Instruction>(U.get())) |
| 2807 | Worklist.Add(OpI); |
| 2808 | } |
| 2809 | } |
Chris Lattner | 39c98bb | 2004-12-08 23:43:58 +0000 | [diff] [blame] | 2810 | } |
| 2811 | } |
| 2812 | |
Chris Lattner | 022a582 | 2009-08-30 07:44:24 +0000 | [diff] [blame] | 2813 | // Now that we have an instruction, try combining it to simplify it. |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2814 | Builder->SetInsertPoint(I); |
Eli Friedman | 96254a0 | 2011-05-18 01:28:27 +0000 | [diff] [blame] | 2815 | Builder->SetCurrentDebugLocation(I->getDebugLoc()); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2816 | |
Reid Spencer | 755d0e7 | 2007-03-26 17:44:01 +0000 | [diff] [blame] | 2817 | #ifndef NDEBUG |
| 2818 | std::string OrigI; |
| 2819 | #endif |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2820 | DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); |
Matt Arsenault | e6db760 | 2013-09-05 19:48:28 +0000 | [diff] [blame] | 2821 | DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); |
Jeffrey Yasskin | dafd08e | 2009-10-08 00:12:24 +0000 | [diff] [blame] | 2822 | |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 2823 | if (Instruction *Result = visit(*I)) { |
Chris Lattner | 0b18c1d | 2002-05-10 15:38:35 +0000 | [diff] [blame] | 2824 | ++NumCombined; |
Chris Lattner | 260ab20 | 2002-04-18 17:39:14 +0000 | [diff] [blame] | 2825 | // Should we replace the old instruction with a new one? |
Chris Lattner | 053c093 | 2002-05-14 15:24:07 +0000 | [diff] [blame] | 2826 | if (Result != I) { |
Matt Arsenault | e6db760 | 2013-09-05 19:48:28 +0000 | [diff] [blame] | 2827 | DEBUG(dbgs() << "IC: Old = " << *I << '\n' |
Jim Grosbach | 8f9acfa | 2011-10-05 20:44:29 +0000 | [diff] [blame] | 2828 | << " New = " << *Result << '\n'); |
| 2829 | |
Duncan P. N. Exon Smith | ec819c0 | 2015-03-30 19:49:49 +0000 | [diff] [blame] | 2830 | if (I->getDebugLoc()) |
Eli Friedman | 35211c6 | 2011-05-27 00:19:40 +0000 | [diff] [blame] | 2831 | Result->setDebugLoc(I->getDebugLoc()); |
Chris Lattner | 396dbfe | 2004-06-09 05:08:07 +0000 | [diff] [blame] | 2832 | // Everything uses the new instruction now. |
| 2833 | I->replaceAllUsesWith(Result); |
| 2834 | |
Jim Grosbach | e7abae0 | 2011-10-05 20:53:43 +0000 | [diff] [blame] | 2835 | // Move the name to the new instruction first. |
| 2836 | Result->takeName(I); |
| 2837 | |
Jim Grosbach | 8f9acfa | 2011-10-05 20:44:29 +0000 | [diff] [blame] | 2838 | // Push the new instruction and any users onto the worklist. |
| 2839 | Worklist.Add(Result); |
| 2840 | Worklist.AddUsersToWorkList(*Result); |
| 2841 | |
Chris Lattner | e8ed4ef | 2003-10-06 17:11:01 +0000 | [diff] [blame] | 2842 | // Insert the new instruction into the basic block... |
| 2843 | BasicBlock *InstParent = I->getParent(); |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2844 | BasicBlock::iterator InsertPos = I->getIterator(); |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 2845 | |
Eli Friedman | a49b828 | 2011-11-01 04:49:29 +0000 | [diff] [blame] | 2846 | // If we replace a PHI with something that isn't a PHI, fix up the |
| 2847 | // insertion point. |
| 2848 | if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos)) |
| 2849 | InsertPos = InstParent->getFirstInsertionPt(); |
Chris Lattner | 7515cab | 2004-11-14 19:13:23 +0000 | [diff] [blame] | 2850 | |
| 2851 | InstParent->getInstList().insert(InsertPos, Result); |
Chris Lattner | e8ed4ef | 2003-10-06 17:11:01 +0000 | [diff] [blame] | 2852 | |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2853 | EraseInstFromFunction(*I); |
Chris Lattner | 113f4f4 | 2002-06-25 16:13:24 +0000 | [diff] [blame] | 2854 | } else { |
Evan Cheng | a4ed8a5 | 2007-03-27 16:44:48 +0000 | [diff] [blame] | 2855 | #ifndef NDEBUG |
Matt Arsenault | e6db760 | 2013-09-05 19:48:28 +0000 | [diff] [blame] | 2856 | DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 2857 | << " New = " << *I << '\n'); |
Evan Cheng | a4ed8a5 | 2007-03-27 16:44:48 +0000 | [diff] [blame] | 2858 | #endif |
Chris Lattner | 7d2a539 | 2004-03-13 23:54:27 +0000 | [diff] [blame] | 2859 | |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 2860 | // If the instruction was modified, it's possible that it is now dead. |
| 2861 | // if so, remove it. |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 2862 | if (isInstructionTriviallyDead(I, TLI)) { |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2863 | EraseInstFromFunction(*I); |
Chris Lattner | 396dbfe | 2004-06-09 05:08:07 +0000 | [diff] [blame] | 2864 | } else { |
Chris Lattner | 905976b | 2009-08-30 06:13:40 +0000 | [diff] [blame] | 2865 | Worklist.Add(I); |
Chris Lattner | bacd05c | 2009-08-30 06:22:51 +0000 | [diff] [blame] | 2866 | Worklist.AddUsersToWorkList(*I); |
Chris Lattner | ae7a0d3 | 2002-08-02 19:29:35 +0000 | [diff] [blame] | 2867 | } |
Chris Lattner | 053c093 | 2002-05-14 15:24:07 +0000 | [diff] [blame] | 2868 | } |
Chris Lattner | ff5f1e4 | 2009-08-31 06:57:37 +0000 | [diff] [blame] | 2869 | MadeIRChange = true; |
Chris Lattner | ca08125 | 2001-12-14 16:52:21 +0000 | [diff] [blame] | 2870 | } |
| 2871 | } |
| 2872 | |
Chris Lattner | 97fd359 | 2009-08-30 05:55:36 +0000 | [diff] [blame] | 2873 | Worklist.Zap(); |
Chris Lattner | ff5f1e4 | 2009-08-31 06:57:37 +0000 | [diff] [blame] | 2874 | return MadeIRChange; |
Chris Lattner | 04805fa | 2002-02-26 21:46:54 +0000 | [diff] [blame] | 2875 | } |
| 2876 | |
Sanjay Patel | 84dca49 | 2015-09-21 15:33:26 +0000 | [diff] [blame] | 2877 | /// Walk the function in depth-first order, adding all reachable code to the |
| 2878 | /// worklist. |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2879 | /// |
| 2880 | /// This has a couple of tricks to make the code faster and more powerful. In |
| 2881 | /// particular, we constant fold and DCE instructions as we go, to avoid adding |
| 2882 | /// them to the worklist (this significantly speeds up instcombine on code where |
| 2883 | /// many instructions are dead or constant). Additionally, if we find a branch |
| 2884 | /// whose condition is a known constant, we only visit the reachable successors. |
| 2885 | /// |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2886 | static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, |
| 2887 | SmallPtrSetImpl<BasicBlock *> &Visited, |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2888 | InstCombineWorklist &ICWorklist, |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2889 | const TargetLibraryInfo *TLI) { |
| 2890 | bool MadeIRChange = false; |
| 2891 | SmallVector<BasicBlock*, 256> Worklist; |
| 2892 | Worklist.push_back(BB); |
Hal Finkel | 60db058 | 2014-09-07 18:57:58 +0000 | [diff] [blame] | 2893 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2894 | SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; |
| 2895 | DenseMap<ConstantExpr*, Constant*> FoldedConstants; |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2896 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2897 | do { |
| 2898 | BB = Worklist.pop_back_val(); |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2899 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2900 | // We have now visited this block! If we've already been here, ignore it. |
| 2901 | if (!Visited.insert(BB).second) |
| 2902 | continue; |
Chris Lattner | 960a543 | 2007-03-03 02:04:50 +0000 | [diff] [blame] | 2903 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2904 | for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 2905 | Instruction *Inst = &*BBI++; |
Devang Patel | aad34d8 | 2011-03-17 22:18:16 +0000 | [diff] [blame] | 2906 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2907 | // DCE instruction if trivially dead. |
| 2908 | if (isInstructionTriviallyDead(Inst, TLI)) { |
| 2909 | ++NumDeadInst; |
| 2910 | DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); |
| 2911 | Inst->eraseFromParent(); |
| 2912 | continue; |
| 2913 | } |
Jakub Staszak | cfc46f8 | 2012-05-06 13:52:31 +0000 | [diff] [blame] | 2914 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2915 | // ConstantProp instruction if trivially constant. |
David Majnemer | 7fddecc | 2015-06-17 20:52:32 +0000 | [diff] [blame] | 2916 | if (!Inst->use_empty() && |
| 2917 | (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2918 | if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { |
| 2919 | DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " |
| 2920 | << *Inst << '\n'); |
| 2921 | Inst->replaceAllUsesWith(C); |
| 2922 | ++NumConstProp; |
| 2923 | Inst->eraseFromParent(); |
| 2924 | continue; |
| 2925 | } |
| 2926 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2927 | // See if we can constant fold its operands. |
| 2928 | for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e; |
| 2929 | ++i) { |
| 2930 | ConstantExpr *CE = dyn_cast<ConstantExpr>(i); |
| 2931 | if (CE == nullptr) |
| 2932 | continue; |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2933 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2934 | Constant *&FoldRes = FoldedConstants[CE]; |
| 2935 | if (!FoldRes) |
| 2936 | FoldRes = ConstantFoldConstantExpression(CE, DL, TLI); |
| 2937 | if (!FoldRes) |
| 2938 | FoldRes = CE; |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2939 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2940 | if (FoldRes != CE) { |
| 2941 | *i = FoldRes; |
| 2942 | MadeIRChange = true; |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2943 | } |
| 2944 | } |
| 2945 | |
| 2946 | InstrsForInstCombineWorklist.push_back(Inst); |
| 2947 | } |
| 2948 | |
| 2949 | // Recursively visit successors. If this is a branch or switch on a |
| 2950 | // constant, only visit the reachable successor. |
| 2951 | TerminatorInst *TI = BB->getTerminator(); |
| 2952 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 2953 | if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { |
| 2954 | bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); |
| 2955 | BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); |
| 2956 | Worklist.push_back(ReachableBB); |
| 2957 | continue; |
| 2958 | } |
| 2959 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 2960 | if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { |
| 2961 | // See if this is an explicit destination. |
| 2962 | for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); |
| 2963 | i != e; ++i) |
| 2964 | if (i.getCaseValue() == Cond) { |
| 2965 | BasicBlock *ReachableBB = i.getCaseSuccessor(); |
| 2966 | Worklist.push_back(ReachableBB); |
| 2967 | continue; |
| 2968 | } |
| 2969 | |
| 2970 | // Otherwise it is the default destination. |
| 2971 | Worklist.push_back(SI->getDefaultDest()); |
| 2972 | continue; |
| 2973 | } |
| 2974 | } |
| 2975 | |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 2976 | for (BasicBlock *SuccBB : TI->successors()) |
| 2977 | Worklist.push_back(SuccBB); |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2978 | } while (!Worklist.empty()); |
| 2979 | |
| 2980 | // Once we've found all of the instructions to add to instcombine's worklist, |
| 2981 | // add them in reverse order. This way instcombine will visit from the top |
| 2982 | // of the function down. This jives well with the way that it adds all uses |
| 2983 | // of instructions to the worklist after doing a transformation, thus avoiding |
| 2984 | // some N^2 behavior in pathological cases. |
Craig Topper | 42526d3 | 2015-10-22 16:35:56 +0000 | [diff] [blame] | 2985 | ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist); |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2986 | |
| 2987 | return MadeIRChange; |
| 2988 | } |
| 2989 | |
| 2990 | /// \brief Populate the IC worklist from a function, and prune any dead basic |
| 2991 | /// blocks discovered in the process. |
| 2992 | /// |
| 2993 | /// This also does basic constant propagation and other forward fixing to make |
| 2994 | /// the combiner itself run much faster. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2995 | static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 2996 | TargetLibraryInfo *TLI, |
| 2997 | InstCombineWorklist &ICWorklist) { |
| 2998 | bool MadeIRChange = false; |
| 2999 | |
| 3000 | // Do a depth-first traversal of the function, populate the worklist with |
| 3001 | // the reachable instructions. Ignore blocks that are not reachable. Keep |
| 3002 | // track of which blocks we visit. |
| 3003 | SmallPtrSet<BasicBlock *, 64> Visited; |
| 3004 | MadeIRChange |= |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 3005 | AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI); |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3006 | |
| 3007 | // Do a quick scan over the function. If we find any blocks that are |
| 3008 | // unreachable, remove any instructions inside of them. This prevents |
| 3009 | // the instcombine code from having to deal with some bad special cases. |
| 3010 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 3011 | if (Visited.count(&*BB)) |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3012 | continue; |
| 3013 | |
| 3014 | // Delete the instructions backwards, as it has a reduced likelihood of |
| 3015 | // having to update as many def-use and use-def chains. |
| 3016 | Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. |
| 3017 | while (EndInst != BB->begin()) { |
| 3018 | // Delete the next to last instruction. |
Duncan P. N. Exon Smith | 9f8aaf2 | 2015-10-13 16:59:33 +0000 | [diff] [blame] | 3019 | Instruction *Inst = &*--EndInst->getIterator(); |
David Majnemer | 7204cff0a | 2015-11-06 21:26:32 +0000 | [diff] [blame] | 3020 | if (!Inst->use_empty() && !Inst->getType()->isTokenTy()) |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3021 | Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); |
David Majnemer | 60c994b | 2015-08-08 03:51:49 +0000 | [diff] [blame] | 3022 | if (Inst->isEHPad()) { |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3023 | EndInst = Inst; |
| 3024 | continue; |
| 3025 | } |
| 3026 | if (!isa<DbgInfoIntrinsic>(Inst)) { |
| 3027 | ++NumDeadInst; |
| 3028 | MadeIRChange = true; |
| 3029 | } |
David Majnemer | 7204cff0a | 2015-11-06 21:26:32 +0000 | [diff] [blame] | 3030 | if (!Inst->getType()->isTokenTy()) |
| 3031 | Inst->eraseFromParent(); |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3032 | } |
| 3033 | } |
| 3034 | |
| 3035 | return MadeIRChange; |
Chris Lattner | 960a543 | 2007-03-03 02:04:50 +0000 | [diff] [blame] | 3036 | } |
| 3037 | |
Mehdi Amini | 46a4355 | 2015-03-04 18:43:29 +0000 | [diff] [blame] | 3038 | static bool |
| 3039 | combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist, |
Bjorn Steinbrink | 8350534 | 2015-07-10 06:55:49 +0000 | [diff] [blame] | 3040 | AliasAnalysis *AA, AssumptionCache &AC, |
| 3041 | TargetLibraryInfo &TLI, DominatorTree &DT, |
| 3042 | LoopInfo *LI = nullptr) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3043 | auto &DL = F.getParent()->getDataLayout(); |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3044 | |
| 3045 | /// Builder - This is an IRBuilder that automatically inserts new |
| 3046 | /// instructions into the worklist when they are created. |
| 3047 | IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder( |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3048 | F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC)); |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3049 | |
| 3050 | // Lower dbg.declare intrinsics otherwise their value may be clobbered |
| 3051 | // by instcombiner. |
| 3052 | bool DbgDeclaresChanged = LowerDbgDeclare(F); |
| 3053 | |
| 3054 | // Iterate while there is work to do. |
| 3055 | int Iteration = 0; |
| 3056 | for (;;) { |
| 3057 | ++Iteration; |
| 3058 | DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " |
| 3059 | << F.getName() << "\n"); |
| 3060 | |
| 3061 | bool Changed = false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3062 | if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist)) |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3063 | Changed = true; |
| 3064 | |
Sanjay Patel | 1cd6d88 | 2015-08-18 16:44:23 +0000 | [diff] [blame] | 3065 | InstCombiner IC(Worklist, &Builder, F.optForMinSize(), |
Bjorn Steinbrink | 8350534 | 2015-07-10 06:55:49 +0000 | [diff] [blame] | 3066 | AA, &AC, &TLI, &DT, DL, LI); |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3067 | if (IC.run()) |
| 3068 | Changed = true; |
| 3069 | |
| 3070 | if (!Changed) |
| 3071 | break; |
| 3072 | } |
| 3073 | |
| 3074 | return DbgDeclaresChanged || Iteration > 1; |
| 3075 | } |
| 3076 | |
| 3077 | PreservedAnalyses InstCombinePass::run(Function &F, |
| 3078 | AnalysisManager<Function> *AM) { |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3079 | auto &AC = AM->getResult<AssumptionAnalysis>(F); |
| 3080 | auto &DT = AM->getResult<DominatorTreeAnalysis>(F); |
| 3081 | auto &TLI = AM->getResult<TargetLibraryAnalysis>(F); |
| 3082 | |
| 3083 | auto *LI = AM->getCachedResult<LoopAnalysis>(F); |
| 3084 | |
Bjorn Steinbrink | 8350534 | 2015-07-10 06:55:49 +0000 | [diff] [blame] | 3085 | // FIXME: The AliasAnalysis is not yet supported in the new pass manager |
| 3086 | if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI)) |
Chandler Carruth | 83ba269 | 2015-01-24 04:19:17 +0000 | [diff] [blame] | 3087 | // No changes, all analyses are preserved. |
| 3088 | return PreservedAnalyses::all(); |
| 3089 | |
| 3090 | // Mark all the analyses that instcombine updates as preserved. |
| 3091 | // FIXME: Need a way to preserve CFG analyses here! |
| 3092 | PreservedAnalyses PA; |
| 3093 | PA.preserve<DominatorTreeAnalysis>(); |
| 3094 | return PA; |
| 3095 | } |
| 3096 | |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3097 | namespace { |
| 3098 | /// \brief The legacy pass manager's instcombine pass. |
| 3099 | /// |
| 3100 | /// This is a basic whole-function wrapper around the instcombine utility. It |
| 3101 | /// will try to combine all instructions in the function. |
| 3102 | class InstructionCombiningPass : public FunctionPass { |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3103 | InstCombineWorklist Worklist; |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3104 | |
| 3105 | public: |
| 3106 | static char ID; // Pass identification, replacement for typeid |
| 3107 | |
| 3108 | InstructionCombiningPass() : FunctionPass(ID) { |
| 3109 | initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); |
| 3110 | } |
| 3111 | |
| 3112 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
| 3113 | bool runOnFunction(Function &F) override; |
| 3114 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 3115 | } |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3116 | |
| 3117 | void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 3118 | AU.setPreservesCFG(); |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 3119 | AU.addRequired<AAResultsWrapperPass>(); |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3120 | AU.addRequired<AssumptionCacheTracker>(); |
| 3121 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 3122 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 3123 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 3124 | AU.addPreserved<GlobalsAAWrapperPass>(); |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3125 | } |
| 3126 | |
| 3127 | bool InstructionCombiningPass::runOnFunction(Function &F) { |
| 3128 | if (skipOptnoneFunction(F)) |
| 3129 | return false; |
| 3130 | |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3131 | // Required analyses. |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 3132 | auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3133 | auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3134 | auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 3135 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Chandler Carruth | df5747a | 2015-01-21 11:38:17 +0000 | [diff] [blame] | 3136 | |
| 3137 | // Optional analyses. |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3138 | auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); |
| 3139 | auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; |
| 3140 | |
Bjorn Steinbrink | 8350534 | 2015-07-10 06:55:49 +0000 | [diff] [blame] | 3141 | return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI); |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3142 | } |
| 3143 | |
| 3144 | char InstructionCombiningPass::ID = 0; |
| 3145 | INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", |
| 3146 | "Combine redundant instructions", false, false) |
| 3147 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 3148 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 3149 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 3150 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
| 3151 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3152 | INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", |
| 3153 | "Combine redundant instructions", false, false) |
| 3154 | |
| 3155 | // Initialization Routines |
| 3156 | void llvm::initializeInstCombine(PassRegistry &Registry) { |
| 3157 | initializeInstructionCombiningPassPass(Registry); |
| 3158 | } |
| 3159 | |
| 3160 | void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { |
| 3161 | initializeInstructionCombiningPassPass(*unwrap(R)); |
| 3162 | } |
| 3163 | |
Brian Gaeke | 38b79e8 | 2004-07-27 17:43:21 +0000 | [diff] [blame] | 3164 | FunctionPass *llvm::createInstructionCombiningPass() { |
Chandler Carruth | 1edb9d6 | 2015-01-20 22:44:35 +0000 | [diff] [blame] | 3165 | return new InstructionCombiningPass(); |
Chris Lattner | 04805fa | 2002-02-26 21:46:54 +0000 | [diff] [blame] | 3166 | } |