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