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