blob: b3cf01342bd48dbaa8ac87834ff986b7c8f4beb2 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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 Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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 Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000050#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000053#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000054#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000058#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000059#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000062
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000067
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Dan Gohman844731a2008-05-13 00:00:25 +000069char InstCombiner::ID = 0;
70static RegisterPass<InstCombiner>
71X("instcombine", "Combine redundant instructions");
72
Chris Lattnere0b4b722010-01-04 07:17:19 +000073void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addPreservedID(LCSSAID);
75 AU.setPreservesCFG();
76}
77
78
Chris Lattnerc22d4d12009-11-10 07:23:37 +000079/// ShouldChangeType - Return true if it is desirable to convert a computation
80/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
81/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000082bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000083 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
84
85 // If we don't have TD, we don't know if the source/dest are legal.
86 if (!TD) return false;
87
88 unsigned FromWidth = From->getPrimitiveSizeInBits();
89 unsigned ToWidth = To->getPrimitiveSizeInBits();
90 bool FromLegal = TD->isLegalInteger(FromWidth);
91 bool ToLegal = TD->isLegalInteger(ToWidth);
92
93 // If this is a legal integer from type, and the result would be an illegal
94 // type, don't do the transformation.
95 if (FromLegal && !ToLegal)
96 return false;
97
98 // Otherwise, if both are illegal, do not increase the size of the result. We
99 // do allow things like i160 -> i64, but not i64 -> i160.
100 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
101 return false;
102
103 return true;
104}
105
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000106/// getBitCastOperand - If the specified operand is a CastInst, a constant
107/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
108/// operand value, otherwise return null.
Chris Lattner753a2b42010-01-05 07:32:13 +0000109
110// FIXME: Value::stripPointerCasts
Reid Spencer3da59db2006-11-27 01:05:10 +0000111static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000112 if (Operator *O = dyn_cast<Operator>(V)) {
113 if (O->getOpcode() == Instruction::BitCast)
114 return O->getOperand(0);
115 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
116 if (GEP->hasAllZeroIndices())
117 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000118 }
Chris Lattnereed48272005-09-13 00:40:14 +0000119 return 0;
120}
121
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000122
Chris Lattner33a61132006-05-06 09:00:16 +0000123
Chris Lattner4f98c562003-03-10 21:43:22 +0000124// SimplifyCommutative - This performs a few simplifications for commutative
125// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126//
Chris Lattner4f98c562003-03-10 21:43:22 +0000127// 1. Order operands such that they are listed from right (least complex) to
128// left (most complex). This puts constants before unary operators before
129// binary operators.
130//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000131// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
132// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000133//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000134bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000135 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000136 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000137 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000138
Chris Lattner4f98c562003-03-10 21:43:22 +0000139 if (!I.isAssociative()) return Changed;
Chris Lattner248a84b2010-01-05 07:04:23 +0000140
Chris Lattner4f98c562003-03-10 21:43:22 +0000141 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000142 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
143 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
144 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000145 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000146 cast<Constant>(I.getOperand(1)),
147 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000148 I.setOperand(0, Op->getOperand(0));
149 I.setOperand(1, Folded);
150 return true;
Chris Lattner248a84b2010-01-05 07:04:23 +0000151 }
152
153 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000154 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner248a84b2010-01-05 07:04:23 +0000155 Op->hasOneUse() && Op1->hasOneUse()) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000156 Constant *C1 = cast<Constant>(Op->getOperand(1));
157 Constant *C2 = cast<Constant>(Op1->getOperand(1));
158
159 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000160 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000161 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000162 Op1->getOperand(0),
163 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000164 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000165 I.setOperand(0, New);
166 I.setOperand(1, Folded);
167 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000169 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000170 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000171}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000172
Chris Lattner8d969642003-03-10 23:06:50 +0000173// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
174// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000175//
Chris Lattner02446fc2010-01-04 07:37:31 +0000176Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000177 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000178 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000179
Chris Lattner0ce85802004-12-14 20:08:06 +0000180 // Constants can be considered to be negated values if they can be folded.
181 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000182 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000183
184 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
185 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000186 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000187
Chris Lattner8d969642003-03-10 23:06:50 +0000188 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000189}
190
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000191// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
192// instruction if the LHS is a constant negative zero (which is the 'negate'
193// form).
194//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000195Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000196 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000197 return BinaryOperator::getFNegArgument(V);
198
199 // Constants can be considered to be negated values if they can be folded.
200 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000201 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000202
203 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
204 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000205 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206
207 return 0;
208}
209
Chris Lattner48b59ec2009-10-26 15:40:07 +0000210/// isFreeToInvert - Return true if the specified value is free to invert (apply
211/// ~ to). This happens in cases where the ~ can be eliminated.
212static inline bool isFreeToInvert(Value *V) {
213 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000214 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000215 return true;
216
217 // Constants can be considered to be not'ed values.
218 if (isa<ConstantInt>(V))
219 return true;
220
221 // Compares can be inverted if they have a single use.
222 if (CmpInst *CI = dyn_cast<CmpInst>(V))
223 return CI->hasOneUse();
224
225 return false;
226}
227
228static inline Value *dyn_castNotVal(Value *V) {
229 // If this is not(not(x)) don't return that this is a not: we want the two
230 // not's to be folded first.
231 if (BinaryOperator::isNot(V)) {
232 Value *Operand = BinaryOperator::getNotArgument(V);
233 if (!isFreeToInvert(Operand))
234 return Operand;
235 }
Chris Lattner8d969642003-03-10 23:06:50 +0000236
237 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000238 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000239 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000240 return 0;
241}
242
Chris Lattner48b59ec2009-10-26 15:40:07 +0000243
244
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000245/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000246static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000247 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000248}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000249/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000250static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000251 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000252}
Reid Spencere7816b52007-03-08 01:52:58 +0000253
Dan Gohman45b4e482008-05-19 22:14:15 +0000254
Chris Lattner6e7ba452005-01-01 16:22:27 +0000255static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000256 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000257 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000258 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000259
Chris Lattner2eefe512004-04-09 19:05:30 +0000260 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000261 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
262 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000263
Chris Lattner2eefe512004-04-09 19:05:30 +0000264 if (Constant *SOC = dyn_cast<Constant>(SO)) {
265 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000266 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
267 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000268 }
269
270 Value *Op0 = SO, *Op1 = ConstOperand;
271 if (!ConstIsRHS)
272 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000273
Chris Lattner6e7ba452005-01-01 16:22:27 +0000274 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000275 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
276 SO->getName()+".op");
277 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
278 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
279 SO->getName()+".cmp");
280 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
281 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
282 SO->getName()+".cmp");
283 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000284}
285
286// FoldOpIntoSelect - Given an instruction with a select as one operand and a
287// constant as the other operand, try to fold the binary operator into the
288// select arguments. This also works for Cast instructions, which obviously do
289// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000290Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000291 // Don't modify shared select instructions
292 if (!SI->hasOneUse()) return 0;
293 Value *TV = SI->getOperand(1);
294 Value *FV = SI->getOperand(2);
295
296 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000297 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000298 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000299
Chris Lattner80f43d32010-01-04 07:53:58 +0000300 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
301 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000302
Gabor Greif051a9502008-04-06 20:25:17 +0000303 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
304 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000305 }
306 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000307}
308
Chris Lattner4e998b22004-09-29 05:07:12 +0000309
Chris Lattner5d1704d2009-09-27 19:57:57 +0000310/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
311/// has a PHI node as operand #0, see if we can fold the instruction into the
312/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000313///
314/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
315/// that would normally be unprofitable because they strongly encourage jump
316/// threading.
317Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
318 bool AllowAggressive) {
319 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000320 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000321 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000322 if (NumPHIValues == 0 ||
323 // We normally only transform phis with a single use, unless we're trying
324 // hard to make jump threading happen.
325 (!PN->hasOneUse() && !AllowAggressive))
326 return 0;
327
328
Chris Lattner5d1704d2009-09-27 19:57:57 +0000329 // Check to see if all of the operands of the PHI are simple constants
330 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000331 // remember the BB it is in. If there is more than one or if *it* is a PHI,
332 // bail out. We don't do arbitrary constant expressions here because moving
333 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000334 BasicBlock *NonConstBB = 0;
335 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000336 if (!isa<Constant>(PN->getIncomingValue(i)) ||
337 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000338 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000339 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000340 NonConstBB = PN->getIncomingBlock(i);
341
342 // If the incoming non-constant value is in I's block, we have an infinite
343 // loop.
344 if (NonConstBB == I.getParent())
345 return 0;
346 }
347
348 // If there is exactly one non-constant value, we can insert a copy of the
349 // operation in that block. However, if this is a critical edge, we would be
350 // inserting the computation one some other paths (e.g. inside a loop). Only
351 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000352 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000353 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
354 if (!BI || !BI->isUnconditional()) return 0;
355 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000356
357 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000358 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000359 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000360 InsertNewInstBefore(NewPN, *PN);
361 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000362
363 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000364 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
365 // We only currently try to fold the condition of a select when it is a phi,
366 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000367 Value *TrueV = SI->getTrueValue();
368 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000369 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000370 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000371 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000372 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
373 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000374 Value *InV = 0;
375 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000376 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000377 } else {
378 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000379 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
380 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000381 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000382 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000383 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000384 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000385 }
386 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000387 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000388 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000389 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000390 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000391 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000392 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000393 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000394 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000395 } else {
396 assert(PN->getIncomingBlock(i) == NonConstBB);
397 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000398 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000399 PN->getIncomingValue(i), C, "phitmp",
400 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000401 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000402 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000403 CI->getPredicate(),
404 PN->getIncomingValue(i), C, "phitmp",
405 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000406 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000407 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000408
409 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000410 }
411 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000412 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000413 } else {
414 CastInst *CI = cast<CastInst>(&I);
415 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000416 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000417 Value *InV;
418 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000419 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000420 } else {
421 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000422 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000423 I.getType(), "phitmp",
424 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000425 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000426 }
427 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000428 }
429 }
430 return ReplaceInstUsesWith(I, NewPN);
431}
432
Chris Lattner2454a2e2008-01-29 06:52:45 +0000433
Reid Spencere4d87aa2006-12-23 06:05:41 +0000434/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000435/// are carefully arranged to allow folding of expressions such as:
436///
437/// (A < B) | (A > B) --> (A != B)
438///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000439/// Note that this is only valid if the first and second predicates have the
440/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000441///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000442/// Three bits are used to represent the condition, as follows:
443/// 0 A > B
444/// 1 A == B
445/// 2 A < B
446///
447/// <=> Value Definition
448/// 000 0 Always false
449/// 001 1 A > B
450/// 010 2 A == B
451/// 011 3 A >= B
452/// 100 4 A < B
453/// 101 5 A != B
454/// 110 6 A <= B
455/// 111 7 Always true
456///
457static unsigned getICmpCode(const ICmpInst *ICI) {
458 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000459 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +0000460 case ICmpInst::ICMP_UGT: return 1; // 001
461 case ICmpInst::ICMP_SGT: return 1; // 001
462 case ICmpInst::ICMP_EQ: return 2; // 010
463 case ICmpInst::ICMP_UGE: return 3; // 011
464 case ICmpInst::ICMP_SGE: return 3; // 011
465 case ICmpInst::ICMP_ULT: return 4; // 100
466 case ICmpInst::ICMP_SLT: return 4; // 100
467 case ICmpInst::ICMP_NE: return 5; // 101
468 case ICmpInst::ICMP_ULE: return 6; // 110
469 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000470 // True -> 7
471 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000472 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000473 return 0;
474 }
475}
476
Evan Cheng8db90722008-10-14 17:15:11 +0000477/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
478/// predicate into a three bit mask. It also returns whether it is an ordered
479/// predicate by reference.
480static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
481 isOrdered = false;
482 switch (CC) {
483 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
484 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +0000485 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
486 case FCmpInst::FCMP_UGT: return 1; // 001
487 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
488 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +0000489 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
490 case FCmpInst::FCMP_UGE: return 3; // 011
491 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
492 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +0000493 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
494 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +0000495 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
496 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +0000497 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +0000498 default:
499 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +0000500 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +0000501 return 0;
502 }
503}
504
Reid Spencere4d87aa2006-12-23 06:05:41 +0000505/// getICmpValue - This is the complement of getICmpCode, which turns an
506/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +0000507/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +0000508/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +0000509static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
510 switch (Code) {
511 default: assert(0 && "Illegal ICmp code!");
512 case 0:
513 return ConstantInt::getFalse(LHS->getContext());
514 case 1:
515 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000516 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000517 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
518 case 2:
519 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
520 case 3:
521 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000522 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000523 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
524 case 4:
525 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000526 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000527 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
528 case 5:
529 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
530 case 6:
531 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000532 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000533 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
534 case 7:
535 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000536 }
537}
538
Evan Cheng8db90722008-10-14 17:15:11 +0000539/// getFCmpValue - This is the complement of getFCmpCode, which turns an
540/// opcode and two operands into either a FCmp instruction. isordered is passed
541/// in to determine which kind of predicate to use in the new fcmp instruction.
542static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +0000543 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +0000544 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000545 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +0000546 case 0:
547 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000548 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000549 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000550 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000551 case 1:
552 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000553 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000554 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000555 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000556 case 2:
557 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000558 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000559 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000560 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000561 case 3:
562 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000563 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000564 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000565 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000566 case 4:
567 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000568 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000569 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000570 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000571 case 5:
572 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000573 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000574 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000575 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000576 case 6:
577 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000578 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000579 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000580 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +0000581 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +0000582 }
583}
584
Chris Lattnerb9553d62008-11-16 04:55:20 +0000585/// PredicatesFoldable - Return true if both predicates match sign or if at
586/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +0000587static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +0000588 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
589 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
590 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000591}
592
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000593// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
594// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +0000595// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000596Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000597 ConstantInt *OpRHS,
598 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000599 BinaryOperator &TheAnd) {
600 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +0000601 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +0000602 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +0000604
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000605 switch (Op->getOpcode()) {
606 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000607 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000608 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +0000609 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000610 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000611 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000612 }
613 break;
614 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000615 if (Together == AndRHS) // (X | C) & C --> C
616 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +0000617
Chris Lattner6e7ba452005-01-01 16:22:27 +0000618 if (Op->hasOneUse() && Together != OpRHS) {
619 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +0000620 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +0000621 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000622 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000623 }
624 break;
625 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +0000626 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000627 // Adding a one to a single bit bit-field should be turned into an XOR
628 // of the bit. First thing to check is to see if this AND is with a
629 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000630 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000631
Chris Lattnerc6334b92010-01-05 06:03:12 +0000632 // If there is only one bit set.
633 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000634 // Ok, at this point, we know that we are masking the result of the
635 // ADD down to exactly one bit. If the constant we are adding has
636 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000637 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000638
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000639 // Check to see if any bits below the one bit set in AndRHSV are set.
640 if ((AddRHS & (AndRHSV-1)) == 0) {
641 // If not, the only thing that can effect the output of the AND is
642 // the bit specified by AndRHSV. If that bit is set, the effect of
643 // the XOR is to toggle the bit. If it is clear, then the ADD has
644 // no effect.
645 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
646 TheAnd.setOperand(0, X);
647 return &TheAnd;
648 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000649 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +0000650 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000651 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000652 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000653 }
654 }
655 }
656 }
657 break;
Chris Lattner62a355c2003-09-19 19:05:02 +0000658
659 case Instruction::Shl: {
660 // We know that the AND will not produce any of the bits shifted in, so if
661 // the anded constant includes them, clear them now!
662 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000663 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000664 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000665 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000666 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
667 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +0000668
Zhou Sheng290bec52007-03-29 08:15:12 +0000669 if (CI->getValue() == ShlMask) {
670 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +0000671 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
672 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +0000673 TheAnd.setOperand(1, CI);
674 return &TheAnd;
675 }
676 break;
Misha Brukmanfd939082005-04-21 23:48:37 +0000677 }
Chris Lattner4de84762010-01-04 07:02:48 +0000678 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +0000679 // We know that the AND will not produce any of the bits shifted in, so if
680 // the anded constant includes them, clear them now! This only applies to
681 // unsigned shifts, because a signed shr may bring in set bits!
682 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000683 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000684 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000685 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000686 ConstantInt *CI = ConstantInt::get(Op->getContext(),
687 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +0000688
Zhou Sheng290bec52007-03-29 08:15:12 +0000689 if (CI->getValue() == ShrMask) {
690 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +0000691 return ReplaceInstUsesWith(TheAnd, Op);
692 } else if (CI != AndRHS) {
693 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
694 return &TheAnd;
695 }
696 break;
697 }
698 case Instruction::AShr:
699 // Signed shr.
700 // See if this is shifting in some sign extension, then masking it out
701 // with an and.
702 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +0000703 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000704 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000705 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000706 Constant *C = ConstantInt::get(Op->getContext(),
707 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +0000708 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +0000709 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +0000710 // Make the argument unsigned.
711 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +0000712 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000713 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +0000714 }
Chris Lattner62a355c2003-09-19 19:05:02 +0000715 }
716 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000717 }
718 return 0;
719}
720
Chris Lattner8b170942002-08-09 23:47:40 +0000721
Chris Lattnera96879a2004-09-29 17:40:11 +0000722/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
723/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +0000724/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
725/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +0000726/// insert new instructions.
727Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000728 bool isSigned, bool Inside,
729 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000730 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +0000731 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +0000732 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000733
Chris Lattnera96879a2004-09-29 17:40:11 +0000734 if (Inside) {
735 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000736 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +0000737
Reid Spencere4d87aa2006-12-23 06:05:41 +0000738 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000739 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +0000740 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +0000741 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000742 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000743 }
744
745 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +0000746 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +0000747 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000748 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000749 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000750 }
751
752 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000753 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +0000754
Reid Spencere4e40032007-03-21 23:19:50 +0000755 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +0000756 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000757 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000758 ICmpInst::Predicate pred = (isSigned ?
759 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000760 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000761 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000762
Reid Spencere4e40032007-03-21 23:19:50 +0000763 // Emit V-Lo >u Hi-1-Lo
764 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000765 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +0000766 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000767 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000768 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000769}
770
Chris Lattner7203e152005-09-18 07:22:02 +0000771// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
772// any number of 0s on either side. The 1s are allowed to wrap from LSB to
773// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
774// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +0000775static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000776 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +0000777 uint32_t BitWidth = Val->getType()->getBitWidth();
778 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +0000779
780 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +0000781 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +0000782 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +0000783 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +0000784 return true;
785}
786
Chris Lattner7203e152005-09-18 07:22:02 +0000787/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
788/// where isSub determines whether the operator is a sub. If we can fold one of
789/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +0000790///
791/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
792/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
793/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
794///
795/// return (A +/- B).
796///
797Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000798 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000799 Instruction &I) {
800 Instruction *LHSI = dyn_cast<Instruction>(LHS);
801 if (!LHSI || LHSI->getNumOperands() != 2 ||
802 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
803
804 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
805
806 switch (LHSI->getOpcode()) {
807 default: return 0;
808 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000809 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +0000810 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +0000811 if ((Mask->getValue().countLeadingZeros() +
812 Mask->getValue().countPopulation()) ==
813 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +0000814 break;
815
816 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
817 // part, we don't need any explicit masks to take them out of A. If that
818 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +0000819 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +0000820 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +0000821 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +0000822 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +0000823 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +0000824 break;
825 }
826 }
Chris Lattnerc8e77562005-09-18 04:24:45 +0000827 return 0;
828 case Instruction::Or:
829 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +0000830 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +0000831 if ((Mask->getValue().countLeadingZeros() +
832 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +0000833 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +0000834 break;
835 return 0;
836 }
837
Chris Lattnerc8e77562005-09-18 04:24:45 +0000838 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +0000839 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
840 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +0000841}
842
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000843/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
844Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
845 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +0000846 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
847
848 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
849 if (PredicatesFoldable(LHSCC, RHSCC)) {
850 if (LHS->getOperand(0) == RHS->getOperand(1) &&
851 LHS->getOperand(1) == RHS->getOperand(0))
852 LHS->swapOperands();
853 if (LHS->getOperand(0) == RHS->getOperand(0) &&
854 LHS->getOperand(1) == RHS->getOperand(1)) {
855 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
856 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
857 bool isSigned = LHS->isSigned() || RHS->isSigned();
858 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
859 if (Instruction *I = dyn_cast<Instruction>(RV))
860 return I;
861 // Otherwise, it's a constant boolean value.
862 return ReplaceInstUsesWith(I, RV);
863 }
864 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000865
Chris Lattnerea065fb2008-11-16 05:10:52 +0000866 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +0000867 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
868 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
869 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
870 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +0000871
Chris Lattner3f40e232009-11-29 00:51:17 +0000872 if (LHSCst == RHSCst && LHSCC == RHSCC) {
873 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
874 // where C is a power of 2
875 if (LHSCC == ICmpInst::ICMP_ULT &&
876 LHSCst->getValue().isPowerOf2()) {
877 Value *NewOr = Builder->CreateOr(Val, Val2);
878 return new ICmpInst(LHSCC, NewOr, LHSCst);
879 }
880
881 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
882 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
883 Value *NewOr = Builder->CreateOr(Val, Val2);
884 return new ICmpInst(LHSCC, NewOr, LHSCst);
885 }
Chris Lattnerea065fb2008-11-16 05:10:52 +0000886 }
887
888 // From here on, we only handle:
889 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
890 if (Val != Val2) return 0;
891
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000892 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
893 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
894 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
895 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
896 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
897 return 0;
898
899 // We can't fold (ugt x, C) & (sgt x, C2).
900 if (!PredicatesFoldable(LHSCC, RHSCC))
901 return 0;
902
903 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +0000904 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +0000905 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000906 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +0000907 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +0000908 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000909 else
Chris Lattneraa3e1572008-11-16 05:14:43 +0000910 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
911
912 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000913 std::swap(LHS, RHS);
914 std::swap(LHSCst, RHSCst);
915 std::swap(LHSCC, RHSCC);
916 }
917
918 // At this point, we know we have have two icmp instructions
919 // comparing a value against two constants and and'ing the result
920 // together. Because of the above check, we know that we only have
921 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +0000922 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000923 // are not equal and that the larger constant is on the RHS
924 assert(LHSCst != RHSCst && "Compares not folded above?");
925
926 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000927 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000928 case ICmpInst::ICMP_EQ:
929 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000931 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
932 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
933 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000935 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
936 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
937 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
938 return ReplaceInstUsesWith(I, LHS);
939 }
940 case ICmpInst::ICMP_NE:
941 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000942 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000943 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +0000944 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000945 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000946 break; // (X != 13 & X u< 15) -> no change
947 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +0000948 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000949 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000950 break; // (X != 13 & X s< 15) -> no change
951 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
952 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
953 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
954 return ReplaceInstUsesWith(I, RHS);
955 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +0000956 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +0000957 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +0000958 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000959 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +0000960 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000961 }
962 break; // (X != 13 & X != 15) -> no change
963 }
964 break;
965 case ICmpInst::ICMP_ULT:
966 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000967 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000968 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
969 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000970 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000971 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
972 break;
973 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
974 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
975 return ReplaceInstUsesWith(I, LHS);
976 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
977 break;
978 }
979 break;
980 case ICmpInst::ICMP_SLT:
981 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000982 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000983 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
984 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000985 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000986 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
987 break;
988 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
989 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
990 return ReplaceInstUsesWith(I, LHS);
991 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
992 break;
993 }
994 break;
995 case ICmpInst::ICMP_UGT:
996 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000997 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000998 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
999 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
1000 return ReplaceInstUsesWith(I, RHS);
1001 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
1002 break;
1003 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001004 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001005 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001006 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001007 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00001008 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001009 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001010 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1011 break;
1012 }
1013 break;
1014 case ICmpInst::ICMP_SGT:
1015 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001016 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001017 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1018 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1019 return ReplaceInstUsesWith(I, RHS);
1020 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1021 break;
1022 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001023 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001024 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001025 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001026 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001027 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001028 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001029 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1030 break;
1031 }
1032 break;
1033 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001034
1035 return 0;
1036}
1037
Chris Lattner42d1be02009-07-23 05:14:02 +00001038Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1039 FCmpInst *RHS) {
1040
1041 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1042 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1043 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1044 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1045 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1046 // If either of the constants are nans, then the whole thing returns
1047 // false.
1048 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001049 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001050 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001051 LHS->getOperand(0), RHS->getOperand(0));
1052 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001053
1054 // Handle vector zeros. This occurs because the canonical form of
1055 // "fcmp ord x,x" is "fcmp ord x, 0".
1056 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1057 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001058 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001059 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001060 return 0;
1061 }
1062
1063 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1064 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1065 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1066
1067
1068 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1069 // Swap RHS operands to match LHS.
1070 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1071 std::swap(Op1LHS, Op1RHS);
1072 }
1073
1074 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1075 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1076 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001077 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001078
1079 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001080 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001081 if (Op0CC == FCmpInst::FCMP_TRUE)
1082 return ReplaceInstUsesWith(I, RHS);
1083 if (Op1CC == FCmpInst::FCMP_TRUE)
1084 return ReplaceInstUsesWith(I, LHS);
1085
1086 bool Op0Ordered;
1087 bool Op1Ordered;
1088 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1089 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1090 if (Op1Pred == 0) {
1091 std::swap(LHS, RHS);
1092 std::swap(Op0Pred, Op1Pred);
1093 std::swap(Op0Ordered, Op1Ordered);
1094 }
1095 if (Op0Pred == 0) {
1096 // uno && ueq -> uno && (uno || eq) -> ueq
1097 // ord && olt -> ord && (ord && lt) -> olt
1098 if (Op0Ordered == Op1Ordered)
1099 return ReplaceInstUsesWith(I, RHS);
1100
1101 // uno && oeq -> uno && (ord && eq) -> false
1102 // uno && ord -> false
1103 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001104 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001105 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001106 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001107 }
1108 }
1109
1110 return 0;
1111}
1112
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001113
Chris Lattner7e708292002-06-25 16:13:24 +00001114Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001115 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001117
Chris Lattnerd06094f2009-11-10 00:55:12 +00001118 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1119 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001120
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001121 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001122 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001123 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001124 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001125
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001126 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001127 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001128 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001129
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001130 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001131 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001132 Value *Op0LHS = Op0I->getOperand(0);
1133 Value *Op0RHS = Op0I->getOperand(1);
1134 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001135 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001136 case Instruction::Xor:
1137 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001138 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001139 if (!Op0I->hasOneUse()) break;
1140
1141 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1142 // Not masking anything out for the LHS, move to RHS.
1143 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1144 Op0RHS->getName()+".masked");
1145 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1146 }
1147 if (!isa<Constant>(Op0RHS) &&
1148 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1149 // Not masking anything out for the RHS, move to LHS.
1150 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1151 Op0LHS->getName()+".masked");
1152 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001153 }
1154
Chris Lattner6e7ba452005-01-01 16:22:27 +00001155 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001156 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001157 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1158 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1159 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1160 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001161 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001162 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001163 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001164 break;
1165
1166 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001167 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1168 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1169 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1170 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001171 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001172
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001173 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1174 // has 1's for all bits that the subtraction with A might affect.
1175 if (Op0I->hasOneUse()) {
1176 uint32_t BitWidth = AndRHSMask.getBitWidth();
1177 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1178 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1179
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001180 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001181 if (!(A && A->isZero()) && // avoid infinite recursion.
1182 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001183 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001184 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1185 }
1186 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001187 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001188
1189 case Instruction::Shl:
1190 case Instruction::LShr:
1191 // (1 << x) & 1 --> zext(x == 0)
1192 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001193 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001194 Value *NewICmp =
1195 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001196 return new ZExtInst(NewICmp, I.getType());
1197 }
1198 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001199 }
1200
Chris Lattner58403262003-07-23 19:25:52 +00001201 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001202 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001203 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001204 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001205 // If this is an integer truncation or change from signed-to-unsigned, and
1206 // if the source is an and/or with immediate, transform it. This
1207 // frequently occurs for bitfield accesses.
1208 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001209 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001210 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001211 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001212 if (CastOp->getOpcode() == Instruction::And) {
1213 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001214 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1215 // This will fold the two constants together, which may allow
1216 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001217 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001218 CastOp->getOperand(0), I.getType(),
1219 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001220 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001221 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001222 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001223 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001224 } else if (CastOp->getOpcode() == Instruction::Or) {
1225 // Change: and (cast (or X, C1) to T), C2
1226 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001227 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001228 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001229 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001230 return ReplaceInstUsesWith(I, AndRHS);
1231 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001232 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001233 }
Chris Lattner06782f82003-07-23 19:36:21 +00001234 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001235
1236 // Try to fold constant and into select arguments.
1237 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001238 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001239 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001240 if (isa<PHINode>(Op0))
1241 if (Instruction *NV = FoldOpIntoPhi(I))
1242 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001243 }
1244
Chris Lattner5b62aa72004-06-18 06:07:51 +00001245
Misha Brukmancb6267b2004-07-30 12:50:08 +00001246 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001247 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1248 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1249 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1250 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1251 I.getName()+".demorgan");
1252 return BinaryOperator::CreateNot(Or);
1253 }
1254
Chris Lattner2082ad92006-02-13 23:07:23 +00001255 {
Chris Lattner003b6202007-06-15 05:58:24 +00001256 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001257 // (A|B) & ~(A&B) -> A^B
1258 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1259 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1260 ((A == C && B == D) || (A == D && B == C)))
1261 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00001262
Chris Lattnerd06094f2009-11-10 00:55:12 +00001263 // ~(A&B) & (A|B) -> A^B
1264 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1265 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1266 ((A == C && B == D) || (A == D && B == C)))
1267 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00001268
1269 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001270 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001271 if (A == Op1) { // (A^B)&A -> A&(A^B)
1272 I.swapOperands(); // Simplify below
1273 std::swap(Op0, Op1);
1274 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1275 cast<BinaryOperator>(Op0)->swapOperands();
1276 I.swapOperands(); // Simplify below
1277 std::swap(Op0, Op1);
1278 }
1279 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001280
Chris Lattner64daab52006-04-01 08:03:55 +00001281 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001282 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001283 if (B == Op0) { // B&(A^B) -> B&(B^A)
1284 cast<BinaryOperator>(Op1)->swapOperands();
1285 std::swap(A, B);
1286 }
Chris Lattner74381062009-08-30 07:44:24 +00001287 if (A == Op0) // A&(A^B) -> A & ~B
1288 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00001289 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001290
1291 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00001292 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1293 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001294 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00001295 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1296 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001297 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00001298 }
1299
Chris Lattnera317e042010-01-05 06:59:49 +00001300 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1302 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1303 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00001304
Chris Lattner6fc205f2006-05-05 06:39:07 +00001305 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001306 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1307 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1308 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
1309 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00001310 if (SrcTy == Op1C->getOperand(0)->getType() &&
1311 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001312 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00001313 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1314 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00001315 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00001316 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00001317 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1318 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001319 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001320 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001321 }
Chris Lattnere511b742006-11-14 07:46:50 +00001322
1323 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001324 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1325 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1326 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001327 SI0->getOperand(1) == SI1->getOperand(1) &&
1328 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001329 Value *NewOp =
1330 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1331 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001332 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00001333 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00001334 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001335 }
1336
Evan Cheng8db90722008-10-14 17:15:11 +00001337 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00001338 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00001339 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1340 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
1341 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00001342 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001343
Chris Lattner7e708292002-06-25 16:13:24 +00001344 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001345}
1346
Chris Lattner8c34cd22008-10-05 02:13:19 +00001347/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1348/// capable of providing pieces of a bswap. The subexpression provides pieces
1349/// of a bswap if it is proven that each of the non-zero bytes in the output of
1350/// the expression came from the corresponding "byte swapped" byte in some other
1351/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1352/// we know that the expression deposits the low byte of %X into the high byte
1353/// of the bswap result and that all other bytes are zero. This expression is
1354/// accepted, the high byte of ByteValues is set to X to indicate a correct
1355/// match.
1356///
1357/// This function returns true if the match was unsuccessful and false if so.
1358/// On entry to the function the "OverallLeftShift" is a signed integer value
1359/// indicating the number of bytes that the subexpression is later shifted. For
1360/// example, if the expression is later right shifted by 16 bits, the
1361/// OverallLeftShift value would be -2 on entry. This is used to specify which
1362/// byte of ByteValues is actually being set.
1363///
1364/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1365/// byte is masked to zero by a user. For example, in (X & 255), X will be
1366/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1367/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1368/// always in the local (OverallLeftShift) coordinate space.
1369///
1370static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1371 SmallVector<Value*, 8> &ByteValues) {
1372 if (Instruction *I = dyn_cast<Instruction>(V)) {
1373 // If this is an or instruction, it may be an inner node of the bswap.
1374 if (I->getOpcode() == Instruction::Or) {
1375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1376 ByteValues) ||
1377 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1378 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001379 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00001380
1381 // If this is a logical shift by a constant multiple of 8, recurse with
1382 // OverallLeftShift and ByteMask adjusted.
1383 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1384 unsigned ShAmt =
1385 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1386 // Ensure the shift amount is defined and of a byte value.
1387 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1388 return true;
1389
1390 unsigned ByteShift = ShAmt >> 3;
1391 if (I->getOpcode() == Instruction::Shl) {
1392 // X << 2 -> collect(X, +2)
1393 OverallLeftShift += ByteShift;
1394 ByteMask >>= ByteShift;
1395 } else {
1396 // X >>u 2 -> collect(X, -2)
1397 OverallLeftShift -= ByteShift;
1398 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00001399 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00001400 }
1401
1402 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1403 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1404
1405 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1406 ByteValues);
1407 }
1408
1409 // If this is a logical 'and' with a mask that clears bytes, clear the
1410 // corresponding bytes in ByteMask.
1411 if (I->getOpcode() == Instruction::And &&
1412 isa<ConstantInt>(I->getOperand(1))) {
1413 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1414 unsigned NumBytes = ByteValues.size();
1415 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1416 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1417
1418 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1419 // If this byte is masked out by a later operation, we don't care what
1420 // the and mask is.
1421 if ((ByteMask & (1 << i)) == 0)
1422 continue;
1423
1424 // If the AndMask is all zeros for this byte, clear the bit.
1425 APInt MaskB = AndMask & Byte;
1426 if (MaskB == 0) {
1427 ByteMask &= ~(1U << i);
1428 continue;
1429 }
1430
1431 // If the AndMask is not all ones for this byte, it's not a bytezap.
1432 if (MaskB != Byte)
1433 return true;
1434
1435 // Otherwise, this byte is kept.
1436 }
1437
1438 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1439 ByteValues);
1440 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001441 }
1442
Chris Lattner8c34cd22008-10-05 02:13:19 +00001443 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1444 // the input value to the bswap. Some observations: 1) if more than one byte
1445 // is demanded from this input, then it could not be successfully assembled
1446 // into a byteswap. At least one of the two bytes would not be aligned with
1447 // their ultimate destination.
1448 if (!isPowerOf2_32(ByteMask)) return true;
1449 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001450
Chris Lattner8c34cd22008-10-05 02:13:19 +00001451 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1452 // is demanded, it needs to go into byte 0 of the result. This means that the
1453 // byte needs to be shifted until it lands in the right byte bucket. The
1454 // shift amount depends on the position: if the byte is coming from the high
1455 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1456 // low part, it must be shifted left.
1457 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1458 if (InputByteNo < ByteValues.size()/2) {
1459 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1460 return true;
1461 } else {
1462 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1463 return true;
1464 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001465
1466 // If the destination byte value is already defined, the values are or'd
1467 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00001468 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00001469 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00001470 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00001471 return false;
1472}
1473
1474/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1475/// If so, insert the new bswap intrinsic and return it.
1476Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00001477 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00001478 if (!ITy || ITy->getBitWidth() % 16 ||
1479 // ByteMask only allows up to 32-byte values.
1480 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00001481 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00001482
1483 /// ByteValues - For each byte of the result, we keep track of which value
1484 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00001485 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00001486 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001487
1488 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00001489 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1490 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00001491 return 0;
1492
1493 // Check to see if all of the bytes come from the same value.
1494 Value *V = ByteValues[0];
1495 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1496
1497 // Check to make sure that all of the bytes come from the same value.
1498 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1499 if (ByteValues[i] != V)
1500 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00001501 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00001502 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00001503 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00001504 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001505}
1506
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001507/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1508/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1509/// we can simplify this expression to "cond ? C : D or B".
1510static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00001511 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00001512 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00001513 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001514 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001515 return 0;
1516
Chris Lattnera6a474d2008-11-16 04:26:55 +00001517 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00001518 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001519 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00001520 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001521 return SelectInst::Create(Cond, C, B);
1522 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00001523 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001524 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00001525 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001526 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001527 return 0;
1528}
Chris Lattnerafe91a52006-06-15 19:07:26 +00001529
Chris Lattner69d4ced2008-11-16 05:20:07 +00001530/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1531Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1532 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001533 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1534
1535 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1536 if (PredicatesFoldable(LHSCC, RHSCC)) {
1537 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1538 LHS->getOperand(1) == RHS->getOperand(0))
1539 LHS->swapOperands();
1540 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1541 LHS->getOperand(1) == RHS->getOperand(1)) {
1542 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1543 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1544 bool isSigned = LHS->isSigned() || RHS->isSigned();
1545 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1546 if (Instruction *I = dyn_cast<Instruction>(RV))
1547 return I;
1548 // Otherwise, it's a constant boolean value.
1549 return ReplaceInstUsesWith(I, RV);
1550 }
1551 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001552
1553 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001554 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1555 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1556 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1557 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00001558
Chris Lattner3f40e232009-11-29 00:51:17 +00001559 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1560 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1561 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1562 Value *NewOr = Builder->CreateOr(Val, Val2);
1563 return new ICmpInst(LHSCC, NewOr, LHSCst);
1564 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001565
1566 // From here on, we only handle:
1567 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1568 if (Val != Val2) return 0;
1569
1570 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1571 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1572 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1573 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1574 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1575 return 0;
1576
1577 // We can't fold (ugt x, C) | (sgt x, C2).
1578 if (!PredicatesFoldable(LHSCC, RHSCC))
1579 return 0;
1580
1581 // Ensure that the larger constant is on the RHS.
1582 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001583 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00001584 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001585 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00001586 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1587 else
1588 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1589
1590 if (ShouldSwap) {
1591 std::swap(LHS, RHS);
1592 std::swap(LHSCst, RHSCst);
1593 std::swap(LHSCC, RHSCC);
1594 }
1595
1596 // At this point, we know we have have two icmp instructions
1597 // comparing a value against two constants and or'ing the result
1598 // together. Because of the above check, we know that we only have
1599 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00001600 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00001601 // equal.
1602 assert(LHSCst != RHSCst && "Compares not folded above?");
1603
1604 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001605 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001606 case ICmpInst::ICMP_EQ:
1607 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001608 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001609 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00001610 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001611 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00001612 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001613 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00001614 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001615 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001616 }
1617 break; // (X == 13 | X == 15) -> no change
1618 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1619 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1620 break;
1621 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1622 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1623 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1624 return ReplaceInstUsesWith(I, RHS);
1625 }
1626 break;
1627 case ICmpInst::ICMP_NE:
1628 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001629 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001630 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1631 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1632 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1633 return ReplaceInstUsesWith(I, LHS);
1634 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1635 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1636 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001637 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001638 }
1639 break;
1640 case ICmpInst::ICMP_ULT:
1641 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001642 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001643 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1644 break;
1645 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1646 // If RHSCst is [us]MAXINT, it is always false. Not handling
1647 // this can cause overflow.
1648 if (RHSCst->isMaxValue(false))
1649 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001650 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001651 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001652 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1653 break;
1654 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1655 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1656 return ReplaceInstUsesWith(I, RHS);
1657 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1658 break;
1659 }
1660 break;
1661 case ICmpInst::ICMP_SLT:
1662 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001663 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001664 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1665 break;
1666 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1667 // If RHSCst is [us]MAXINT, it is always false. Not handling
1668 // this can cause overflow.
1669 if (RHSCst->isMaxValue(true))
1670 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001671 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001672 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001673 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1674 break;
1675 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1676 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1677 return ReplaceInstUsesWith(I, RHS);
1678 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1679 break;
1680 }
1681 break;
1682 case ICmpInst::ICMP_UGT:
1683 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001684 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001685 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1686 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1687 return ReplaceInstUsesWith(I, LHS);
1688 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1689 break;
1690 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1691 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001692 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001693 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1694 break;
1695 }
1696 break;
1697 case ICmpInst::ICMP_SGT:
1698 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001699 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001700 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1701 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1702 return ReplaceInstUsesWith(I, LHS);
1703 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1704 break;
1705 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1706 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001707 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001708 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1709 break;
1710 }
1711 break;
1712 }
1713 return 0;
1714}
1715
Chris Lattner5414cc52009-07-23 05:46:22 +00001716Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1717 FCmpInst *RHS) {
1718 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1719 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1720 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1721 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1722 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1723 // If either of the constants are nans, then the whole thing returns
1724 // true.
1725 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001726 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001727
1728 // Otherwise, no need to compare the two constants, compare the
1729 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001730 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001731 LHS->getOperand(0), RHS->getOperand(0));
1732 }
1733
1734 // Handle vector zeros. This occurs because the canonical form of
1735 // "fcmp uno x,x" is "fcmp uno x, 0".
1736 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1737 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001738 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001739 LHS->getOperand(0), RHS->getOperand(0));
1740
1741 return 0;
1742 }
1743
1744 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1745 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1746 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1747
1748 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1749 // Swap RHS operands to match LHS.
1750 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1751 std::swap(Op1LHS, Op1RHS);
1752 }
1753 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1754 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1755 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001756 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00001757 Op0LHS, Op0RHS);
1758 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00001759 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001760 if (Op0CC == FCmpInst::FCMP_FALSE)
1761 return ReplaceInstUsesWith(I, RHS);
1762 if (Op1CC == FCmpInst::FCMP_FALSE)
1763 return ReplaceInstUsesWith(I, LHS);
1764 bool Op0Ordered;
1765 bool Op1Ordered;
1766 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1767 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1768 if (Op0Ordered == Op1Ordered) {
1769 // If both are ordered or unordered, return a new fcmp with
1770 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00001771 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00001772 if (Instruction *I = dyn_cast<Instruction>(RV))
1773 return I;
1774 // Otherwise, it's a constant boolean value...
1775 return ReplaceInstUsesWith(I, RV);
1776 }
1777 }
1778 return 0;
1779}
1780
Bill Wendlinga698a472008-12-01 08:23:25 +00001781/// FoldOrWithConstants - This helper function folds:
1782///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001783/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00001784///
1785/// into:
1786///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001787/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00001788///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001789/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00001790Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00001791 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00001792 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1793 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001794
Bill Wendling286a0542008-12-02 06:24:20 +00001795 Value *V1 = 0;
1796 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001797 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001798
Bill Wendling29976b92008-12-02 06:18:11 +00001799 APInt Xor = CI1->getValue() ^ CI2->getValue();
1800 if (!Xor.isAllOnesValue()) return 0;
1801
Bill Wendling286a0542008-12-02 06:24:20 +00001802 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00001803 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00001804 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00001805 }
1806
1807 return 0;
1808}
1809
Chris Lattner7e708292002-06-25 16:13:24 +00001810Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001811 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001812 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001813
Chris Lattnerd06094f2009-11-10 00:55:12 +00001814 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1815 return ReplaceInstUsesWith(I, V);
1816
1817
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001818 // See if we can simplify any instructions used by the instruction whose sole
1819 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001820 if (SimplifyDemandedInstructionBits(I))
1821 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00001822
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001823 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001824 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001825 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001826 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001827 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001828 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001829 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001830 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001831 ConstantInt::get(I.getContext(),
1832 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001833 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001834
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001835 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001836 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001837 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001838 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001839 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001840 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001841 ConstantInt::get(I.getContext(),
1842 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001843 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001844
1845 // Try to fold constant and into select arguments.
1846 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001847 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001848 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001849 if (isa<PHINode>(Op0))
1850 if (Instruction *NV = FoldOpIntoPhi(I))
1851 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001852 }
1853
Chris Lattner4f637d42006-01-06 17:59:59 +00001854 Value *A = 0, *B = 0;
1855 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00001856
Chris Lattner6423d4c2006-07-10 20:25:24 +00001857 // (A | B) | C and A | (B | C) -> bswap if possible.
1858 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00001859 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1860 match(Op1, m_Or(m_Value(), m_Value())) ||
1861 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1862 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00001863 if (Instruction *BSwap = MatchBSwap(I))
1864 return BSwap;
1865 }
1866
Chris Lattner6e4c6492005-05-09 04:58:36 +00001867 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001868 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001869 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001870 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001871 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00001872 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001873 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001874 }
1875
1876 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001877 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001878 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001879 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001880 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00001881 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001882 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001883 }
1884
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001885 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00001886 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001887 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1888 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001889 Value *V1 = 0, *V2 = 0, *V3 = 0;
1890 C1 = dyn_cast<ConstantInt>(C);
1891 C2 = dyn_cast<ConstantInt>(D);
1892 if (C1 && C2) { // (A & C1)|(B & C2)
1893 // If we have: ((V + N) & C1) | (V & C2)
1894 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1895 // replace with V+N.
1896 if (C1->getValue() == ~C2->getValue()) {
1897 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00001898 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001899 // Add commutes, try both ways.
1900 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1901 return ReplaceInstUsesWith(I, A);
1902 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1903 return ReplaceInstUsesWith(I, A);
1904 }
1905 // Or commutes, try both ways.
1906 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001907 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001908 // Add commutes, try both ways.
1909 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1910 return ReplaceInstUsesWith(I, B);
1911 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1912 return ReplaceInstUsesWith(I, B);
1913 }
1914 }
Chris Lattnere4412c12010-01-04 06:03:59 +00001915
1916 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1917 // iff (C1&C2) == 0 and (N&~C1) == 0
1918 if ((C1->getValue() & C2->getValue()) == 0) {
1919 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1920 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1921 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1922 return BinaryOperator::CreateAnd(A,
1923 ConstantInt::get(A->getContext(),
1924 C1->getValue()|C2->getValue()));
1925 // Or commutes, try both ways.
1926 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1927 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1928 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1929 return BinaryOperator::CreateAnd(B,
1930 ConstantInt::get(B->getContext(),
1931 C1->getValue()|C2->getValue()));
1932 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00001933 }
1934
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001935 // Check to see if we have any common things being and'ed. If so, find the
1936 // terms for V1 & (V2|V3).
Chris Lattner248a84b2010-01-05 07:04:23 +00001937 if (Op0->hasOneUse() || Op1->hasOneUse()) {
Chris Lattnere4412c12010-01-04 06:03:59 +00001938 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001939 if (A == B) // (A & C)|(A & D) == A & (C|D)
1940 V1 = A, V2 = C, V3 = D;
1941 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1942 V1 = A, V2 = B, V3 = C;
1943 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1944 V1 = C, V2 = A, V3 = D;
1945 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1946 V1 = C, V2 = A, V3 = B;
1947
1948 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00001949 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001950 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00001951 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001952 }
Dan Gohmanb493b272008-10-28 22:38:57 +00001953
Dan Gohman1975d032008-10-30 20:40:10 +00001954 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00001955 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001956 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001957 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001958 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001959 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001960 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001961 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001962 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00001963
Bill Wendlingb01865c2008-11-30 13:52:49 +00001964 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001965 if ((match(C, m_Not(m_Specific(D))) &&
1966 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001967 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001968 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001969 if ((match(A, m_Not(m_Specific(D))) &&
1970 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001971 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001972 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001973 if ((match(C, m_Not(m_Specific(B))) &&
1974 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001975 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001976 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001977 if ((match(A, m_Not(m_Specific(B))) &&
1978 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001979 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00001980 }
Chris Lattnere511b742006-11-14 07:46:50 +00001981
1982 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001983 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1984 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1985 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001986 SI0->getOperand(1) == SI1->getOperand(1) &&
1987 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001988 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1989 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001990 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00001991 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00001992 }
1993 }
Chris Lattner67ca7682003-08-12 19:11:07 +00001994
Bill Wendlingb3833d12008-12-01 01:07:11 +00001995 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00001996 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1997 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00001998 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00001999 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002000 }
2001 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00002002 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
2003 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00002004 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00002005 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00002006 }
2007
Chris Lattnerd06094f2009-11-10 00:55:12 +00002008 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2009 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2010 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2011 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2012 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2013 I.getName()+".demorgan");
2014 return BinaryOperator::CreateNot(And);
2015 }
Chris Lattnera2881962003-02-18 19:28:33 +00002016
Chris Lattnera317e042010-01-05 06:59:49 +00002017 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002018 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2019 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2020 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002021
2022 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002023 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002024 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002025 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002026 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2027 !isa<ICmpInst>(Op1C->getOperand(0))) {
2028 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002029 if (SrcTy == Op1C->getOperand(0)->getType() &&
2030 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002031 // Only do this if the casts both really cause code to be
2032 // generated.
2033 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002034 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002035 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002036 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002037 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2038 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002039 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002040 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002041 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002042 }
Chris Lattner99c65742007-10-24 05:38:08 +00002043 }
2044
2045
2046 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2047 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002048 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2049 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2050 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002051 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002052
Chris Lattner7e708292002-06-25 16:13:24 +00002053 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002054}
2055
Chris Lattner7e708292002-06-25 16:13:24 +00002056Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002057 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002059
Evan Chengd34af782008-03-25 20:07:13 +00002060 if (isa<UndefValue>(Op1)) {
2061 if (isa<UndefValue>(Op0))
2062 // Handle undef ^ undef -> 0 special case. This is a common
2063 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002064 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002065 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002066 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002067
Chris Lattnerdea34da2010-01-05 07:01:16 +00002068 // xor X, X = 0
2069 if (Op0 == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002070 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002071
2072 // See if we can simplify any instructions used by the instruction whose sole
2073 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002074 if (SimplifyDemandedInstructionBits(I))
2075 return &I;
2076 if (isa<VectorType>(I.getType()))
2077 if (isa<ConstantAggregateZero>(Op1))
2078 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002079
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002080 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002081 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002082 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2083 if (Op0I->getOpcode() == Instruction::And ||
2084 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002085 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2086 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2087 if (dyn_castNotVal(Op0I->getOperand(1)))
2088 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002089 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002090 Value *NotY =
2091 Builder->CreateNot(Op0I->getOperand(1),
2092 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002093 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002094 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002095 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002096 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002097
2098 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2099 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2100 if (isFreeToInvert(Op0I->getOperand(0)) &&
2101 isFreeToInvert(Op0I->getOperand(1))) {
2102 Value *NotX =
2103 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2104 Value *NotY =
2105 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2106 if (Op0I->getOpcode() == Instruction::And)
2107 return BinaryOperator::CreateOr(NotX, NotY);
2108 return BinaryOperator::CreateAnd(NotX, NotY);
2109 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002110 }
2111 }
2112 }
2113
2114
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002115 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002116 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002117 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002118 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002119 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002120 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002121
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002122 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002123 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002124 FCI->getOperand(0), FCI->getOperand(1));
2125 }
2126
Nick Lewycky517e1f52008-05-31 19:01:33 +00002127 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2128 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2129 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2130 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2131 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002132 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2133 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002134 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002135 Op0C->getDestTy()))) {
2136 CI->setPredicate(CI->getInversePredicate());
2137 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002138 }
2139 }
2140 }
2141 }
2142
Reid Spencere4d87aa2006-12-23 06:05:41 +00002143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002144 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002145 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2146 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002147 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2148 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002149 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002150 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002151 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002152
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002153 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002154 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002155 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002156 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002157 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002158 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002159 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002160 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002161 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002162 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002163 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002164 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002165 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002166 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002167
Chris Lattner7c4049c2004-01-12 19:35:11 +00002168 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002169 } else if (Op0I->getOpcode() == Instruction::Or) {
2170 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002171 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002172 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002173 // Anything in both C1 and C2 is known to be zero, remove it from
2174 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002175 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2176 NewRHS = ConstantExpr::getAnd(NewRHS,
2177 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002178 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002179 I.setOperand(0, Op0I->getOperand(0));
2180 I.setOperand(1, NewRHS);
2181 return &I;
2182 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002183 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002184 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002185 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002186
2187 // Try to fold constant and into select arguments.
2188 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002189 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002190 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002191 if (isa<PHINode>(Op0))
2192 if (Instruction *NV = FoldOpIntoPhi(I))
2193 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002194 }
2195
Dan Gohman186a6362009-08-12 16:04:34 +00002196 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002197 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002198 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002199
Dan Gohman186a6362009-08-12 16:04:34 +00002200 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002201 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002202 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002203
Chris Lattner318bf792007-03-18 22:51:34 +00002204
2205 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2206 if (Op1I) {
2207 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002208 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002209 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002210 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002211 I.swapOperands();
2212 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002213 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002214 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002215 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002216 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002217 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002218 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002219 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002220 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002221 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002222 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002223 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002224 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002225 std::swap(A, B);
2226 }
Chris Lattner318bf792007-03-18 22:51:34 +00002227 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002228 I.swapOperands(); // Simplified below.
2229 std::swap(Op0, Op1);
2230 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002231 }
Chris Lattner318bf792007-03-18 22:51:34 +00002232 }
2233
2234 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2235 if (Op0I) {
2236 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002237 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002238 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00002239 if (A == Op1) // (B|A)^B == (A|B)^B
2240 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00002241 if (B == Op1) // (A|B)^B == A & ~B
2242 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00002243 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002244 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002245 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002246 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002247 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002248 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00002249 if (A == Op1) // (A&B)^A -> (B&A)^A
2250 std::swap(A, B);
2251 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00002252 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00002253 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00002254 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002255 }
Chris Lattner318bf792007-03-18 22:51:34 +00002256 }
2257
2258 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2259 if (Op0I && Op1I && Op0I->isShift() &&
2260 Op0I->getOpcode() == Op1I->getOpcode() &&
2261 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2262 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002263 Value *NewOp =
2264 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2265 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00002267 Op1I->getOperand(1));
2268 }
2269
2270 if (Op0I && Op1I) {
2271 Value *A, *B, *C, *D;
2272 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002273 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2274 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002275 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002276 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002277 }
2278 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002279 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2280 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002281 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002282 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002283 }
2284
2285 // (A & B)^(C & D)
2286 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002287 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2288 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002289 // (X & Y)^(X & Y) -> (Y^Z) & X
2290 Value *X = 0, *Y = 0, *Z = 0;
2291 if (A == C)
2292 X = A, Y = B, Z = D;
2293 else if (A == D)
2294 X = A, Y = B, Z = C;
2295 else if (B == C)
2296 X = B, Y = A, Z = D;
2297 else if (B == D)
2298 X = B, Y = A, Z = C;
2299
2300 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00002301 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002302 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00002303 }
2304 }
2305 }
2306
Reid Spencere4d87aa2006-12-23 06:05:41 +00002307 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2308 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00002309 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2310 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2311 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2312 LHS->getOperand(1) == RHS->getOperand(0))
2313 LHS->swapOperands();
2314 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2315 LHS->getOperand(1) == RHS->getOperand(1)) {
2316 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2317 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2318 bool isSigned = LHS->isSigned() || RHS->isSigned();
2319 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2320 if (Instruction *I = dyn_cast<Instruction>(RV))
2321 return I;
2322 // Otherwise, it's a constant boolean value.
2323 return ReplaceInstUsesWith(I, RV);
2324 }
2325 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002326
Chris Lattner6fc205f2006-05-05 06:39:07 +00002327 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002328 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002329 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002330 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2331 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002332 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002333 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002334 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002335 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002336 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002337 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002338 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2339 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002340 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002341 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002342 }
Chris Lattner99c65742007-10-24 05:38:08 +00002343 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00002344
Chris Lattner7e708292002-06-25 16:13:24 +00002345 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002346}
2347
Chris Lattner3f5b8772002-05-06 16:14:14 +00002348
Reid Spencer832254e2007-02-02 02:16:23 +00002349Instruction *InstCombiner::visitShl(BinaryOperator &I) {
2350 return commonShiftTransforms(I);
2351}
2352
2353Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
2354 return commonShiftTransforms(I);
2355}
2356
2357Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00002358 if (Instruction *R = commonShiftTransforms(I))
2359 return R;
2360
2361 Value *Op0 = I.getOperand(0);
2362
2363 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
2364 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2365 if (CSI->isAllOnesValue())
2366 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00002367
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002368 // See if we can turn a signed shr into an unsigned shr.
2369 if (MaskedValueIsZero(Op0,
2370 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
2371 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
2372
2373 // Arithmetic shifting an all-sign-bit value is a no-op.
2374 unsigned NumSignBits = ComputeNumSignBits(Op0);
2375 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
2376 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00002377
Chris Lattner348f6652007-12-06 01:59:46 +00002378 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002379}
2380
2381Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
2382 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00002383 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002384
2385 // shl X, 0 == X and shr X, 0 == X
2386 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002387 if (Op1 == Constant::getNullValue(Op1->getType()) ||
2388 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00002389 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002390
Reid Spencere4d87aa2006-12-23 06:05:41 +00002391 if (isa<UndefValue>(Op0)) {
2392 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00002393 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002394 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002395 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002396 }
2397 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002398 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
2399 return ReplaceInstUsesWith(I, Op0);
2400 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002401 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002402 }
2403
Dan Gohman9004c8a2009-05-21 02:28:33 +00002404 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00002405 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00002406 return &I;
2407
Chris Lattner2eefe512004-04-09 19:05:30 +00002408 // Try to fold constant and into select arguments.
2409 if (isa<Constant>(Op0))
2410 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00002411 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002412 return R;
2413
Reid Spencerb83eb642006-10-20 07:07:24 +00002414 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00002415 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
2416 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002417 return 0;
2418}
2419
Reid Spencerb83eb642006-10-20 07:07:24 +00002420Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00002421 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00002422 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002423
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002424 // See if we can simplify any instructions used by the instruction whose sole
2425 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002426 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002427
Dan Gohmana119de82009-06-14 23:30:43 +00002428 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
2429 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00002430 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002431 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00002432 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002433 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002434 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00002435 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002436 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00002437 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002438 }
2439
2440 // ((X*C1) << C2) == (X * (C1 << C2))
2441 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2442 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2443 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002444 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002445 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002446
2447 // Try to fold constant and into select arguments.
2448 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002449 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00002450 return R;
2451 if (isa<PHINode>(Op0))
2452 if (Instruction *NV = FoldOpIntoPhi(I))
2453 return NV;
2454
Chris Lattner8999dd32007-12-22 09:07:47 +00002455 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
2456 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
2457 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
2458 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
2459 // place. Don't try to do this transformation in this case. Also, we
2460 // require that the input operand is a shift-by-constant so that we have
2461 // confidence that the shifts will get folded together. We could do this
2462 // xform in more cases, but it is unlikely to be profitable.
2463 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
2464 isa<ConstantInt>(TrOp->getOperand(1))) {
2465 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00002467 // (shift2 (shift1 & 0x00FF), c2)
2468 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002469
2470 // For logical shifts, the truncation has the effect of making the high
2471 // part of the register be zeros. Emulate this by inserting an AND to
2472 // clear the top bits as needed. This 'and' will usually be zapped by
2473 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002474 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
2475 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00002476 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
2477
2478 // The mask we constructed says what the trunc would do if occurring
2479 // between the shifts. We want to know the effect *after* the second
2480 // shift. We know that it is a logical shift by a constant, so adjust the
2481 // mask as appropriate.
2482 if (I.getOpcode() == Instruction::Shl)
2483 MaskV <<= Op1->getZExtValue();
2484 else {
2485 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
2486 MaskV = MaskV.lshr(Op1->getZExtValue());
2487 }
2488
Chris Lattner74381062009-08-30 07:44:24 +00002489 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00002490 Value *And = Builder->CreateAnd(NSh,
2491 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00002492 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002493
2494 // Return the value truncated to the interesting size.
2495 return new TruncInst(And, I.getType());
2496 }
2497 }
2498
Chris Lattner4d5542c2006-01-06 07:12:35 +00002499 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00002500 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
2501 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
2502 Value *V1, *V2;
2503 ConstantInt *CC;
2504 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00002505 default: break;
2506 case Instruction::Add:
2507 case Instruction::And:
2508 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00002509 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002510 // These operators commute.
2511 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002512 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002513 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002514 m_Specific(Op1)))) {
2515 Value *YS = // (Y << C)
2516 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
2517 // (X + (Y << C))
2518 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
2519 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002520 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002521 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002522 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002523 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002524
Chris Lattner150f12a2005-09-18 06:30:59 +00002525 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00002526 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00002527 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00002528 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00002529 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002530 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00002531 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002532 Value *YS = // (Y << C)
2533 Builder->CreateShl(Op0BO->getOperand(0), Op1,
2534 Op0BO->getName());
2535 // X & (CC << C)
2536 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2537 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00002539 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00002540 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002541
Reid Spencera07cb7d2007-02-02 14:41:37 +00002542 // FALL THROUGH.
2543 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002544 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002545 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002546 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00002547 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002548 Value *YS = // (Y << C)
2549 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2550 // (X + (Y << C))
2551 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
2552 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002553 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002554 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002555 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002556 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002557
Chris Lattner13d4ab42006-05-31 21:14:00 +00002558 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002559 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2560 match(Op0BO->getOperand(0),
2561 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002562 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00002563 cast<BinaryOperator>(Op0BO->getOperand(0))
2564 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002565 Value *YS = // (Y << C)
2566 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2567 // X & (CC << C)
2568 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2569 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00002570
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002571 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00002572 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002573
Chris Lattner11021cb2005-09-18 05:12:10 +00002574 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00002575 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002576 }
2577
2578
2579 // If the operand is an bitwise operator with a constant RHS, and the
2580 // shift is the only use, we can pull it out of the shift.
2581 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2582 bool isValid = true; // Valid only for And, Or, Xor
2583 bool highBitSet = false; // Transform if high bit of constant set?
2584
2585 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00002586 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00002587 case Instruction::Add:
2588 isValid = isLeftShift;
2589 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00002590 case Instruction::Or:
2591 case Instruction::Xor:
2592 highBitSet = false;
2593 break;
2594 case Instruction::And:
2595 highBitSet = true;
2596 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002597 }
2598
2599 // If this is a signed shift right, and the high bit is modified
2600 // by the logical operation, do not perform the transformation.
2601 // The highBitSet boolean indicates the value of the high bit of
2602 // the constant which would cause it to be modified for this
2603 // operation.
2604 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00002605 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00002606 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002607
2608 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002609 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002610
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002611 Value *NewShift =
2612 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002613 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002614
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002615 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00002616 NewRHS);
2617 }
2618 }
2619 }
2620 }
2621
Chris Lattnerad0124c2006-01-06 07:52:12 +00002622 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00002623 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
2624 if (ShiftOp && !ShiftOp->isShift())
2625 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002626
Reid Spencerb83eb642006-10-20 07:07:24 +00002627 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002628 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002629 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
2630 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002631 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
2632 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
2633 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00002634
Zhou Sheng4351c642007-04-02 08:20:41 +00002635 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00002636
2637 const IntegerType *Ty = cast<IntegerType>(I.getType());
2638
2639 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00002640 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002641 // If this is oversized composite shift, then unsigned shifts get 0, ashr
2642 // saturates.
2643 if (AmtSum >= TypeBits) {
2644 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002645 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002646 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
2647 }
2648
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002649 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00002650 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002651 }
2652
2653 if (ShiftOp->getOpcode() == Instruction::LShr &&
2654 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002655 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00002656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002657
Chris Lattnerb87056f2007-02-05 00:57:54 +00002658 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00002659 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002660 }
2661
2662 if (ShiftOp->getOpcode() == Instruction::AShr &&
2663 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00002664 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00002665 if (AmtSum >= TypeBits)
2666 AmtSum = TypeBits-1;
2667
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002668 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002669
Zhou Shenge9e03f62007-03-28 15:02:20 +00002670 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00002671 return BinaryOperator::CreateAnd(Shift,
2672 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002673 }
2674
Chris Lattnerb87056f2007-02-05 00:57:54 +00002675 // Okay, if we get here, one shift must be left, and the other shift must be
2676 // right. See if the amounts are equal.
2677 if (ShiftAmt1 == ShiftAmt2) {
2678 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
2679 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00002680 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002681 return BinaryOperator::CreateAnd(X,
2682 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002683 }
2684 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
2685 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002686 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002687 return BinaryOperator::CreateAnd(X,
2688 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002689 }
2690 // We can simplify ((X << C) >>s C) into a trunc + sext.
2691 // NOTE: we could do this for any C, but that would make 'unusual' integer
2692 // types. For now, just stick to ones well-supported by the code
2693 // generators.
2694 const Type *SExtType = 0;
2695 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00002696 case 1 :
2697 case 8 :
2698 case 16 :
2699 case 32 :
2700 case 64 :
2701 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00002702 SExtType = IntegerType::get(I.getContext(),
2703 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00002704 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002705 default: break;
2706 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002707 if (SExtType)
2708 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002709 // Otherwise, we can't handle it yet.
2710 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002711 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002712
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002713 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002714 if (I.getOpcode() == Instruction::Shl) {
2715 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2716 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002717 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00002718
Reid Spencer55702aa2007-03-25 21:11:44 +00002719 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002720 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002721 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002722 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002723
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002724 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002725 if (I.getOpcode() == Instruction::LShr) {
2726 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002727 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002728
Reid Spencerd5e30f02007-03-26 17:18:58 +00002729 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002730 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002731 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00002732 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002733
2734 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
2735 } else {
2736 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00002737 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002738
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002739 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002740 if (I.getOpcode() == Instruction::Shl) {
2741 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2742 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002743 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
2744 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002745
Reid Spencer55702aa2007-03-25 21:11:44 +00002746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002747 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002748 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002749 }
2750
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002751 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002752 if (I.getOpcode() == Instruction::LShr) {
2753 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002754 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002755
Reid Spencer68d27cf2007-03-26 23:45:51 +00002756 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002757 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002758 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002759 }
2760
2761 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002762 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00002763 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002764 return 0;
2765}
2766
Chris Lattnera1be5662002-05-02 17:06:02 +00002767
Reid Spencer3da59db2006-11-27 01:05:10 +00002768
Chris Lattner46cd5a12009-01-09 05:44:56 +00002769/// FindElementAtOffset - Given a type and a constant offset, determine whether
2770/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00002771/// the specified offset. If so, fill them into NewIndices and return the
2772/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00002773const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
2774 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002775 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00002776 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002777
2778 // Start with the index over the outer type. Note that the type size
2779 // might be zero (even if the offset isn't zero) if the indexed type
2780 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00002781 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00002782 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00002783 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00002784 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00002785 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002786
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002787 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00002788 if (Offset < 0) {
2789 --FirstIdx;
2790 Offset += TySize;
2791 assert(Offset >= 0);
2792 }
2793 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
2794 }
2795
Owen Andersoneed707b2009-07-24 23:12:02 +00002796 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002797
2798 // Index into the types. If we fail, set OrigBase to null.
2799 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002800 // Indexing into tail padding between struct/array elements.
2801 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00002802 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002803
Chris Lattner46cd5a12009-01-09 05:44:56 +00002804 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2805 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002806 assert(Offset < (int64_t)SL->getSizeInBytes() &&
2807 "Offset must stay within the indexed type");
2808
Chris Lattner46cd5a12009-01-09 05:44:56 +00002809 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00002810 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2811 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002812
2813 Offset -= SL->getElementOffset(Elt);
2814 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00002815 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00002816 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002817 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00002818 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002819 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00002820 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00002821 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002822 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00002823 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002824 }
2825 }
2826
Chris Lattner3914f722009-01-24 01:00:13 +00002827 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002828}
2829
Chris Lattner8a2a3112001-12-14 16:52:21 +00002830
Chris Lattner473945d2002-05-06 18:06:38 +00002831
Chris Lattner7e708292002-06-25 16:13:24 +00002832Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002833 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
2834
2835 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
2836 return ReplaceInstUsesWith(GEP, V);
2837
Chris Lattner620ce142004-05-07 22:09:22 +00002838 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002839
Chris Lattnere87597f2004-10-16 18:11:37 +00002840 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002841 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002842
Chris Lattner28977af2004-04-05 01:30:19 +00002843 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00002844 if (TD) {
2845 bool MadeChange = false;
2846 unsigned PtrSize = TD->getPointerSizeInBits();
2847
2848 gep_type_iterator GTI = gep_type_begin(GEP);
2849 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
2850 I != E; ++I, ++GTI) {
2851 if (!isa<SequentialType>(*GTI)) continue;
2852
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002853 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00002854 // to what we need. If narrower, sign-extend it to what we need. This
2855 // explicit cast can make subsequent optimizations more obvious.
2856 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00002857 if (OpBits == PtrSize)
2858 continue;
2859
Chris Lattner2345d1d2009-08-30 20:01:10 +00002860 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00002861 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00002862 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00002863 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00002864 }
Chris Lattner28977af2004-04-05 01:30:19 +00002865
Chris Lattner90ac28c2002-08-02 19:29:35 +00002866 // Combine Indices - If the source pointer to this getelementptr instruction
2867 // is a getelementptr instruction, combine the indices of the two
2868 // getelementptr instructions into a single instruction.
2869 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00002870 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00002871 // Note that if our source is a gep chain itself that we wait for that
2872 // chain to be resolved before we perform this transformation. This
2873 // avoids us creating a TON of code in some cases.
2874 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002875 if (GetElementPtrInst *SrcGEP =
2876 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
2877 if (SrcGEP->getNumOperands() == 2)
2878 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00002879
Chris Lattner72588fc2007-02-15 22:48:32 +00002880 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00002881
2882 // Find out whether the last index in the source GEP is a sequential idx.
2883 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00002884 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2885 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00002886 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002887
Chris Lattner90ac28c2002-08-02 19:29:35 +00002888 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00002889 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00002890 // Replace: gep (gep %P, long B), long A, ...
2891 // With: T = long A+B; gep %P, T, ...
2892 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002893 Value *Sum;
2894 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2895 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00002896 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00002897 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00002898 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00002899 Sum = SO1;
2900 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00002901 // If they aren't the same type, then the input hasn't been processed
2902 // by the loop above yet (which canonicalizes sequential index types to
2903 // intptr_t). Just avoid transforming this until the input has been
2904 // normalized.
2905 if (SO1->getType() != GO1->getType())
2906 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002907 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00002908 }
Chris Lattner620ce142004-05-07 22:09:22 +00002909
Chris Lattnerab984842009-08-30 05:30:55 +00002910 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002911 if (Src->getNumOperands() == 2) {
2912 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00002913 GEP.setOperand(1, Sum);
2914 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00002915 }
Chris Lattnerab984842009-08-30 05:30:55 +00002916 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00002917 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00002918 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00002919 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00002920 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002921 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002922 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00002923 Indices.append(Src->op_begin()+1, Src->op_end());
2924 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00002925 }
2926
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002927 if (!Indices.empty())
2928 return (cast<GEPOperator>(&GEP)->isInBounds() &&
2929 Src->isInBounds()) ?
2930 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
2931 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002932 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00002933 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00002934 }
2935
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002936 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2937 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +00002938 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +00002939
Chris Lattner2de23192009-08-30 20:38:21 +00002940 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
2941 // want to change the gep until the bitcasts are eliminated.
2942 if (getBitCastOperand(X)) {
2943 Worklist.AddValue(PtrOp);
2944 return 0;
2945 }
2946
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002947 bool HasZeroPointerIndex = false;
2948 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2949 HasZeroPointerIndex = C->isZero();
2950
Chris Lattner963f4ba2009-08-30 20:36:46 +00002951 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2952 // into : GEP [10 x i8]* X, i32 0, ...
2953 //
2954 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2955 // into : GEP i8* X, ...
2956 //
2957 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00002958 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00002959 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
2960 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002961 if (const ArrayType *CATy =
2962 dyn_cast<ArrayType>(CPTy->getElementType())) {
2963 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2964 if (CATy->getElementType() == XTy->getElementType()) {
2965 // -> GEP i8* X, ...
2966 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002967 return cast<GEPOperator>(&GEP)->isInBounds() ?
2968 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
2969 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +00002970 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
2971 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +00002972 }
2973
2974 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002975 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00002976 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002977 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00002978 // At this point, we know that the cast source type is a pointer
2979 // to an array of the same type as the destination pointer
2980 // array. Because the array type is never stepped over (there
2981 // is a leading zero) we can fold the cast into this GEP.
2982 GEP.setOperand(0, X);
2983 return &GEP;
2984 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002985 }
2986 }
Chris Lattnereed48272005-09-13 00:40:14 +00002987 } else if (GEP.getNumOperands() == 2) {
2988 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00002989 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2990 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00002991 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
2992 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002993 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00002994 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
2995 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00002996 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00002997 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00002998 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002999 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3000 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003001 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00003002 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003003 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003004 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00003005
3006 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003007 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00003008 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003009 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00003010
Chris Lattner4de84762010-01-04 07:02:48 +00003011 if (TD && isa<ArrayType>(SrcElTy) &&
3012 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00003013 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00003014 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00003015
3016 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
3017 // allow either a mul, shift, or constant here.
3018 Value *NewIdx = 0;
3019 ConstantInt *Scale = 0;
3020 if (ArrayEltSize == 1) {
3021 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00003022 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00003023 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003024 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00003025 Scale = CI;
3026 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
3027 if (Inst->getOpcode() == Instruction::Shl &&
3028 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003029 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
3030 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00003031 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00003032 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00003033 NewIdx = Inst->getOperand(0);
3034 } else if (Inst->getOpcode() == Instruction::Mul &&
3035 isa<ConstantInt>(Inst->getOperand(1))) {
3036 Scale = cast<ConstantInt>(Inst->getOperand(1));
3037 NewIdx = Inst->getOperand(0);
3038 }
3039 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003040
Chris Lattner7835cdd2005-09-13 18:36:04 +00003041 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003042 // out, perform the transformation. Note, we don't know whether Scale is
3043 // signed or not. We'll use unsigned version of division/modulo
3044 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00003045 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003046 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003047 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003048 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00003049 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00003050 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
3051 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003052 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00003053 }
3054
3055 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00003056 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00003057 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00003058 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003059 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3060 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
3061 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00003062 // The NewGEP must be pointer typed, so must the old one -> BitCast
3063 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00003064 }
3065 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003066 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003067 }
Chris Lattner58407792009-01-09 04:53:57 +00003068
Chris Lattner46cd5a12009-01-09 05:44:56 +00003069 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00003070 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00003071 /// Y = gep X, <...constant indices...>
3072 /// into a gep of the original struct. This is important for SROA and alias
3073 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00003074 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003075 if (TD &&
3076 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003077 // Determine how much the GEP moves the pointer. We are guaranteed to get
3078 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00003079 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003080 int64_t Offset = OffsetV->getSExtValue();
3081
3082 // If this GEP instruction doesn't move the pointer, just replace the GEP
3083 // with a bitcast of the real input to the dest type.
3084 if (Offset == 0) {
3085 // If the bitcast is of an allocation, and the allocation will be
3086 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00003087 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00003088 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003089 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
3090 if (Instruction *I = visitBitCast(*BCI)) {
3091 if (I != BCI) {
3092 I->takeName(BCI);
3093 BCI->getParent()->getInstList().insert(BCI, I);
3094 ReplaceInstUsesWith(*BCI, I);
3095 }
3096 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00003097 }
Chris Lattner58407792009-01-09 04:53:57 +00003098 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00003099 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00003100 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00003101
3102 // Otherwise, if the offset is non-zero, we need to find out if there is a
3103 // field at Offset in 'A's type. If so, we can pull the cast through the
3104 // GEP.
3105 SmallVector<Value*, 8> NewIndices;
3106 const Type *InTy =
3107 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00003108 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003109 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
3110 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
3111 NewIndices.end()) :
3112 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
3113 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003114
3115 if (NGEP->getType() == GEP.getType())
3116 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00003117 NGEP->takeName(&GEP);
3118 return new BitCastInst(NGEP, GEP.getType());
3119 }
Chris Lattner58407792009-01-09 04:53:57 +00003120 }
3121 }
3122
Chris Lattner8a2a3112001-12-14 16:52:21 +00003123 return 0;
3124}
3125
Victor Hernandez66284e02009-10-24 04:23:03 +00003126Instruction *InstCombiner::visitFree(Instruction &FI) {
3127 Value *Op = FI.getOperand(1);
3128
3129 // free undef -> unreachable.
3130 if (isa<UndefValue>(Op)) {
3131 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00003132 new StoreInst(ConstantInt::getTrue(FI.getContext()),
3133 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00003134 return EraseInstFromFunction(FI);
3135 }
3136
3137 // If we have 'free null' delete the instruction. This can happen in stl code
3138 // when lots of inlining happens.
3139 if (isa<ConstantPointerNull>(Op))
3140 return EraseInstFromFunction(FI);
3141
Victor Hernandez046e78c2009-10-26 23:43:48 +00003142 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00003143 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003144 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
3145 if (Op->hasOneUse() && CI->hasOneUse()) {
3146 EraseInstFromFunction(FI);
3147 EraseInstFromFunction(*CI);
3148 return EraseInstFromFunction(*cast<Instruction>(Op));
3149 }
3150 } else {
3151 // Op is a call to malloc
3152 if (Op->hasOneUse()) {
3153 EraseInstFromFunction(FI);
3154 return EraseInstFromFunction(*cast<Instruction>(Op));
3155 }
3156 }
Dan Gohman7f712a12009-10-27 00:11:02 +00003157 }
Victor Hernandez66284e02009-10-24 04:23:03 +00003158
3159 return 0;
3160}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003161
Chris Lattner3284d1f2007-04-15 00:07:55 +00003162
Chris Lattner2f503e62005-01-31 05:36:43 +00003163
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003164Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3165 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00003166 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003167 BasicBlock *TrueDest;
3168 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00003169 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003170 !isa<Constant>(X)) {
3171 // Swap Destinations and condition...
3172 BI.setCondition(X);
3173 BI.setSuccessor(0, FalseDest);
3174 BI.setSuccessor(1, TrueDest);
3175 return &BI;
3176 }
3177
Reid Spencere4d87aa2006-12-23 06:05:41 +00003178 // Cannonicalize fcmp_one -> fcmp_oeq
3179 FCmpInst::Predicate FPred; Value *Y;
3180 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00003181 TrueDest, FalseDest)) &&
3182 BI.getCondition()->hasOneUse())
3183 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
3184 FPred == FCmpInst::FCMP_OGE) {
3185 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
3186 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
3187
3188 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003189 BI.setSuccessor(0, FalseDest);
3190 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003191 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003192 return &BI;
3193 }
3194
3195 // Cannonicalize icmp_ne -> icmp_eq
3196 ICmpInst::Predicate IPred;
3197 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00003198 TrueDest, FalseDest)) &&
3199 BI.getCondition()->hasOneUse())
3200 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
3201 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
3202 IPred == ICmpInst::ICMP_SGE) {
3203 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
3204 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
3205 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00003206 BI.setSuccessor(0, FalseDest);
3207 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003208 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00003209 return &BI;
3210 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003211
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003212 return 0;
3213}
Chris Lattner0864acf2002-11-04 16:18:53 +00003214
Chris Lattner46238a62004-07-03 00:26:11 +00003215Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3216 Value *Cond = SI.getCondition();
3217 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3218 if (I->getOpcode() == Instruction::Add)
3219 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3220 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3221 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00003222 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00003223 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00003224 AddRHS));
3225 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003226 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00003227 return &SI;
3228 }
3229 }
3230 return 0;
3231}
3232
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003233Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003234 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003235
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003236 if (!EV.hasIndices())
3237 return ReplaceInstUsesWith(EV, Agg);
3238
3239 if (Constant *C = dyn_cast<Constant>(Agg)) {
3240 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003241 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003242
3243 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00003244 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003245
3246 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3247 // Extract the element indexed by the first index out of the constant
3248 Value *V = C->getOperand(*EV.idx_begin());
3249 if (EV.getNumIndices() > 1)
3250 // Extract the remaining indices out of the constant indexed by the
3251 // first index
3252 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
3253 else
3254 return ReplaceInstUsesWith(EV, V);
3255 }
3256 return 0; // Can't handle other constants
3257 }
3258 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3259 // We're extracting from an insertvalue instruction, compare the indices
3260 const unsigned *exti, *exte, *insi, *inse;
3261 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3262 exte = EV.idx_end(), inse = IV->idx_end();
3263 exti != exte && insi != inse;
3264 ++exti, ++insi) {
3265 if (*insi != *exti)
3266 // The insert and extract both reference distinctly different elements.
3267 // This means the extract is not influenced by the insert, and we can
3268 // replace the aggregate operand of the extract with the aggregate
3269 // operand of the insert. i.e., replace
3270 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3271 // %E = extractvalue { i32, { i32 } } %I, 0
3272 // with
3273 // %E = extractvalue { i32, { i32 } } %A, 0
3274 return ExtractValueInst::Create(IV->getAggregateOperand(),
3275 EV.idx_begin(), EV.idx_end());
3276 }
3277 if (exti == exte && insi == inse)
3278 // Both iterators are at the end: Index lists are identical. Replace
3279 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3280 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3281 // with "i32 42"
3282 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
3283 if (exti == exte) {
3284 // The extract list is a prefix of the insert list. i.e. replace
3285 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3286 // %E = extractvalue { i32, { i32 } } %I, 1
3287 // with
3288 // %X = extractvalue { i32, { i32 } } %A, 1
3289 // %E = insertvalue { i32 } %X, i32 42, 0
3290 // by switching the order of the insert and extract (though the
3291 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003292 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
3293 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003294 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3295 insi, inse);
3296 }
3297 if (insi == inse)
3298 // The insert list is a prefix of the extract list
3299 // We can simply remove the common indices from the extract and make it
3300 // operate on the inserted value instead of the insertvalue result.
3301 // i.e., replace
3302 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3303 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3304 // with
3305 // %E extractvalue { i32 } { i32 42 }, 0
3306 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
3307 exti, exte);
3308 }
Chris Lattner7e606e22009-11-09 07:07:56 +00003309 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
3310 // We're extracting from an intrinsic, see if we're the only user, which
3311 // allows us to simplify multiple result intrinsics to simpler things that
3312 // just get one value..
3313 if (II->hasOneUse()) {
3314 // Check if we're grabbing the overflow bit or the result of a 'with
3315 // overflow' intrinsic. If it's the latter we can remove the intrinsic
3316 // and replace it with a traditional binary instruction.
3317 switch (II->getIntrinsicID()) {
3318 case Intrinsic::uadd_with_overflow:
3319 case Intrinsic::sadd_with_overflow:
3320 if (*EV.idx_begin() == 0) { // Normal result.
3321 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3322 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3323 EraseInstFromFunction(*II);
3324 return BinaryOperator::CreateAdd(LHS, RHS);
3325 }
3326 break;
3327 case Intrinsic::usub_with_overflow:
3328 case Intrinsic::ssub_with_overflow:
3329 if (*EV.idx_begin() == 0) { // Normal result.
3330 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3331 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3332 EraseInstFromFunction(*II);
3333 return BinaryOperator::CreateSub(LHS, RHS);
3334 }
3335 break;
3336 case Intrinsic::umul_with_overflow:
3337 case Intrinsic::smul_with_overflow:
3338 if (*EV.idx_begin() == 0) { // Normal result.
3339 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3340 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3341 EraseInstFromFunction(*II);
3342 return BinaryOperator::CreateMul(LHS, RHS);
3343 }
3344 break;
3345 default:
3346 break;
3347 }
3348 }
3349 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003350 // Can't simplify extracts from other values. Note that nested extracts are
3351 // already simplified implicitely by the above (extract ( extract (insert) )
3352 // will be translated into extract ( insert ( extract ) ) first and then just
3353 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003354 return 0;
3355}
3356
Chris Lattnera844fc4c2006-04-10 22:45:52 +00003357
Robert Bocchino1d7456d2006-01-13 22:48:06 +00003358
Chris Lattnerea1c4542004-12-08 23:43:58 +00003359
3360/// TryToSinkInstruction - Try to move the specified instruction from its
3361/// current block into the beginning of DestBlock, which can only happen if it's
3362/// safe to move the instruction past all of the instructions between it and the
3363/// end of its block.
3364static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3365 assert(I->hasOneUse() && "Invariants didn't hold!");
3366
Chris Lattner108e9022005-10-27 17:13:11 +00003367 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00003368 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00003369 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00003370
Chris Lattnerea1c4542004-12-08 23:43:58 +00003371 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00003372 if (isa<AllocaInst>(I) && I->getParent() ==
3373 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00003374 return false;
3375
Chris Lattner96a52a62004-12-09 07:14:34 +00003376 // We can only sink load instructions if there is nothing between the load and
3377 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00003378 if (I->mayReadFromMemory()) {
3379 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00003380 Scan != E; ++Scan)
3381 if (Scan->mayWriteToMemory())
3382 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00003383 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00003384
Dan Gohman02dea8b2008-05-23 21:05:58 +00003385 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00003386
Chris Lattner4bc5f802005-08-08 19:11:57 +00003387 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00003388 ++NumSunkInst;
3389 return true;
3390}
3391
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003392
3393/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
3394/// all reachable code to the worklist.
3395///
3396/// This has a couple of tricks to make the code faster and more powerful. In
3397/// particular, we constant fold and DCE instructions as we go, to avoid adding
3398/// them to the worklist (this significantly speeds up instcombine on code where
3399/// many instructions are dead or constant). Additionally, if we find a branch
3400/// whose condition is a known constant, we only visit the reachable successors.
3401///
Chris Lattner2ee743b2009-10-15 04:59:28 +00003402static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00003403 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00003404 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003405 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00003406 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00003407 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00003408 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00003409
3410 std::vector<Instruction*> InstrsForInstCombineWorklist;
3411 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003412
Chris Lattner2ee743b2009-10-15 04:59:28 +00003413 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
3414
Chris Lattner2c7718a2007-03-23 19:17:18 +00003415 while (!Worklist.empty()) {
3416 BB = Worklist.back();
3417 Worklist.pop_back();
3418
3419 // We have now visited this block! If we've already been here, ignore it.
3420 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00003421
Chris Lattner2c7718a2007-03-23 19:17:18 +00003422 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3423 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003424
Chris Lattner2c7718a2007-03-23 19:17:18 +00003425 // DCE instruction if trivially dead.
3426 if (isInstructionTriviallyDead(Inst)) {
3427 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00003428 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00003429 Inst->eraseFromParent();
3430 continue;
3431 }
3432
3433 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003434 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00003435 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003436 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
3437 << *Inst << '\n');
3438 Inst->replaceAllUsesWith(C);
3439 ++NumConstProp;
3440 Inst->eraseFromParent();
3441 continue;
3442 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00003443
3444
3445
3446 if (TD) {
3447 // See if we can constant fold its operands.
3448 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
3449 i != e; ++i) {
3450 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
3451 if (CE == 0) continue;
3452
3453 // If we already folded this constant, don't try again.
3454 if (!FoldedConstants.insert(CE))
3455 continue;
3456
Chris Lattner7b550cc2009-11-06 04:27:31 +00003457 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00003458 if (NewC && NewC != CE) {
3459 *i = NewC;
3460 MadeIRChange = true;
3461 }
3462 }
3463 }
3464
Devang Patel7fe1dec2008-11-19 18:56:50 +00003465
Chris Lattner67f7d542009-10-12 03:58:40 +00003466 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003467 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00003468
3469 // Recursively visit successors. If this is a branch or switch on a
3470 // constant, only visit the reachable successor.
3471 TerminatorInst *TI = BB->getTerminator();
3472 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3473 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3474 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00003475 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00003476 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00003477 continue;
3478 }
3479 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3480 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3481 // See if this is an explicit destination.
3482 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
3483 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00003484 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00003485 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00003486 continue;
3487 }
3488
3489 // Otherwise it is the default destination.
3490 Worklist.push_back(SI->getSuccessor(0));
3491 continue;
3492 }
3493 }
3494
3495 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3496 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003497 }
Chris Lattner67f7d542009-10-12 03:58:40 +00003498
3499 // Once we've found all of the instructions to add to instcombine's worklist,
3500 // add them in reverse order. This way instcombine will visit from the top
3501 // of the function down. This jives well with the way that it adds all uses
3502 // of instructions to the worklist after doing a transformation, thus avoiding
3503 // some N^2 behavior in pathological cases.
3504 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
3505 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00003506
3507 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003508}
3509
Chris Lattnerec9c3582007-03-03 02:04:50 +00003510bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003511 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00003512
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00003513 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3514 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00003515
Chris Lattnerb3d59702005-07-07 20:40:38 +00003516 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003517 // Do a depth-first traversal of the function, populate the worklist with
3518 // the reachable instructions. Ignore blocks that are not reachable. Keep
3519 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00003520 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00003521 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00003522
Chris Lattnerb3d59702005-07-07 20:40:38 +00003523 // Do a quick scan over the function. If we find any blocks that are
3524 // unreachable, remove any instructions inside of them. This prevents
3525 // the instcombine code from having to deal with some bad special cases.
3526 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3527 if (!Visited.count(BB)) {
3528 Instruction *Term = BB->getTerminator();
3529 while (Term != BB->begin()) { // Remove instrs bottom-up
3530 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00003531
Chris Lattnerbdff5482009-08-23 04:37:46 +00003532 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00003533 // A debug intrinsic shouldn't force another iteration if we weren't
3534 // going to do one without it.
3535 if (!isa<DbgInfoIntrinsic>(I)) {
3536 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003537 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00003538 }
Devang Patel228ebd02009-10-13 22:56:32 +00003539
Devang Patel228ebd02009-10-13 22:56:32 +00003540 // If I is not void type then replaceAllUsesWith undef.
3541 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00003542 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00003543 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00003544 I->eraseFromParent();
3545 }
3546 }
3547 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003548
Chris Lattner873ff012009-08-30 05:55:36 +00003549 while (!Worklist.isEmpty()) {
3550 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00003551 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00003552
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003553 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003554 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00003555 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00003556 EraseInstFromFunction(*I);
3557 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003558 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003559 continue;
3560 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003561
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003562 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003563 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00003564 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003565 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00003566
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003567 // Add operands to the worklist.
3568 ReplaceInstUsesWith(*I, C);
3569 ++NumConstProp;
3570 EraseInstFromFunction(*I);
3571 MadeIRChange = true;
3572 continue;
3573 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003574
Chris Lattnerea1c4542004-12-08 23:43:58 +00003575 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00003576 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00003577 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00003578 Instruction *UserInst = cast<Instruction>(I->use_back());
3579 BasicBlock *UserParent;
3580
3581 // Get the block the use occurs in.
3582 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3583 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
3584 else
3585 UserParent = UserInst->getParent();
3586
Chris Lattnerea1c4542004-12-08 23:43:58 +00003587 if (UserParent != BB) {
3588 bool UserIsSuccessor = false;
3589 // See if the user is one of our successors.
3590 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3591 if (*SI == UserParent) {
3592 UserIsSuccessor = true;
3593 break;
3594 }
3595
3596 // If the user is one of our immediate successors, and if that successor
3597 // only has us as a predecessors (we'd have to split the critical edge
3598 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00003599 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00003600 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003601 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00003602 }
3603 }
3604
Chris Lattner74381062009-08-30 07:44:24 +00003605 // Now that we have an instruction, try combining it to simplify it.
3606 Builder->SetInsertPoint(I->getParent(), I);
3607
Reid Spencera9b81012007-03-26 17:44:01 +00003608#ifndef NDEBUG
3609 std::string OrigI;
3610#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00003611 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00003612 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
3613
Chris Lattner90ac28c2002-08-02 19:29:35 +00003614 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003615 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003616 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003617 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00003618 DEBUG(errs() << "IC: Old = " << *I << '\n'
3619 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00003620
Chris Lattnerf523d062004-06-09 05:08:07 +00003621 // Everything uses the new instruction now.
3622 I->replaceAllUsesWith(Result);
3623
3624 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00003625 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003626 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003627
Chris Lattner6934a042007-02-11 01:23:03 +00003628 // Move the name to the new instruction first.
3629 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003630
3631 // Insert the new instruction into the basic block...
3632 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00003633 BasicBlock::iterator InsertPos = I;
3634
3635 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
3636 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
3637 ++InsertPos;
3638
3639 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003640
Chris Lattner7a1e9242009-08-30 06:13:40 +00003641 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00003642 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00003643#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00003644 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
3645 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00003646#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00003647
Chris Lattner90ac28c2002-08-02 19:29:35 +00003648 // If the instruction was modified, it's possible that it is now dead.
3649 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003650 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00003651 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003652 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00003653 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003654 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003655 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003656 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003657 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003658 }
3659 }
3660
Chris Lattner873ff012009-08-30 05:55:36 +00003661 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003662 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003663}
3664
Chris Lattnerec9c3582007-03-03 02:04:50 +00003665
3666bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00003667 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003668 TD = getAnalysisIfAvailable<TargetData>();
3669
Chris Lattner74381062009-08-30 07:44:24 +00003670
3671 /// Builder - This is an IRBuilder that automatically inserts new
3672 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003673 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00003674 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00003675 InstCombineIRInserter(Worklist));
3676 Builder = &TheBuilder;
3677
Chris Lattnerec9c3582007-03-03 02:04:50 +00003678 bool EverMadeChange = false;
3679
3680 // Iterate while there is work to do.
3681 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00003682 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00003683 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00003684
3685 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00003686 return EverMadeChange;
3687}
3688
Brian Gaeke96d4bf72004-07-27 17:43:21 +00003689FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003690 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003691}