blob: c73fb792d0529f1ab67f0c55b352f487dcf24747 [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
Chris Lattner33a61132006-05-06 09:00:16 +0000106
Chris Lattner4f98c562003-03-10 21:43:22 +0000107// SimplifyCommutative - This performs a few simplifications for commutative
108// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109//
Chris Lattner4f98c562003-03-10 21:43:22 +0000110// 1. Order operands such that they are listed from right (least complex) to
111// left (most complex). This puts constants before unary operators before
112// binary operators.
113//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000114// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
115// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000116//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000117bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000118 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000119 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000120 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000121
Chris Lattner4f98c562003-03-10 21:43:22 +0000122 if (!I.isAssociative()) return Changed;
Chris Lattner248a84b2010-01-05 07:04:23 +0000123
Chris Lattner4f98c562003-03-10 21:43:22 +0000124 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000125 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
126 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
127 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000128 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000129 cast<Constant>(I.getOperand(1)),
130 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000131 I.setOperand(0, Op->getOperand(0));
132 I.setOperand(1, Folded);
133 return true;
Chris Lattner248a84b2010-01-05 07:04:23 +0000134 }
135
136 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000137 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner248a84b2010-01-05 07:04:23 +0000138 Op->hasOneUse() && Op1->hasOneUse()) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000139 Constant *C1 = cast<Constant>(Op->getOperand(1));
140 Constant *C2 = cast<Constant>(Op1->getOperand(1));
141
142 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000143 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000144 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000145 Op1->getOperand(0),
146 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000147 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000148 I.setOperand(0, New);
149 I.setOperand(1, Folded);
150 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000151 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000152 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000153 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000154}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000155
Chris Lattner8d969642003-03-10 23:06:50 +0000156// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
157// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000158//
Chris Lattner02446fc2010-01-04 07:37:31 +0000159Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000160 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000161 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000162
Chris Lattner0ce85802004-12-14 20:08:06 +0000163 // Constants can be considered to be negated values if they can be folded.
164 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000165 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000166
167 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
168 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000169 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000170
Chris Lattner8d969642003-03-10 23:06:50 +0000171 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000172}
173
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
175// instruction if the LHS is a constant negative zero (which is the 'negate'
176// form).
177//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000178Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000179 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000180 return BinaryOperator::getFNegArgument(V);
181
182 // Constants can be considered to be negated values if they can be folded.
183 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000184 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000185
186 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
187 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000188 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000189
190 return 0;
191}
192
Chris Lattner48b59ec2009-10-26 15:40:07 +0000193/// isFreeToInvert - Return true if the specified value is free to invert (apply
194/// ~ to). This happens in cases where the ~ can be eliminated.
195static inline bool isFreeToInvert(Value *V) {
196 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000197 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000198 return true;
199
200 // Constants can be considered to be not'ed values.
201 if (isa<ConstantInt>(V))
202 return true;
203
204 // Compares can be inverted if they have a single use.
205 if (CmpInst *CI = dyn_cast<CmpInst>(V))
206 return CI->hasOneUse();
207
208 return false;
209}
210
211static inline Value *dyn_castNotVal(Value *V) {
212 // If this is not(not(x)) don't return that this is a not: we want the two
213 // not's to be folded first.
214 if (BinaryOperator::isNot(V)) {
215 Value *Operand = BinaryOperator::getNotArgument(V);
216 if (!isFreeToInvert(Operand))
217 return Operand;
218 }
Chris Lattner8d969642003-03-10 23:06:50 +0000219
220 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000221 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000222 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000223 return 0;
224}
225
Chris Lattner48b59ec2009-10-26 15:40:07 +0000226
227
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000228/// AddOne - Add one to a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000229static Constant *AddOne(Constant *C) {
Chris Lattner02446fc2010-01-04 07:37:31 +0000230 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000231}
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000232/// SubOne - Subtract one from a ConstantInt.
Dan Gohman186a6362009-08-12 16:04:34 +0000233static Constant *SubOne(ConstantInt *C) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000234 return ConstantInt::get(C->getContext(), C->getValue()-1);
Chris Lattner955f3312004-09-28 21:48:02 +0000235}
Reid Spencere7816b52007-03-08 01:52:58 +0000236
Dan Gohman45b4e482008-05-19 22:14:15 +0000237
Chris Lattner6e7ba452005-01-01 16:22:27 +0000238static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000239 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000240 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000241 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000242
Chris Lattner2eefe512004-04-09 19:05:30 +0000243 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000244 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
245 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000246
Chris Lattner2eefe512004-04-09 19:05:30 +0000247 if (Constant *SOC = dyn_cast<Constant>(SO)) {
248 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000249 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
250 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000251 }
252
253 Value *Op0 = SO, *Op1 = ConstOperand;
254 if (!ConstIsRHS)
255 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000256
Chris Lattner6e7ba452005-01-01 16:22:27 +0000257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000258 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
259 SO->getName()+".op");
260 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
261 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
262 SO->getName()+".cmp");
263 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
264 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
265 SO->getName()+".cmp");
266 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000267}
268
269// FoldOpIntoSelect - Given an instruction with a select as one operand and a
270// constant as the other operand, try to fold the binary operator into the
271// select arguments. This also works for Cast instructions, which obviously do
272// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000273Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000274 // Don't modify shared select instructions
275 if (!SI->hasOneUse()) return 0;
276 Value *TV = SI->getOperand(1);
277 Value *FV = SI->getOperand(2);
278
279 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000280 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +0000281 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000282
Chris Lattner80f43d32010-01-04 07:53:58 +0000283 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
284 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000285
Gabor Greif051a9502008-04-06 20:25:17 +0000286 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
287 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000288 }
289 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000290}
291
Chris Lattner4e998b22004-09-29 05:07:12 +0000292
Chris Lattner5d1704d2009-09-27 19:57:57 +0000293/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
294/// has a PHI node as operand #0, see if we can fold the instruction into the
295/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000296///
297/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
298/// that would normally be unprofitable because they strongly encourage jump
299/// threading.
300Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
301 bool AllowAggressive) {
302 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000303 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000304 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000305 if (NumPHIValues == 0 ||
306 // We normally only transform phis with a single use, unless we're trying
307 // hard to make jump threading happen.
308 (!PN->hasOneUse() && !AllowAggressive))
309 return 0;
310
311
Chris Lattner5d1704d2009-09-27 19:57:57 +0000312 // Check to see if all of the operands of the PHI are simple constants
313 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000314 // remember the BB it is in. If there is more than one or if *it* is a PHI,
315 // bail out. We don't do arbitrary constant expressions here because moving
316 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000317 BasicBlock *NonConstBB = 0;
318 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000319 if (!isa<Constant>(PN->getIncomingValue(i)) ||
320 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000321 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000322 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000323 NonConstBB = PN->getIncomingBlock(i);
324
325 // If the incoming non-constant value is in I's block, we have an infinite
326 // loop.
327 if (NonConstBB == I.getParent())
328 return 0;
329 }
330
331 // If there is exactly one non-constant value, we can insert a copy of the
332 // operation in that block. However, if this is a critical edge, we would be
333 // inserting the computation one some other paths (e.g. inside a loop). Only
334 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000335 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000336 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
337 if (!BI || !BI->isUnconditional()) return 0;
338 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000339
340 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000341 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000342 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000343 InsertNewInstBefore(NewPN, *PN);
344 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000345
346 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000347 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
348 // We only currently try to fold the condition of a select when it is a phi,
349 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000350 Value *TrueV = SI->getTrueValue();
351 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000352 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000353 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000354 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000355 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
356 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000357 Value *InV = 0;
358 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000359 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000360 } else {
361 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000362 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
363 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000364 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000365 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000366 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000367 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000368 }
369 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000370 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000371 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000372 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000373 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000374 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000375 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000376 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000377 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000378 } else {
379 assert(PN->getIncomingBlock(i) == NonConstBB);
380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000381 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000382 PN->getIncomingValue(i), C, "phitmp",
383 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000384 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000385 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 CI->getPredicate(),
387 PN->getIncomingValue(i), C, "phitmp",
388 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000389 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000390 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000391
392 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000393 }
394 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000395 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000396 } else {
397 CastInst *CI = cast<CastInst>(&I);
398 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000399 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000400 Value *InV;
401 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000402 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000403 } else {
404 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000405 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000406 I.getType(), "phitmp",
407 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000408 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000409 }
410 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000411 }
412 }
413 return ReplaceInstUsesWith(I, NewPN);
414}
415
Chris Lattner2454a2e2008-01-29 06:52:45 +0000416
Reid Spencere4d87aa2006-12-23 06:05:41 +0000417/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000418/// are carefully arranged to allow folding of expressions such as:
419///
420/// (A < B) | (A > B) --> (A != B)
421///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000422/// Note that this is only valid if the first and second predicates have the
423/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000424///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000425/// Three bits are used to represent the condition, as follows:
426/// 0 A > B
427/// 1 A == B
428/// 2 A < B
429///
430/// <=> Value Definition
431/// 000 0 Always false
432/// 001 1 A > B
433/// 010 2 A == B
434/// 011 3 A >= B
435/// 100 4 A < B
436/// 101 5 A != B
437/// 110 6 A <= B
438/// 111 7 Always true
439///
440static unsigned getICmpCode(const ICmpInst *ICI) {
441 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000442 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443 case ICmpInst::ICMP_UGT: return 1; // 001
444 case ICmpInst::ICMP_SGT: return 1; // 001
445 case ICmpInst::ICMP_EQ: return 2; // 010
446 case ICmpInst::ICMP_UGE: return 3; // 011
447 case ICmpInst::ICMP_SGE: return 3; // 011
448 case ICmpInst::ICMP_ULT: return 4; // 100
449 case ICmpInst::ICMP_SLT: return 4; // 100
450 case ICmpInst::ICMP_NE: return 5; // 101
451 case ICmpInst::ICMP_ULE: return 6; // 110
452 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000453 // True -> 7
454 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000455 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000456 return 0;
457 }
458}
459
Evan Cheng8db90722008-10-14 17:15:11 +0000460/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
461/// predicate into a three bit mask. It also returns whether it is an ordered
462/// predicate by reference.
463static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
464 isOrdered = false;
465 switch (CC) {
466 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
467 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +0000468 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
469 case FCmpInst::FCMP_UGT: return 1; // 001
470 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
471 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +0000472 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
473 case FCmpInst::FCMP_UGE: return 3; // 011
474 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
475 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +0000476 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
477 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +0000478 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
479 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +0000480 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +0000481 default:
482 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +0000483 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +0000484 return 0;
485 }
486}
487
Reid Spencere4d87aa2006-12-23 06:05:41 +0000488/// getICmpValue - This is the complement of getICmpCode, which turns an
489/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +0000490/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +0000491/// of predicate to use in the new icmp instruction.
Chris Lattnera317e042010-01-05 06:59:49 +0000492static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
493 switch (Code) {
494 default: assert(0 && "Illegal ICmp code!");
495 case 0:
496 return ConstantInt::getFalse(LHS->getContext());
497 case 1:
498 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000499 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000500 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
501 case 2:
502 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
503 case 3:
504 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000505 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000506 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
507 case 4:
508 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000509 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000510 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
511 case 5:
512 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
513 case 6:
514 if (Sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000515 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Chris Lattnera317e042010-01-05 06:59:49 +0000516 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
517 case 7:
518 return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000519 }
520}
521
Evan Cheng8db90722008-10-14 17:15:11 +0000522/// getFCmpValue - This is the complement of getFCmpCode, which turns an
523/// opcode and two operands into either a FCmp instruction. isordered is passed
524/// in to determine which kind of predicate to use in the new fcmp instruction.
525static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +0000526 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +0000527 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000528 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +0000529 case 0:
530 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000531 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000532 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000533 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000534 case 1:
535 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000536 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000537 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000538 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000539 case 2:
540 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000541 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000542 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000543 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000544 case 3:
545 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000546 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000547 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000548 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000549 case 4:
550 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000551 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000552 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000553 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000554 case 5:
555 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000556 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000557 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000558 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +0000559 case 6:
560 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000561 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +0000562 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000563 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +0000564 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +0000565 }
566}
567
Chris Lattnerb9553d62008-11-16 04:55:20 +0000568/// PredicatesFoldable - Return true if both predicates match sign or if at
569/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +0000571 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
572 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
573 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000574}
575
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000576// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
577// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +0000578// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000579Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000580 ConstantInt *OpRHS,
581 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000582 BinaryOperator &TheAnd) {
583 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +0000584 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +0000585 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000586 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +0000587
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000588 switch (Op->getOpcode()) {
589 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000590 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000591 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +0000592 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000593 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000594 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000595 }
596 break;
597 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +0000598 if (Together == AndRHS) // (X | C) & C --> C
599 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +0000600
Chris Lattner6e7ba452005-01-01 16:22:27 +0000601 if (Op->hasOneUse() && Together != OpRHS) {
602 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +0000603 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +0000604 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000605 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000606 }
607 break;
608 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +0000609 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000610 // Adding a one to a single bit bit-field should be turned into an XOR
611 // of the bit. First thing to check is to see if this AND is with a
612 // single bit constant.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000613 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000614
Chris Lattnerc6334b92010-01-05 06:03:12 +0000615 // If there is only one bit set.
616 if (AndRHSV.isPowerOf2()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000617 // Ok, at this point, we know that we are masking the result of the
618 // ADD down to exactly one bit. If the constant we are adding has
619 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000620 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000621
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000622 // Check to see if any bits below the one bit set in AndRHSV are set.
623 if ((AddRHS & (AndRHSV-1)) == 0) {
624 // If not, the only thing that can effect the output of the AND is
625 // the bit specified by AndRHSV. If that bit is set, the effect of
626 // the XOR is to toggle the bit. If it is clear, then the ADD has
627 // no effect.
628 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
629 TheAnd.setOperand(0, X);
630 return &TheAnd;
631 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000632 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +0000633 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +0000634 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000635 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000636 }
637 }
638 }
639 }
640 break;
Chris Lattner62a355c2003-09-19 19:05:02 +0000641
642 case Instruction::Shl: {
643 // We know that the AND will not produce any of the bits shifted in, so if
644 // the anded constant includes them, clear them now!
645 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000646 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000647 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000648 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000649 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
650 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +0000651
Zhou Sheng290bec52007-03-29 08:15:12 +0000652 if (CI->getValue() == ShlMask) {
653 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +0000654 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
655 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +0000656 TheAnd.setOperand(1, CI);
657 return &TheAnd;
658 }
659 break;
Misha Brukmanfd939082005-04-21 23:48:37 +0000660 }
Chris Lattner4de84762010-01-04 07:02:48 +0000661 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +0000662 // We know that the AND will not produce any of the bits shifted in, so if
663 // the anded constant includes them, clear them now! This only applies to
664 // unsigned shifts, because a signed shr may bring in set bits!
665 //
Zhou Sheng290bec52007-03-29 08:15:12 +0000666 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000667 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000668 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000669 ConstantInt *CI = ConstantInt::get(Op->getContext(),
670 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +0000671
Zhou Sheng290bec52007-03-29 08:15:12 +0000672 if (CI->getValue() == ShrMask) {
673 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +0000674 return ReplaceInstUsesWith(TheAnd, Op);
675 } else if (CI != AndRHS) {
676 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
677 return &TheAnd;
678 }
679 break;
680 }
681 case Instruction::AShr:
682 // Signed shr.
683 // See if this is shifting in some sign extension, then masking it out
684 // with an and.
685 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +0000686 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000687 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +0000688 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +0000689 Constant *C = ConstantInt::get(Op->getContext(),
690 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +0000691 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +0000692 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +0000693 // Make the argument unsigned.
694 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +0000695 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000696 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +0000697 }
Chris Lattner62a355c2003-09-19 19:05:02 +0000698 }
699 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000700 }
701 return 0;
702}
703
Chris Lattner8b170942002-08-09 23:47:40 +0000704
Chris Lattnera96879a2004-09-29 17:40:11 +0000705/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
706/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +0000707/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
708/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +0000709/// insert new instructions.
710Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000711 bool isSigned, bool Inside,
712 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000713 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +0000714 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +0000715 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000716
Chris Lattnera96879a2004-09-29 17:40:11 +0000717 if (Inside) {
718 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000719 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +0000720
Reid Spencere4d87aa2006-12-23 06:05:41 +0000721 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000722 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +0000723 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +0000724 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000725 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000726 }
727
728 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +0000729 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +0000730 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000731 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000732 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000733 }
734
735 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000736 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +0000737
Reid Spencere4e40032007-03-21 23:19:50 +0000738 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +0000739 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000740 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000741 ICmpInst::Predicate pred = (isSigned ?
742 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000743 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000744 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000745
Reid Spencere4e40032007-03-21 23:19:50 +0000746 // Emit V-Lo >u Hi-1-Lo
747 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000748 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +0000749 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +0000750 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000751 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +0000752}
753
Chris Lattner7203e152005-09-18 07:22:02 +0000754// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
755// any number of 0s on either side. The 1s are allowed to wrap from LSB to
756// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
757// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +0000758static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +0000759 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +0000760 uint32_t BitWidth = Val->getType()->getBitWidth();
761 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +0000762
763 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +0000764 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +0000765 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +0000766 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +0000767 return true;
768}
769
Chris Lattner7203e152005-09-18 07:22:02 +0000770/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
771/// where isSub determines whether the operator is a sub. If we can fold one of
772/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +0000773///
774/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
775/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
776/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
777///
778/// return (A +/- B).
779///
780Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000781 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000782 Instruction &I) {
783 Instruction *LHSI = dyn_cast<Instruction>(LHS);
784 if (!LHSI || LHSI->getNumOperands() != 2 ||
785 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
786
787 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
788
789 switch (LHSI->getOpcode()) {
790 default: return 0;
791 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000792 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +0000793 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +0000794 if ((Mask->getValue().countLeadingZeros() +
795 Mask->getValue().countPopulation()) ==
796 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +0000797 break;
798
799 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
800 // part, we don't need any explicit masks to take them out of A. If that
801 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +0000802 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +0000803 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +0000804 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +0000805 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +0000806 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +0000807 break;
808 }
809 }
Chris Lattnerc8e77562005-09-18 04:24:45 +0000810 return 0;
811 case Instruction::Or:
812 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +0000813 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +0000814 if ((Mask->getValue().countLeadingZeros() +
815 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +0000816 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +0000817 break;
818 return 0;
819 }
820
Chris Lattnerc8e77562005-09-18 04:24:45 +0000821 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +0000822 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
823 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +0000824}
825
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000826/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
827Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
828 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +0000829 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
830
831 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
832 if (PredicatesFoldable(LHSCC, RHSCC)) {
833 if (LHS->getOperand(0) == RHS->getOperand(1) &&
834 LHS->getOperand(1) == RHS->getOperand(0))
835 LHS->swapOperands();
836 if (LHS->getOperand(0) == RHS->getOperand(0) &&
837 LHS->getOperand(1) == RHS->getOperand(1)) {
838 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
839 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
840 bool isSigned = LHS->isSigned() || RHS->isSigned();
841 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
842 if (Instruction *I = dyn_cast<Instruction>(RV))
843 return I;
844 // Otherwise, it's a constant boolean value.
845 return ReplaceInstUsesWith(I, RV);
846 }
847 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000848
Chris Lattnerea065fb2008-11-16 05:10:52 +0000849 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +0000850 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
851 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
852 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
853 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +0000854
Chris Lattner3f40e232009-11-29 00:51:17 +0000855 if (LHSCst == RHSCst && LHSCC == RHSCC) {
856 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
857 // where C is a power of 2
858 if (LHSCC == ICmpInst::ICMP_ULT &&
859 LHSCst->getValue().isPowerOf2()) {
860 Value *NewOr = Builder->CreateOr(Val, Val2);
861 return new ICmpInst(LHSCC, NewOr, LHSCst);
862 }
863
864 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
865 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
866 Value *NewOr = Builder->CreateOr(Val, Val2);
867 return new ICmpInst(LHSCC, NewOr, LHSCst);
868 }
Chris Lattnerea065fb2008-11-16 05:10:52 +0000869 }
870
871 // From here on, we only handle:
872 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
873 if (Val != Val2) return 0;
874
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000875 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
876 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
877 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
878 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
879 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
880 return 0;
881
882 // We can't fold (ugt x, C) & (sgt x, C2).
883 if (!PredicatesFoldable(LHSCC, RHSCC))
884 return 0;
885
886 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +0000887 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +0000888 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000889 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +0000890 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +0000891 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000892 else
Chris Lattneraa3e1572008-11-16 05:14:43 +0000893 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
894
895 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000896 std::swap(LHS, RHS);
897 std::swap(LHSCst, RHSCst);
898 std::swap(LHSCC, RHSCC);
899 }
900
901 // At this point, we know we have have two icmp instructions
902 // comparing a value against two constants and and'ing the result
903 // together. Because of the above check, we know that we only have
904 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
Chris Lattnera317e042010-01-05 06:59:49 +0000905 // (from the icmp folding check above), that the two constants
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000906 // are not equal and that the larger constant is on the RHS
907 assert(LHSCst != RHSCst && "Compares not folded above?");
908
909 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000911 case ICmpInst::ICMP_EQ:
912 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000914 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
915 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
916 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000918 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
919 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
920 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
921 return ReplaceInstUsesWith(I, LHS);
922 }
923 case ICmpInst::ICMP_NE:
924 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000925 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000926 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +0000927 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000928 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000929 break; // (X != 13 & X u< 15) -> no change
930 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +0000931 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000932 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000933 break; // (X != 13 & X s< 15) -> no change
934 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
935 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
936 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
937 return ReplaceInstUsesWith(I, RHS);
938 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +0000939 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +0000940 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +0000941 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000942 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +0000943 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000944 }
945 break; // (X != 13 & X != 15) -> no change
946 }
947 break;
948 case ICmpInst::ICMP_ULT:
949 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000950 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000951 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
952 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000953 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000954 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
955 break;
956 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
957 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
958 return ReplaceInstUsesWith(I, LHS);
959 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
960 break;
961 }
962 break;
963 case ICmpInst::ICMP_SLT:
964 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000965 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000966 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
967 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +0000968 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000969 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
970 break;
971 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
972 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
973 return ReplaceInstUsesWith(I, LHS);
974 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
975 break;
976 }
977 break;
978 case ICmpInst::ICMP_UGT:
979 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000980 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000981 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
982 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
983 return ReplaceInstUsesWith(I, RHS);
984 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
985 break;
986 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +0000987 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000988 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000989 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +0000990 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +0000991 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +0000992 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000993 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
994 break;
995 }
996 break;
997 case ICmpInst::ICMP_SGT:
998 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000999 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001000 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1001 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1002 return ReplaceInstUsesWith(I, RHS);
1003 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1004 break;
1005 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00001006 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001007 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001008 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00001009 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00001010 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001011 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001012 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1013 break;
1014 }
1015 break;
1016 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001017
1018 return 0;
1019}
1020
Chris Lattner42d1be02009-07-23 05:14:02 +00001021Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
1022 FCmpInst *RHS) {
1023
1024 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1025 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1026 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1027 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1028 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1029 // If either of the constants are nans, then the whole thing returns
1030 // false.
1031 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001032 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001033 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00001034 LHS->getOperand(0), RHS->getOperand(0));
1035 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00001036
1037 // Handle vector zeros. This occurs because the canonical form of
1038 // "fcmp ord x,x" is "fcmp ord x, 0".
1039 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1040 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001041 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00001042 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00001043 return 0;
1044 }
1045
1046 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1047 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1048 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1049
1050
1051 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1052 // Swap RHS operands to match LHS.
1053 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1054 std::swap(Op1LHS, Op1RHS);
1055 }
1056
1057 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1058 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1059 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001060 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00001061
1062 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00001063 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001064 if (Op0CC == FCmpInst::FCMP_TRUE)
1065 return ReplaceInstUsesWith(I, RHS);
1066 if (Op1CC == FCmpInst::FCMP_TRUE)
1067 return ReplaceInstUsesWith(I, LHS);
1068
1069 bool Op0Ordered;
1070 bool Op1Ordered;
1071 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1072 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1073 if (Op1Pred == 0) {
1074 std::swap(LHS, RHS);
1075 std::swap(Op0Pred, Op1Pred);
1076 std::swap(Op0Ordered, Op1Ordered);
1077 }
1078 if (Op0Pred == 0) {
1079 // uno && ueq -> uno && (uno || eq) -> ueq
1080 // ord && olt -> ord && (ord && lt) -> olt
1081 if (Op0Ordered == Op1Ordered)
1082 return ReplaceInstUsesWith(I, RHS);
1083
1084 // uno && oeq -> uno && (ord && eq) -> false
1085 // uno && ord -> false
1086 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00001087 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00001088 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00001089 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00001090 }
1091 }
1092
1093 return 0;
1094}
1095
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001096
Chris Lattner7e708292002-06-25 16:13:24 +00001097Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001098 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001100
Chris Lattnerd06094f2009-11-10 00:55:12 +00001101 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1102 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001103
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001104 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00001105 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001106 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00001107 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00001108
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001110 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001111 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001112
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001113 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001115 Value *Op0LHS = Op0I->getOperand(0);
1116 Value *Op0RHS = Op0I->getOperand(1);
1117 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001118 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001119 case Instruction::Xor:
1120 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00001121 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00001122 if (!Op0I->hasOneUse()) break;
1123
1124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1125 // Not masking anything out for the LHS, move to RHS.
1126 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1127 Op0RHS->getName()+".masked");
1128 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1129 }
1130 if (!isa<Constant>(Op0RHS) &&
1131 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1132 // Not masking anything out for the RHS, move to LHS.
1133 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1134 Op0LHS->getName()+".masked");
1135 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001136 }
1137
Chris Lattner6e7ba452005-01-01 16:22:27 +00001138 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001139 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001140 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1141 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1142 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1143 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001144 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00001145 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001146 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001147 break;
1148
1149 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001150 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1151 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1152 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1153 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001154 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001155
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001156 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1157 // has 1's for all bits that the subtraction with A might affect.
1158 if (Op0I->hasOneUse()) {
1159 uint32_t BitWidth = AndRHSMask.getBitWidth();
1160 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1161 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1162
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001163 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00001164 if (!(A && A->isZero()) && // avoid infinite recursion.
1165 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00001166 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001167 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1168 }
1169 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001170 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001171
1172 case Instruction::Shl:
1173 case Instruction::LShr:
1174 // (1 << x) & 1 --> zext(x == 0)
1175 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00001176 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00001177 Value *NewICmp =
1178 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00001179 return new ZExtInst(NewICmp, I.getType());
1180 }
1181 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001182 }
1183
Chris Lattner58403262003-07-23 19:25:52 +00001184 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001185 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001186 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001187 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00001188 // If this is an integer truncation or change from signed-to-unsigned, and
1189 // if the source is an and/or with immediate, transform it. This
1190 // frequently occurs for bitfield accesses.
1191 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001192 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00001193 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00001194 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00001195 if (CastOp->getOpcode() == Instruction::And) {
1196 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00001197 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1198 // This will fold the two constants together, which may allow
1199 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00001200 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00001201 CastOp->getOperand(0), I.getType(),
1202 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00001203 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00001204 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001205 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001206 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00001207 } else if (CastOp->getOpcode() == Instruction::Or) {
1208 // Change: and (cast (or X, C1) to T), C2
1209 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00001210 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001211 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001212 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00001213 return ReplaceInstUsesWith(I, AndRHS);
1214 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001215 }
Chris Lattner2b83af22005-08-07 07:03:10 +00001216 }
Chris Lattner06782f82003-07-23 19:36:21 +00001217 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001218
1219 // Try to fold constant and into select arguments.
1220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001221 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001222 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001223 if (isa<PHINode>(Op0))
1224 if (Instruction *NV = FoldOpIntoPhi(I))
1225 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001226 }
1227
Chris Lattner5b62aa72004-06-18 06:07:51 +00001228
Misha Brukmancb6267b2004-07-30 12:50:08 +00001229 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00001230 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1231 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1232 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1233 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1234 I.getName()+".demorgan");
1235 return BinaryOperator::CreateNot(Or);
1236 }
1237
Chris Lattner2082ad92006-02-13 23:07:23 +00001238 {
Chris Lattner003b6202007-06-15 05:58:24 +00001239 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001240 // (A|B) & ~(A&B) -> A^B
1241 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1242 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1243 ((A == C && B == D) || (A == D && B == C)))
1244 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00001245
Chris Lattnerd06094f2009-11-10 00:55:12 +00001246 // ~(A&B) & (A|B) -> A^B
1247 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1248 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1249 ((A == C && B == D) || (A == D && B == C)))
1250 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00001251
1252 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001253 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001254 if (A == Op1) { // (A^B)&A -> A&(A^B)
1255 I.swapOperands(); // Simplify below
1256 std::swap(Op0, Op1);
1257 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1258 cast<BinaryOperator>(Op0)->swapOperands();
1259 I.swapOperands(); // Simplify below
1260 std::swap(Op0, Op1);
1261 }
1262 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001263
Chris Lattner64daab52006-04-01 08:03:55 +00001264 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001265 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00001266 if (B == Op0) { // B&(A^B) -> B&(B^A)
1267 cast<BinaryOperator>(Op1)->swapOperands();
1268 std::swap(A, B);
1269 }
Chris Lattner74381062009-08-30 07:44:24 +00001270 if (A == Op0) // A&(A^B) -> A & ~B
1271 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00001272 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00001273
1274 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00001275 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1276 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001277 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00001278 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1279 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00001280 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00001281 }
1282
Chris Lattnera317e042010-01-05 06:59:49 +00001283 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00001284 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1285 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
1286 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00001287
Chris Lattner6fc205f2006-05-05 06:39:07 +00001288 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001289 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1290 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1291 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
1292 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00001293 if (SrcTy == Op1C->getOperand(0)->getType() &&
1294 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001295 // Only do this if the casts both really cause code to be generated.
Chris Lattner80f43d32010-01-04 07:53:58 +00001296 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1297 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00001298 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00001299 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00001300 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
1301 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001302 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00001303 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001304 }
Chris Lattnere511b742006-11-14 07:46:50 +00001305
1306 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001307 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1308 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1309 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001310 SI0->getOperand(1) == SI1->getOperand(1) &&
1311 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001312 Value *NewOp =
1313 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1314 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001315 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00001316 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00001317 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00001318 }
1319
Evan Cheng8db90722008-10-14 17:15:11 +00001320 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00001321 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00001322 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1323 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
1324 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00001325 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00001326
Chris Lattner7e708292002-06-25 16:13:24 +00001327 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001328}
1329
Chris Lattner8c34cd22008-10-05 02:13:19 +00001330/// CollectBSwapParts - Analyze the specified subexpression and see if it is
1331/// capable of providing pieces of a bswap. The subexpression provides pieces
1332/// of a bswap if it is proven that each of the non-zero bytes in the output of
1333/// the expression came from the corresponding "byte swapped" byte in some other
1334/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1335/// we know that the expression deposits the low byte of %X into the high byte
1336/// of the bswap result and that all other bytes are zero. This expression is
1337/// accepted, the high byte of ByteValues is set to X to indicate a correct
1338/// match.
1339///
1340/// This function returns true if the match was unsuccessful and false if so.
1341/// On entry to the function the "OverallLeftShift" is a signed integer value
1342/// indicating the number of bytes that the subexpression is later shifted. For
1343/// example, if the expression is later right shifted by 16 bits, the
1344/// OverallLeftShift value would be -2 on entry. This is used to specify which
1345/// byte of ByteValues is actually being set.
1346///
1347/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1348/// byte is masked to zero by a user. For example, in (X & 255), X will be
1349/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1350/// this function to working on up to 32-byte (256 bit) values. ByteMask is
1351/// always in the local (OverallLeftShift) coordinate space.
1352///
1353static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1354 SmallVector<Value*, 8> &ByteValues) {
1355 if (Instruction *I = dyn_cast<Instruction>(V)) {
1356 // If this is an or instruction, it may be an inner node of the bswap.
1357 if (I->getOpcode() == Instruction::Or) {
1358 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1359 ByteValues) ||
1360 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1361 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001362 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00001363
1364 // If this is a logical shift by a constant multiple of 8, recurse with
1365 // OverallLeftShift and ByteMask adjusted.
1366 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1367 unsigned ShAmt =
1368 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1369 // Ensure the shift amount is defined and of a byte value.
1370 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1371 return true;
1372
1373 unsigned ByteShift = ShAmt >> 3;
1374 if (I->getOpcode() == Instruction::Shl) {
1375 // X << 2 -> collect(X, +2)
1376 OverallLeftShift += ByteShift;
1377 ByteMask >>= ByteShift;
1378 } else {
1379 // X >>u 2 -> collect(X, -2)
1380 OverallLeftShift -= ByteShift;
1381 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00001382 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00001383 }
1384
1385 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1386 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1387
1388 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1389 ByteValues);
1390 }
1391
1392 // If this is a logical 'and' with a mask that clears bytes, clear the
1393 // corresponding bytes in ByteMask.
1394 if (I->getOpcode() == Instruction::And &&
1395 isa<ConstantInt>(I->getOperand(1))) {
1396 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1397 unsigned NumBytes = ByteValues.size();
1398 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1399 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1400
1401 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1402 // If this byte is masked out by a later operation, we don't care what
1403 // the and mask is.
1404 if ((ByteMask & (1 << i)) == 0)
1405 continue;
1406
1407 // If the AndMask is all zeros for this byte, clear the bit.
1408 APInt MaskB = AndMask & Byte;
1409 if (MaskB == 0) {
1410 ByteMask &= ~(1U << i);
1411 continue;
1412 }
1413
1414 // If the AndMask is not all ones for this byte, it's not a bytezap.
1415 if (MaskB != Byte)
1416 return true;
1417
1418 // Otherwise, this byte is kept.
1419 }
1420
1421 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1422 ByteValues);
1423 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001424 }
1425
Chris Lattner8c34cd22008-10-05 02:13:19 +00001426 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1427 // the input value to the bswap. Some observations: 1) if more than one byte
1428 // is demanded from this input, then it could not be successfully assembled
1429 // into a byteswap. At least one of the two bytes would not be aligned with
1430 // their ultimate destination.
1431 if (!isPowerOf2_32(ByteMask)) return true;
1432 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001433
Chris Lattner8c34cd22008-10-05 02:13:19 +00001434 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1435 // is demanded, it needs to go into byte 0 of the result. This means that the
1436 // byte needs to be shifted until it lands in the right byte bucket. The
1437 // shift amount depends on the position: if the byte is coming from the high
1438 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1439 // low part, it must be shifted left.
1440 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1441 if (InputByteNo < ByteValues.size()/2) {
1442 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1443 return true;
1444 } else {
1445 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1446 return true;
1447 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00001448
1449 // If the destination byte value is already defined, the values are or'd
1450 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00001451 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00001452 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00001453 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00001454 return false;
1455}
1456
1457/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1458/// If so, insert the new bswap intrinsic and return it.
1459Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00001460 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00001461 if (!ITy || ITy->getBitWidth() % 16 ||
1462 // ByteMask only allows up to 32-byte values.
1463 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00001464 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00001465
1466 /// ByteValues - For each byte of the result, we keep track of which value
1467 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00001468 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00001469 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001470
1471 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00001472 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1473 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00001474 return 0;
1475
1476 // Check to see if all of the bytes come from the same value.
1477 Value *V = ByteValues[0];
1478 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1479
1480 // Check to make sure that all of the bytes come from the same value.
1481 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1482 if (ByteValues[i] != V)
1483 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00001484 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00001485 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00001486 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00001487 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00001488}
1489
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001490/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1491/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1492/// we can simplify this expression to "cond ? C : D or B".
1493static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00001494 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00001495 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00001496 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001497 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001498 return 0;
1499
Chris Lattnera6a474d2008-11-16 04:26:55 +00001500 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00001501 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001502 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00001503 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001504 return SelectInst::Create(Cond, C, B);
1505 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00001506 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001507 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00001508 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00001509 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001510 return 0;
1511}
Chris Lattnerafe91a52006-06-15 19:07:26 +00001512
Chris Lattner69d4ced2008-11-16 05:20:07 +00001513/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1514Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1515 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnera317e042010-01-05 06:59:49 +00001516 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1517
1518 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1519 if (PredicatesFoldable(LHSCC, RHSCC)) {
1520 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1521 LHS->getOperand(1) == RHS->getOperand(0))
1522 LHS->swapOperands();
1523 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1524 LHS->getOperand(1) == RHS->getOperand(1)) {
1525 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1526 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1527 bool isSigned = LHS->isSigned() || RHS->isSigned();
1528 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1529 if (Instruction *I = dyn_cast<Instruction>(RV))
1530 return I;
1531 // Otherwise, it's a constant boolean value.
1532 return ReplaceInstUsesWith(I, RV);
1533 }
1534 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001535
1536 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattnera317e042010-01-05 06:59:49 +00001537 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1538 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1539 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1540 if (LHSCst == 0 || RHSCst == 0) return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00001541
Chris Lattner3f40e232009-11-29 00:51:17 +00001542 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1543 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1544 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1545 Value *NewOr = Builder->CreateOr(Val, Val2);
1546 return new ICmpInst(LHSCC, NewOr, LHSCst);
1547 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00001548
1549 // From here on, we only handle:
1550 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1551 if (Val != Val2) return 0;
1552
1553 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1554 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1555 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1556 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1557 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1558 return 0;
1559
1560 // We can't fold (ugt x, C) | (sgt x, C2).
1561 if (!PredicatesFoldable(LHSCC, RHSCC))
1562 return 0;
1563
1564 // Ensure that the larger constant is on the RHS.
1565 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00001566 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00001567 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00001568 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00001569 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1570 else
1571 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1572
1573 if (ShouldSwap) {
1574 std::swap(LHS, RHS);
1575 std::swap(LHSCst, RHSCst);
1576 std::swap(LHSCC, RHSCC);
1577 }
1578
1579 // At this point, we know we have have two icmp instructions
1580 // comparing a value against two constants and or'ing the result
1581 // together. Because of the above check, we know that we only have
1582 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
Chris Lattnera317e042010-01-05 06:59:49 +00001583 // icmp folding check above), that the two constants are not
Chris Lattner69d4ced2008-11-16 05:20:07 +00001584 // equal.
1585 assert(LHSCst != RHSCst && "Compares not folded above?");
1586
1587 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001588 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001589 case ICmpInst::ICMP_EQ:
1590 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001591 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001592 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00001593 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001594 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00001595 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00001596 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00001597 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001598 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001599 }
1600 break; // (X == 13 | X == 15) -> no change
1601 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1602 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1603 break;
1604 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1605 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1606 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1607 return ReplaceInstUsesWith(I, RHS);
1608 }
1609 break;
1610 case ICmpInst::ICMP_NE:
1611 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001612 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001613 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1614 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1615 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1616 return ReplaceInstUsesWith(I, LHS);
1617 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1618 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1619 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001620 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001621 }
1622 break;
1623 case ICmpInst::ICMP_ULT:
1624 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001625 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001626 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1627 break;
1628 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1629 // If RHSCst is [us]MAXINT, it is always false. Not handling
1630 // this can cause overflow.
1631 if (RHSCst->isMaxValue(false))
1632 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001633 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001634 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001635 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1636 break;
1637 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1638 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1639 return ReplaceInstUsesWith(I, RHS);
1640 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1641 break;
1642 }
1643 break;
1644 case ICmpInst::ICMP_SLT:
1645 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001646 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001647 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1648 break;
1649 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1650 // If RHSCst is [us]MAXINT, it is always false. Not handling
1651 // this can cause overflow.
1652 if (RHSCst->isMaxValue(true))
1653 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00001654 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00001655 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00001656 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1657 break;
1658 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1659 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1660 return ReplaceInstUsesWith(I, RHS);
1661 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1662 break;
1663 }
1664 break;
1665 case ICmpInst::ICMP_UGT:
1666 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001667 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001668 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1669 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1670 return ReplaceInstUsesWith(I, LHS);
1671 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1672 break;
1673 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1674 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001675 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001676 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1677 break;
1678 }
1679 break;
1680 case ICmpInst::ICMP_SGT:
1681 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001682 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00001683 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1684 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1685 return ReplaceInstUsesWith(I, LHS);
1686 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1687 break;
1688 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1689 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00001690 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00001691 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1692 break;
1693 }
1694 break;
1695 }
1696 return 0;
1697}
1698
Chris Lattner5414cc52009-07-23 05:46:22 +00001699Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1700 FCmpInst *RHS) {
1701 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1702 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1703 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1704 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1705 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1706 // If either of the constants are nans, then the whole thing returns
1707 // true.
1708 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00001709 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001710
1711 // Otherwise, no need to compare the two constants, compare the
1712 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001713 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001714 LHS->getOperand(0), RHS->getOperand(0));
1715 }
1716
1717 // Handle vector zeros. This occurs because the canonical form of
1718 // "fcmp uno x,x" is "fcmp uno x, 0".
1719 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1720 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001721 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00001722 LHS->getOperand(0), RHS->getOperand(0));
1723
1724 return 0;
1725 }
1726
1727 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1728 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1729 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1730
1731 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1732 // Swap RHS operands to match LHS.
1733 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1734 std::swap(Op1LHS, Op1RHS);
1735 }
1736 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1737 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1738 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001739 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00001740 Op0LHS, Op0RHS);
1741 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00001742 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00001743 if (Op0CC == FCmpInst::FCMP_FALSE)
1744 return ReplaceInstUsesWith(I, RHS);
1745 if (Op1CC == FCmpInst::FCMP_FALSE)
1746 return ReplaceInstUsesWith(I, LHS);
1747 bool Op0Ordered;
1748 bool Op1Ordered;
1749 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1750 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1751 if (Op0Ordered == Op1Ordered) {
1752 // If both are ordered or unordered, return a new fcmp with
1753 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00001754 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00001755 if (Instruction *I = dyn_cast<Instruction>(RV))
1756 return I;
1757 // Otherwise, it's a constant boolean value...
1758 return ReplaceInstUsesWith(I, RV);
1759 }
1760 }
1761 return 0;
1762}
1763
Bill Wendlinga698a472008-12-01 08:23:25 +00001764/// FoldOrWithConstants - This helper function folds:
1765///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001766/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00001767///
1768/// into:
1769///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001770/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00001771///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00001772/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00001773Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00001774 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00001775 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1776 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001777
Bill Wendling286a0542008-12-02 06:24:20 +00001778 Value *V1 = 0;
1779 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001780 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00001781
Bill Wendling29976b92008-12-02 06:18:11 +00001782 APInt Xor = CI1->getValue() ^ CI2->getValue();
1783 if (!Xor.isAllOnesValue()) return 0;
1784
Bill Wendling286a0542008-12-02 06:24:20 +00001785 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00001786 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00001787 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00001788 }
1789
1790 return 0;
1791}
1792
Chris Lattner7e708292002-06-25 16:13:24 +00001793Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001794 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001796
Chris Lattnerd06094f2009-11-10 00:55:12 +00001797 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1798 return ReplaceInstUsesWith(I, V);
1799
1800
Chris Lattnerf8c36f52006-02-12 08:02:11 +00001801 // See if we can simplify any instructions used by the instruction whose sole
1802 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00001803 if (SimplifyDemandedInstructionBits(I))
1804 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00001805
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001807 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001808 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001809 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001810 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001811 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001812 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001813 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001814 ConstantInt::get(I.getContext(),
1815 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001816 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001817
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001818 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00001819 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Chris Lattner248a84b2010-01-05 07:04:23 +00001820 Op0->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00001821 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00001822 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001823 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00001824 ConstantInt::get(I.getContext(),
1825 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001826 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001827
1828 // Try to fold constant and into select arguments.
1829 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00001830 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00001831 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001832 if (isa<PHINode>(Op0))
1833 if (Instruction *NV = FoldOpIntoPhi(I))
1834 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001835 }
1836
Chris Lattner4f637d42006-01-06 17:59:59 +00001837 Value *A = 0, *B = 0;
1838 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00001839
Chris Lattner6423d4c2006-07-10 20:25:24 +00001840 // (A | B) | C and A | (B | C) -> bswap if possible.
1841 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00001842 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1843 match(Op1, m_Or(m_Value(), m_Value())) ||
1844 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1845 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00001846 if (Instruction *BSwap = MatchBSwap(I))
1847 return BSwap;
1848 }
1849
Chris Lattner6e4c6492005-05-09 04:58:36 +00001850 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001851 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001852 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001853 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001854 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00001855 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001856 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001857 }
1858
1859 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001860 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001861 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00001862 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00001863 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00001864 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001865 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00001866 }
1867
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001868 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00001869 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00001870 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1871 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001872 Value *V1 = 0, *V2 = 0, *V3 = 0;
1873 C1 = dyn_cast<ConstantInt>(C);
1874 C2 = dyn_cast<ConstantInt>(D);
1875 if (C1 && C2) { // (A & C1)|(B & C2)
1876 // If we have: ((V + N) & C1) | (V & C2)
1877 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1878 // replace with V+N.
1879 if (C1->getValue() == ~C2->getValue()) {
1880 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00001881 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001882 // Add commutes, try both ways.
1883 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1884 return ReplaceInstUsesWith(I, A);
1885 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1886 return ReplaceInstUsesWith(I, A);
1887 }
1888 // Or commutes, try both ways.
1889 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00001890 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00001891 // Add commutes, try both ways.
1892 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1893 return ReplaceInstUsesWith(I, B);
1894 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1895 return ReplaceInstUsesWith(I, B);
1896 }
1897 }
Chris Lattnere4412c12010-01-04 06:03:59 +00001898
1899 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1900 // iff (C1&C2) == 0 and (N&~C1) == 0
1901 if ((C1->getValue() & C2->getValue()) == 0) {
1902 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1903 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1904 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1905 return BinaryOperator::CreateAnd(A,
1906 ConstantInt::get(A->getContext(),
1907 C1->getValue()|C2->getValue()));
1908 // Or commutes, try both ways.
1909 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1910 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1911 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1912 return BinaryOperator::CreateAnd(B,
1913 ConstantInt::get(B->getContext(),
1914 C1->getValue()|C2->getValue()));
1915 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00001916 }
1917
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001918 // Check to see if we have any common things being and'ed. If so, find the
1919 // terms for V1 & (V2|V3).
Chris Lattner248a84b2010-01-05 07:04:23 +00001920 if (Op0->hasOneUse() || Op1->hasOneUse()) {
Chris Lattnere4412c12010-01-04 06:03:59 +00001921 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001922 if (A == B) // (A & C)|(A & D) == A & (C|D)
1923 V1 = A, V2 = C, V3 = D;
1924 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1925 V1 = A, V2 = B, V3 = C;
1926 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1927 V1 = C, V2 = A, V3 = D;
1928 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1929 V1 = C, V2 = A, V3 = B;
1930
1931 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00001932 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001933 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00001934 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00001935 }
Dan Gohmanb493b272008-10-28 22:38:57 +00001936
Dan Gohman1975d032008-10-30 20:40:10 +00001937 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00001938 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001939 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001940 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001941 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001942 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001943 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00001944 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00001945 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00001946
Bill Wendlingb01865c2008-11-30 13:52:49 +00001947 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001948 if ((match(C, m_Not(m_Specific(D))) &&
1949 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001950 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001951 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001952 if ((match(A, m_Not(m_Specific(D))) &&
1953 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001954 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001955 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001956 if ((match(C, m_Not(m_Specific(B))) &&
1957 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001958 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00001959 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00001960 if ((match(A, m_Not(m_Specific(B))) &&
1961 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00001962 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00001963 }
Chris Lattnere511b742006-11-14 07:46:50 +00001964
1965 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00001966 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1967 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1968 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00001969 SI0->getOperand(1) == SI1->getOperand(1) &&
1970 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00001971 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1972 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001973 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00001974 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00001975 }
1976 }
Chris Lattner67ca7682003-08-12 19:11:07 +00001977
Bill Wendlingb3833d12008-12-01 01:07:11 +00001978 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00001979 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1980 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00001981 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00001982 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00001983 }
1984 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00001985 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1986 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00001987 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00001988 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00001989 }
1990
Chris Lattnerd06094f2009-11-10 00:55:12 +00001991 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1992 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1993 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1994 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1995 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1996 I.getName()+".demorgan");
1997 return BinaryOperator::CreateNot(And);
1998 }
Chris Lattnera2881962003-02-18 19:28:33 +00001999
Chris Lattnera317e042010-01-05 06:59:49 +00002000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00002001 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2002 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
2003 return Res;
Chris Lattner6fc205f2006-05-05 06:39:07 +00002004
2005 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002006 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002007 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002008 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00002009 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
2010 !isa<ICmpInst>(Op1C->getOperand(0))) {
2011 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00002012 if (SrcTy == Op1C->getOperand(0)->getType() &&
2013 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002014 // Only do this if the casts both really cause code to be
2015 // generated.
2016 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002017 I.getType()) &&
Evan Chengb98a10e2008-03-24 00:21:34 +00002018 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002019 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002020 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
2021 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002022 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00002023 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002024 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002025 }
Chris Lattner99c65742007-10-24 05:38:08 +00002026 }
2027
2028
2029 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2030 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00002031 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2032 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
2033 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00002034 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002035
Chris Lattner7e708292002-06-25 16:13:24 +00002036 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002037}
2038
Chris Lattner7e708292002-06-25 16:13:24 +00002039Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002040 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002042
Evan Chengd34af782008-03-25 20:07:13 +00002043 if (isa<UndefValue>(Op1)) {
2044 if (isa<UndefValue>(Op0))
2045 // Handle undef ^ undef -> 0 special case. This is a common
2046 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00002047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002048 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00002049 }
Chris Lattnere87597f2004-10-16 18:11:37 +00002050
Chris Lattnerdea34da2010-01-05 07:01:16 +00002051 // xor X, X = 0
2052 if (Op0 == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002054
2055 // See if we can simplify any instructions used by the instruction whose sole
2056 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00002057 if (SimplifyDemandedInstructionBits(I))
2058 return &I;
2059 if (isa<VectorType>(I.getType()))
2060 if (isa<ConstantAggregateZero>(Op1))
2061 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00002062
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002063 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00002064 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002065 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2066 if (Op0I->getOpcode() == Instruction::And ||
2067 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00002068 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2069 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2070 if (dyn_castNotVal(Op0I->getOperand(1)))
2071 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00002072 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00002073 Value *NotY =
2074 Builder->CreateNot(Op0I->getOperand(1),
2075 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002076 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002077 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00002078 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002079 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00002080
2081 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2082 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2083 if (isFreeToInvert(Op0I->getOperand(0)) &&
2084 isFreeToInvert(Op0I->getOperand(1))) {
2085 Value *NotX =
2086 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2087 Value *NotY =
2088 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2089 if (Op0I->getOpcode() == Instruction::And)
2090 return BinaryOperator::CreateOr(NotX, NotY);
2091 return BinaryOperator::CreateAnd(NotX, NotY);
2092 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002093 }
2094 }
2095 }
2096
2097
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002098 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00002099 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00002100 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002101 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002102 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002103 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002104
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002105 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002106 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00002107 FCI->getOperand(0), FCI->getOperand(1));
2108 }
2109
Nick Lewycky517e1f52008-05-31 19:01:33 +00002110 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2111 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2112 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2113 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2114 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00002115 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2116 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00002117 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00002118 Op0C->getDestTy()))) {
2119 CI->setPredicate(CI->getInversePredicate());
2120 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00002121 }
2122 }
2123 }
2124 }
2125
Reid Spencere4d87aa2006-12-23 06:05:41 +00002126 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00002127 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002128 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2129 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002130 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2131 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00002132 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002133 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002134 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002135
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002136 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002137 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002138 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002139 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002140 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002141 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002142 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00002143 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00002144 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00002145 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00002146 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00002147 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00002148 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002149 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00002150
Chris Lattner7c4049c2004-01-12 19:35:11 +00002151 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002152 } else if (Op0I->getOpcode() == Instruction::Or) {
2153 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00002154 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002155 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002156 // Anything in both C1 and C2 is known to be zero, remove it from
2157 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002158 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2159 NewRHS = ConstantExpr::getAnd(NewRHS,
2160 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00002161 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00002162 I.setOperand(0, Op0I->getOperand(0));
2163 I.setOperand(1, NewRHS);
2164 return &I;
2165 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002166 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002167 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002168 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002169
2170 // Try to fold constant and into select arguments.
2171 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002172 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002173 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002174 if (isa<PHINode>(Op0))
2175 if (Instruction *NV = FoldOpIntoPhi(I))
2176 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002177 }
2178
Dan Gohman186a6362009-08-12 16:04:34 +00002179 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002180 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00002181 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002182
Dan Gohman186a6362009-08-12 16:04:34 +00002183 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002184 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00002185 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002186
Chris Lattner318bf792007-03-18 22:51:34 +00002187
2188 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2189 if (Op1I) {
2190 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002191 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002192 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002193 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002194 I.swapOperands();
2195 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00002196 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002197 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002198 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002199 }
Dan Gohman4ae51262009-08-12 16:23:25 +00002200 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002201 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002202 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002203 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002204 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002205 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00002206 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00002207 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00002208 std::swap(A, B);
2209 }
Chris Lattner318bf792007-03-18 22:51:34 +00002210 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00002211 I.swapOperands(); // Simplified below.
2212 std::swap(Op0, Op1);
2213 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002214 }
Chris Lattner318bf792007-03-18 22:51:34 +00002215 }
2216
2217 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2218 if (Op0I) {
2219 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00002220 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002221 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00002222 if (A == Op1) // (B|A)^B == (A|B)^B
2223 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00002224 if (B == Op1) // (A|B)^B == A & ~B
2225 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00002226 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002227 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002228 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00002229 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00002230 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002231 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00002232 if (A == Op1) // (A&B)^A -> (B&A)^A
2233 std::swap(A, B);
2234 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00002235 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00002236 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00002237 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002238 }
Chris Lattner318bf792007-03-18 22:51:34 +00002239 }
2240
2241 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2242 if (Op0I && Op1I && Op0I->isShift() &&
2243 Op0I->getOpcode() == Op1I->getOpcode() &&
2244 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2245 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00002246 Value *NewOp =
2247 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2248 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002249 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00002250 Op1I->getOperand(1));
2251 }
2252
2253 if (Op0I && Op1I) {
2254 Value *A, *B, *C, *D;
2255 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002256 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2257 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002258 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002259 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002260 }
2261 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00002262 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2263 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002264 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002265 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00002266 }
2267
2268 // (A & B)^(C & D)
2269 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002270 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2271 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00002272 // (X & Y)^(X & Y) -> (Y^Z) & X
2273 Value *X = 0, *Y = 0, *Z = 0;
2274 if (A == C)
2275 X = A, Y = B, Z = D;
2276 else if (A == D)
2277 X = A, Y = B, Z = C;
2278 else if (B == C)
2279 X = B, Y = A, Z = D;
2280 else if (B == D)
2281 X = B, Y = A, Z = C;
2282
2283 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00002284 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002285 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00002286 }
2287 }
2288 }
2289
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2291 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Chris Lattnera317e042010-01-05 06:59:49 +00002292 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2293 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2294 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2295 LHS->getOperand(1) == RHS->getOperand(0))
2296 LHS->swapOperands();
2297 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2298 LHS->getOperand(1) == RHS->getOperand(1)) {
2299 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2300 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2301 bool isSigned = LHS->isSigned() || RHS->isSigned();
2302 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
2303 if (Instruction *I = dyn_cast<Instruction>(RV))
2304 return I;
2305 // Otherwise, it's a constant boolean value.
2306 return ReplaceInstUsesWith(I, RV);
2307 }
2308 }
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002309
Chris Lattner6fc205f2006-05-05 06:39:07 +00002310 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00002311 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002312 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002313 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2314 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00002315 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002316 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002317 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002318 I.getType()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00002319 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
Chris Lattner80f43d32010-01-04 07:53:58 +00002320 I.getType())) {
Chris Lattner74381062009-08-30 07:44:24 +00002321 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2322 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002323 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00002324 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00002325 }
Chris Lattner99c65742007-10-24 05:38:08 +00002326 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00002327
Chris Lattner7e708292002-06-25 16:13:24 +00002328 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002329}
2330
Chris Lattner3f5b8772002-05-06 16:14:14 +00002331
Reid Spencer832254e2007-02-02 02:16:23 +00002332Instruction *InstCombiner::visitShl(BinaryOperator &I) {
2333 return commonShiftTransforms(I);
2334}
2335
2336Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
2337 return commonShiftTransforms(I);
2338}
2339
2340Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00002341 if (Instruction *R = commonShiftTransforms(I))
2342 return R;
2343
2344 Value *Op0 = I.getOperand(0);
2345
2346 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
2347 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2348 if (CSI->isAllOnesValue())
2349 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00002350
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002351 // See if we can turn a signed shr into an unsigned shr.
2352 if (MaskedValueIsZero(Op0,
2353 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
2354 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
2355
2356 // Arithmetic shifting an all-sign-bit value is a no-op.
2357 unsigned NumSignBits = ComputeNumSignBits(Op0);
2358 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
2359 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00002360
Chris Lattner348f6652007-12-06 01:59:46 +00002361 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00002362}
2363
2364Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
2365 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00002366 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002367
2368 // shl X, 0 == X and shr X, 0 == X
2369 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002370 if (Op1 == Constant::getNullValue(Op1->getType()) ||
2371 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00002372 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002373
Reid Spencere4d87aa2006-12-23 06:05:41 +00002374 if (isa<UndefValue>(Op0)) {
2375 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00002376 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002377 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002379 }
2380 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002381 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
2382 return ReplaceInstUsesWith(I, Op0);
2383 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002384 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002385 }
2386
Dan Gohman9004c8a2009-05-21 02:28:33 +00002387 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00002388 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00002389 return &I;
2390
Chris Lattner2eefe512004-04-09 19:05:30 +00002391 // Try to fold constant and into select arguments.
2392 if (isa<Constant>(Op0))
2393 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner80f43d32010-01-04 07:53:58 +00002394 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner2eefe512004-04-09 19:05:30 +00002395 return R;
2396
Reid Spencerb83eb642006-10-20 07:07:24 +00002397 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00002398 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
2399 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002400 return 0;
2401}
2402
Reid Spencerb83eb642006-10-20 07:07:24 +00002403Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00002404 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00002405 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002406
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002407 // See if we can simplify any instructions used by the instruction whose sole
2408 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002409 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00002410
Dan Gohmana119de82009-06-14 23:30:43 +00002411 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
2412 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00002413 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002414 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00002415 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002416 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002417 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00002418 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002419 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00002420 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002421 }
2422
2423 // ((X*C1) << C2) == (X * (C1 << C2))
2424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2425 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2426 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002427 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002428 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00002429
2430 // Try to fold constant and into select arguments.
2431 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner80f43d32010-01-04 07:53:58 +00002432 if (Instruction *R = FoldOpIntoSelect(I, SI))
Chris Lattner4d5542c2006-01-06 07:12:35 +00002433 return R;
2434 if (isa<PHINode>(Op0))
2435 if (Instruction *NV = FoldOpIntoPhi(I))
2436 return NV;
2437
Chris Lattner8999dd32007-12-22 09:07:47 +00002438 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
2439 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
2440 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
2441 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
2442 // place. Don't try to do this transformation in this case. Also, we
2443 // require that the input operand is a shift-by-constant so that we have
2444 // confidence that the shifts will get folded together. We could do this
2445 // xform in more cases, but it is unlikely to be profitable.
2446 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
2447 isa<ConstantInt>(TrOp->getOperand(1))) {
2448 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00002449 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00002450 // (shift2 (shift1 & 0x00FF), c2)
2451 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002452
2453 // For logical shifts, the truncation has the effect of making the high
2454 // part of the register be zeros. Emulate this by inserting an AND to
2455 // clear the top bits as needed. This 'and' will usually be zapped by
2456 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00002457 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
2458 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00002459 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
2460
2461 // The mask we constructed says what the trunc would do if occurring
2462 // between the shifts. We want to know the effect *after* the second
2463 // shift. We know that it is a logical shift by a constant, so adjust the
2464 // mask as appropriate.
2465 if (I.getOpcode() == Instruction::Shl)
2466 MaskV <<= Op1->getZExtValue();
2467 else {
2468 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
2469 MaskV = MaskV.lshr(Op1->getZExtValue());
2470 }
2471
Chris Lattner74381062009-08-30 07:44:24 +00002472 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00002473 Value *And = Builder->CreateAnd(NSh,
2474 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00002475 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00002476
2477 // Return the value truncated to the interesting size.
2478 return new TruncInst(And, I.getType());
2479 }
2480 }
2481
Chris Lattner4d5542c2006-01-06 07:12:35 +00002482 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00002483 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
2484 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
2485 Value *V1, *V2;
2486 ConstantInt *CC;
2487 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00002488 default: break;
2489 case Instruction::Add:
2490 case Instruction::And:
2491 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00002492 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002493 // These operators commute.
2494 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002495 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002496 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002497 m_Specific(Op1)))) {
2498 Value *YS = // (Y << C)
2499 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
2500 // (X + (Y << C))
2501 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
2502 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002503 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002504 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002505 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002506 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002507
Chris Lattner150f12a2005-09-18 06:30:59 +00002508 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00002509 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00002510 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00002511 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00002512 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002513 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00002514 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002515 Value *YS = // (Y << C)
2516 Builder->CreateShl(Op0BO->getOperand(0), Op1,
2517 Op0BO->getName());
2518 // X & (CC << C)
2519 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2520 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002521 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00002522 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00002523 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002524
Reid Spencera07cb7d2007-02-02 14:41:37 +00002525 // FALL THROUGH.
2526 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00002527 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002528 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002529 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00002530 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002531 Value *YS = // (Y << C)
2532 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2533 // (X + (Y << C))
2534 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
2535 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00002536 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00002537 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00002538 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00002539 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002540
Chris Lattner13d4ab42006-05-31 21:14:00 +00002541 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00002542 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
2543 match(Op0BO->getOperand(0),
2544 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00002545 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00002546 cast<BinaryOperator>(Op0BO->getOperand(0))
2547 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002548 Value *YS = // (Y << C)
2549 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
2550 // X & (CC << C)
2551 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
2552 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00002553
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002554 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00002555 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002556
Chris Lattner11021cb2005-09-18 05:12:10 +00002557 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00002558 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00002559 }
2560
2561
2562 // If the operand is an bitwise operator with a constant RHS, and the
2563 // shift is the only use, we can pull it out of the shift.
2564 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2565 bool isValid = true; // Valid only for And, Or, Xor
2566 bool highBitSet = false; // Transform if high bit of constant set?
2567
2568 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00002569 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00002570 case Instruction::Add:
2571 isValid = isLeftShift;
2572 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00002573 case Instruction::Or:
2574 case Instruction::Xor:
2575 highBitSet = false;
2576 break;
2577 case Instruction::And:
2578 highBitSet = true;
2579 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002580 }
2581
2582 // If this is a signed shift right, and the high bit is modified
2583 // by the logical operation, do not perform the transformation.
2584 // The highBitSet boolean indicates the value of the high bit of
2585 // the constant which would cause it to be modified for this
2586 // operation.
2587 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00002588 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00002589 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00002590
2591 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002592 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002593
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002594 Value *NewShift =
2595 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00002596 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00002597
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002598 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00002599 NewRHS);
2600 }
2601 }
2602 }
2603 }
2604
Chris Lattnerad0124c2006-01-06 07:52:12 +00002605 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00002606 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
2607 if (ShiftOp && !ShiftOp->isShift())
2608 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002609
Reid Spencerb83eb642006-10-20 07:07:24 +00002610 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002611 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00002612 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
2613 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002614 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
2615 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
2616 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00002617
Zhou Sheng4351c642007-04-02 08:20:41 +00002618 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00002619
2620 const IntegerType *Ty = cast<IntegerType>(I.getType());
2621
2622 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00002623 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002624 // If this is oversized composite shift, then unsigned shifts get 0, ashr
2625 // saturates.
2626 if (AmtSum >= TypeBits) {
2627 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00002628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002629 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
2630 }
2631
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002632 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00002633 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002634 }
2635
2636 if (ShiftOp->getOpcode() == Instruction::LShr &&
2637 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00002638 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00002639 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00002640
Chris Lattnerb87056f2007-02-05 00:57:54 +00002641 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00002642 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002643 }
2644
2645 if (ShiftOp->getOpcode() == Instruction::AShr &&
2646 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00002647 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00002648 if (AmtSum >= TypeBits)
2649 AmtSum = TypeBits-1;
2650
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002651 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002652
Zhou Shenge9e03f62007-03-28 15:02:20 +00002653 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00002654 return BinaryOperator::CreateAnd(Shift,
2655 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002656 }
2657
Chris Lattnerb87056f2007-02-05 00:57:54 +00002658 // Okay, if we get here, one shift must be left, and the other shift must be
2659 // right. See if the amounts are equal.
2660 if (ShiftAmt1 == ShiftAmt2) {
2661 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
2662 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00002663 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002664 return BinaryOperator::CreateAnd(X,
2665 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002666 }
2667 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
2668 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00002670 return BinaryOperator::CreateAnd(X,
2671 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002672 }
2673 // We can simplify ((X << C) >>s C) into a trunc + sext.
2674 // NOTE: we could do this for any C, but that would make 'unusual' integer
2675 // types. For now, just stick to ones well-supported by the code
2676 // generators.
2677 const Type *SExtType = 0;
2678 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00002679 case 1 :
2680 case 8 :
2681 case 16 :
2682 case 32 :
2683 case 64 :
2684 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00002685 SExtType = IntegerType::get(I.getContext(),
2686 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00002687 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002688 default: break;
2689 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002690 if (SExtType)
2691 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00002692 // Otherwise, we can't handle it yet.
2693 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002694 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00002695
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002696 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002697 if (I.getOpcode() == Instruction::Shl) {
2698 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2699 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002700 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00002701
Reid Spencer55702aa2007-03-25 21:11:44 +00002702 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002703 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002704 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002705 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002706
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002707 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002708 if (I.getOpcode() == Instruction::LShr) {
2709 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002710 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00002711
Reid Spencerd5e30f02007-03-26 17:18:58 +00002712 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002713 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002714 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00002715 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00002716
2717 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
2718 } else {
2719 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00002720 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00002721
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002722 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002723 if (I.getOpcode() == Instruction::Shl) {
2724 assert(ShiftOp->getOpcode() == Instruction::LShr ||
2725 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002726 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
2727 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002728
Reid Spencer55702aa2007-03-25 21:11:44 +00002729 APInt Mask(APInt::getHighBitsSet(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 Lattnerb87056f2007-02-05 00:57:54 +00002732 }
2733
Chris Lattnerb0b991a2007-02-05 05:57:49 +00002734 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00002735 if (I.getOpcode() == Instruction::LShr) {
2736 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002737 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002738
Reid Spencer68d27cf2007-03-26 23:45:51 +00002739 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00002740 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00002741 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00002742 }
2743
2744 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002745 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00002746 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002747 return 0;
2748}
2749
Chris Lattnera1be5662002-05-02 17:06:02 +00002750
Reid Spencer3da59db2006-11-27 01:05:10 +00002751
Chris Lattner46cd5a12009-01-09 05:44:56 +00002752/// FindElementAtOffset - Given a type and a constant offset, determine whether
2753/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00002754/// the specified offset. If so, fill them into NewIndices and return the
2755/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +00002756const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
2757 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002758 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00002759 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002760
2761 // Start with the index over the outer type. Note that the type size
2762 // might be zero (even if the offset isn't zero) if the indexed type
2763 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00002764 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00002765 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00002766 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00002767 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00002768 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002769
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002770 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00002771 if (Offset < 0) {
2772 --FirstIdx;
2773 Offset += TySize;
2774 assert(Offset >= 0);
2775 }
2776 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
2777 }
2778
Owen Andersoneed707b2009-07-24 23:12:02 +00002779 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002780
2781 // Index into the types. If we fail, set OrigBase to null.
2782 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002783 // Indexing into tail padding between struct/array elements.
2784 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00002785 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002786
Chris Lattner46cd5a12009-01-09 05:44:56 +00002787 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
2788 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002789 assert(Offset < (int64_t)SL->getSizeInBytes() &&
2790 "Offset must stay within the indexed type");
2791
Chris Lattner46cd5a12009-01-09 05:44:56 +00002792 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00002793 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
2794 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00002795
2796 Offset -= SL->getElementOffset(Elt);
2797 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00002798 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00002799 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002800 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00002801 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002802 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00002803 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00002804 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00002805 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00002806 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002807 }
2808 }
2809
Chris Lattner3914f722009-01-24 01:00:13 +00002810 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00002811}
2812
Chris Lattner8a2a3112001-12-14 16:52:21 +00002813
Chris Lattner473945d2002-05-06 18:06:38 +00002814
Chris Lattner7e708292002-06-25 16:13:24 +00002815Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002816 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
2817
2818 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
2819 return ReplaceInstUsesWith(GEP, V);
2820
Chris Lattner620ce142004-05-07 22:09:22 +00002821 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002822
Chris Lattnere87597f2004-10-16 18:11:37 +00002823 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00002824 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002825
Chris Lattner28977af2004-04-05 01:30:19 +00002826 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +00002827 if (TD) {
2828 bool MadeChange = false;
2829 unsigned PtrSize = TD->getPointerSizeInBits();
2830
2831 gep_type_iterator GTI = gep_type_begin(GEP);
2832 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
2833 I != E; ++I, ++GTI) {
2834 if (!isa<SequentialType>(*GTI)) continue;
2835
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002836 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +00002837 // to what we need. If narrower, sign-extend it to what we need. This
2838 // explicit cast can make subsequent optimizations more obvious.
2839 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +00002840 if (OpBits == PtrSize)
2841 continue;
2842
Chris Lattner2345d1d2009-08-30 20:01:10 +00002843 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +00002844 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +00002845 }
Chris Lattnerccf4b342009-08-30 04:49:01 +00002846 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00002847 }
Chris Lattner28977af2004-04-05 01:30:19 +00002848
Chris Lattner90ac28c2002-08-02 19:29:35 +00002849 // Combine Indices - If the source pointer to this getelementptr instruction
2850 // is a getelementptr instruction, combine the indices of the two
2851 // getelementptr instructions into a single instruction.
2852 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +00002853 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +00002854 // Note that if our source is a gep chain itself that we wait for that
2855 // chain to be resolved before we perform this transformation. This
2856 // avoids us creating a TON of code in some cases.
2857 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002858 if (GetElementPtrInst *SrcGEP =
2859 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
2860 if (SrcGEP->getNumOperands() == 2)
2861 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +00002862
Chris Lattner72588fc2007-02-15 22:48:32 +00002863 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00002864
2865 // Find out whether the last index in the source GEP is a sequential idx.
2866 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +00002867 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2868 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00002869 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002870
Chris Lattner90ac28c2002-08-02 19:29:35 +00002871 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00002872 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00002873 // Replace: gep (gep %P, long B), long A, ...
2874 // With: T = long A+B; gep %P, T, ...
2875 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002876 Value *Sum;
2877 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2878 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +00002879 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00002880 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +00002881 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +00002882 Sum = SO1;
2883 } else {
Chris Lattnerab984842009-08-30 05:30:55 +00002884 // If they aren't the same type, then the input hasn't been processed
2885 // by the loop above yet (which canonicalizes sequential index types to
2886 // intptr_t). Just avoid transforming this until the input has been
2887 // normalized.
2888 if (SO1->getType() != GO1->getType())
2889 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002890 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +00002891 }
Chris Lattner620ce142004-05-07 22:09:22 +00002892
Chris Lattnerab984842009-08-30 05:30:55 +00002893 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002894 if (Src->getNumOperands() == 2) {
2895 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +00002896 GEP.setOperand(1, Sum);
2897 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +00002898 }
Chris Lattnerab984842009-08-30 05:30:55 +00002899 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +00002900 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +00002901 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +00002902 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00002903 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002904 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002905 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +00002906 Indices.append(Src->op_begin()+1, Src->op_end());
2907 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00002908 }
2909
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002910 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +00002911 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +00002912 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
2913 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002914 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +00002915 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +00002916 }
2917
Chris Lattnerf9b91bb2009-08-30 05:08:50 +00002918 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +00002919 Value *StrippedPtr = PtrOp->stripPointerCasts();
2920 if (StrippedPtr != PtrOp) {
2921 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattner963f4ba2009-08-30 20:36:46 +00002922
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002923 bool HasZeroPointerIndex = false;
2924 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2925 HasZeroPointerIndex = C->isZero();
2926
Chris Lattner963f4ba2009-08-30 20:36:46 +00002927 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2928 // into : GEP [10 x i8]* X, i32 0, ...
2929 //
2930 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2931 // into : GEP i8* X, ...
2932 //
2933 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +00002934 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +00002935 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002936 if (const ArrayType *CATy =
2937 dyn_cast<ArrayType>(CPTy->getElementType())) {
2938 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +00002939 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002940 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +00002941 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
2942 GetElementPtrInst *Res =
2943 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
2944 Idx.end(), GEP.getName());
2945 Res->setIsInBounds(GEP.isInBounds());
2946 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +00002947 }
2948
Chris Lattner948cdeb2010-01-05 07:42:10 +00002949 if (const ArrayType *XATy =
2950 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002951 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +00002952 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002953 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00002954 // At this point, we know that the cast source type is a pointer
2955 // to an array of the same type as the destination pointer
2956 // array. Because the array type is never stepped over (there
2957 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +00002958 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +00002959 return &GEP;
2960 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +00002961 }
2962 }
Chris Lattnereed48272005-09-13 00:40:14 +00002963 } else if (GEP.getNumOperands() == 2) {
2964 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00002965 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
2966 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner948cdeb2010-01-05 07:42:10 +00002967 const Type *SrcElTy = StrippedPtrTy->getElementType();
Chris Lattnereed48272005-09-13 00:40:14 +00002968 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00002969 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +00002970 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
2971 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00002972 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00002973 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00002974 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +00002975 Value *NewGEP = GEP.isInBounds() ?
2976 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
2977 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00002978 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +00002979 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002980 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00002981
2982 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00002983 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00002984 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00002985 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00002986
Chris Lattner4de84762010-01-04 07:02:48 +00002987 if (TD && isa<ArrayType>(SrcElTy) &&
2988 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00002989 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +00002990 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00002991
2992 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
2993 // allow either a mul, shift, or constant here.
2994 Value *NewIdx = 0;
2995 ConstantInt *Scale = 0;
2996 if (ArrayEltSize == 1) {
2997 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00002998 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00002999 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003000 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00003001 Scale = CI;
3002 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
3003 if (Inst->getOpcode() == Instruction::Shl &&
3004 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003005 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
3006 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00003007 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00003008 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00003009 NewIdx = Inst->getOperand(0);
3010 } else if (Inst->getOpcode() == Instruction::Mul &&
3011 isa<ConstantInt>(Inst->getOperand(1))) {
3012 Scale = cast<ConstantInt>(Inst->getOperand(1));
3013 NewIdx = Inst->getOperand(0);
3014 }
3015 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003016
Chris Lattner7835cdd2005-09-13 18:36:04 +00003017 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003018 // out, perform the transformation. Note, we don't know whether Scale is
3019 // signed or not. We'll use unsigned version of division/modulo
3020 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00003021 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003022 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003023 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00003024 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00003025 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00003026 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
3027 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003028 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00003029 }
3030
3031 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00003032 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00003033 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00003034 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +00003035 Value *NewGEP = GEP.isInBounds() ?
3036 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
3037 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00003038 // The NewGEP must be pointer typed, so must the old one -> BitCast
3039 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00003040 }
3041 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00003042 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003043 }
Chris Lattner58407792009-01-09 04:53:57 +00003044
Chris Lattner46cd5a12009-01-09 05:44:56 +00003045 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00003046 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00003047 /// Y = gep X, <...constant indices...>
3048 /// into a gep of the original struct. This is important for SROA and alias
3049 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00003050 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00003051 if (TD &&
3052 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003053 // Determine how much the GEP moves the pointer. We are guaranteed to get
3054 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00003055 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00003056 int64_t Offset = OffsetV->getSExtValue();
3057
3058 // If this GEP instruction doesn't move the pointer, just replace the GEP
3059 // with a bitcast of the real input to the dest type.
3060 if (Offset == 0) {
3061 // If the bitcast is of an allocation, and the allocation will be
3062 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00003063 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00003064 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00003065 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
3066 if (Instruction *I = visitBitCast(*BCI)) {
3067 if (I != BCI) {
3068 I->takeName(BCI);
3069 BCI->getParent()->getInstList().insert(BCI, I);
3070 ReplaceInstUsesWith(*BCI, I);
3071 }
3072 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00003073 }
Chris Lattner58407792009-01-09 04:53:57 +00003074 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00003075 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00003076 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00003077
3078 // Otherwise, if the offset is non-zero, we need to find out if there is a
3079 // field at Offset in 'A's type. If so, we can pull the cast through the
3080 // GEP.
3081 SmallVector<Value*, 8> NewIndices;
3082 const Type *InTy =
3083 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00003084 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00003085 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +00003086 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
3087 NewIndices.end()) :
3088 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
3089 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003090
3091 if (NGEP->getType() == GEP.getType())
3092 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00003093 NGEP->takeName(&GEP);
3094 return new BitCastInst(NGEP, GEP.getType());
3095 }
Chris Lattner58407792009-01-09 04:53:57 +00003096 }
3097 }
3098
Chris Lattner8a2a3112001-12-14 16:52:21 +00003099 return 0;
3100}
3101
Victor Hernandez66284e02009-10-24 04:23:03 +00003102Instruction *InstCombiner::visitFree(Instruction &FI) {
3103 Value *Op = FI.getOperand(1);
3104
3105 // free undef -> unreachable.
3106 if (isa<UndefValue>(Op)) {
3107 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00003108 new StoreInst(ConstantInt::getTrue(FI.getContext()),
3109 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00003110 return EraseInstFromFunction(FI);
3111 }
3112
3113 // If we have 'free null' delete the instruction. This can happen in stl code
3114 // when lots of inlining happens.
3115 if (isa<ConstantPointerNull>(Op))
3116 return EraseInstFromFunction(FI);
3117
Victor Hernandez046e78c2009-10-26 23:43:48 +00003118 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +00003119 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +00003120 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
3121 if (Op->hasOneUse() && CI->hasOneUse()) {
3122 EraseInstFromFunction(FI);
3123 EraseInstFromFunction(*CI);
3124 return EraseInstFromFunction(*cast<Instruction>(Op));
3125 }
3126 } else {
3127 // Op is a call to malloc
3128 if (Op->hasOneUse()) {
3129 EraseInstFromFunction(FI);
3130 return EraseInstFromFunction(*cast<Instruction>(Op));
3131 }
3132 }
Dan Gohman7f712a12009-10-27 00:11:02 +00003133 }
Victor Hernandez66284e02009-10-24 04:23:03 +00003134
3135 return 0;
3136}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003137
Chris Lattner3284d1f2007-04-15 00:07:55 +00003138
Chris Lattner2f503e62005-01-31 05:36:43 +00003139
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003140Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3141 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00003142 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003143 BasicBlock *TrueDest;
3144 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00003145 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003146 !isa<Constant>(X)) {
3147 // Swap Destinations and condition...
3148 BI.setCondition(X);
3149 BI.setSuccessor(0, FalseDest);
3150 BI.setSuccessor(1, TrueDest);
3151 return &BI;
3152 }
3153
Reid Spencere4d87aa2006-12-23 06:05:41 +00003154 // Cannonicalize fcmp_one -> fcmp_oeq
3155 FCmpInst::Predicate FPred; Value *Y;
3156 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00003157 TrueDest, FalseDest)) &&
3158 BI.getCondition()->hasOneUse())
3159 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
3160 FPred == FCmpInst::FCMP_OGE) {
3161 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
3162 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
3163
3164 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003165 BI.setSuccessor(0, FalseDest);
3166 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003167 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003168 return &BI;
3169 }
3170
3171 // Cannonicalize icmp_ne -> icmp_eq
3172 ICmpInst::Predicate IPred;
3173 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00003174 TrueDest, FalseDest)) &&
3175 BI.getCondition()->hasOneUse())
3176 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
3177 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
3178 IPred == ICmpInst::ICMP_SGE) {
3179 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
3180 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
3181 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00003182 BI.setSuccessor(0, FalseDest);
3183 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003184 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00003185 return &BI;
3186 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003187
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003188 return 0;
3189}
Chris Lattner0864acf2002-11-04 16:18:53 +00003190
Chris Lattner46238a62004-07-03 00:26:11 +00003191Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3192 Value *Cond = SI.getCondition();
3193 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3194 if (I->getOpcode() == Instruction::Add)
3195 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3196 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3197 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00003198 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00003199 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00003200 AddRHS));
3201 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00003202 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00003203 return &SI;
3204 }
3205 }
3206 return 0;
3207}
3208
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003209Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003210 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003211
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003212 if (!EV.hasIndices())
3213 return ReplaceInstUsesWith(EV, Agg);
3214
3215 if (Constant *C = dyn_cast<Constant>(Agg)) {
3216 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003217 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003218
3219 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00003220 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003221
3222 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
3223 // Extract the element indexed by the first index out of the constant
3224 Value *V = C->getOperand(*EV.idx_begin());
3225 if (EV.getNumIndices() > 1)
3226 // Extract the remaining indices out of the constant indexed by the
3227 // first index
3228 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
3229 else
3230 return ReplaceInstUsesWith(EV, V);
3231 }
3232 return 0; // Can't handle other constants
3233 }
3234 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3235 // We're extracting from an insertvalue instruction, compare the indices
3236 const unsigned *exti, *exte, *insi, *inse;
3237 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3238 exte = EV.idx_end(), inse = IV->idx_end();
3239 exti != exte && insi != inse;
3240 ++exti, ++insi) {
3241 if (*insi != *exti)
3242 // The insert and extract both reference distinctly different elements.
3243 // This means the extract is not influenced by the insert, and we can
3244 // replace the aggregate operand of the extract with the aggregate
3245 // operand of the insert. i.e., replace
3246 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3247 // %E = extractvalue { i32, { i32 } } %I, 0
3248 // with
3249 // %E = extractvalue { i32, { i32 } } %A, 0
3250 return ExtractValueInst::Create(IV->getAggregateOperand(),
3251 EV.idx_begin(), EV.idx_end());
3252 }
3253 if (exti == exte && insi == inse)
3254 // Both iterators are at the end: Index lists are identical. Replace
3255 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3256 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3257 // with "i32 42"
3258 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
3259 if (exti == exte) {
3260 // The extract list is a prefix of the insert list. i.e. replace
3261 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3262 // %E = extractvalue { i32, { i32 } } %I, 1
3263 // with
3264 // %X = extractvalue { i32, { i32 } } %A, 1
3265 // %E = insertvalue { i32 } %X, i32 42, 0
3266 // by switching the order of the insert and extract (though the
3267 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00003268 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
3269 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003270 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3271 insi, inse);
3272 }
3273 if (insi == inse)
3274 // The insert list is a prefix of the extract list
3275 // We can simply remove the common indices from the extract and make it
3276 // operate on the inserted value instead of the insertvalue result.
3277 // i.e., replace
3278 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3279 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3280 // with
3281 // %E extractvalue { i32 } { i32 42 }, 0
3282 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
3283 exti, exte);
3284 }
Chris Lattner7e606e22009-11-09 07:07:56 +00003285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
3286 // We're extracting from an intrinsic, see if we're the only user, which
3287 // allows us to simplify multiple result intrinsics to simpler things that
3288 // just get one value..
3289 if (II->hasOneUse()) {
3290 // Check if we're grabbing the overflow bit or the result of a 'with
3291 // overflow' intrinsic. If it's the latter we can remove the intrinsic
3292 // and replace it with a traditional binary instruction.
3293 switch (II->getIntrinsicID()) {
3294 case Intrinsic::uadd_with_overflow:
3295 case Intrinsic::sadd_with_overflow:
3296 if (*EV.idx_begin() == 0) { // Normal result.
3297 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3298 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3299 EraseInstFromFunction(*II);
3300 return BinaryOperator::CreateAdd(LHS, RHS);
3301 }
3302 break;
3303 case Intrinsic::usub_with_overflow:
3304 case Intrinsic::ssub_with_overflow:
3305 if (*EV.idx_begin() == 0) { // Normal result.
3306 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3307 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3308 EraseInstFromFunction(*II);
3309 return BinaryOperator::CreateSub(LHS, RHS);
3310 }
3311 break;
3312 case Intrinsic::umul_with_overflow:
3313 case Intrinsic::smul_with_overflow:
3314 if (*EV.idx_begin() == 0) { // Normal result.
3315 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
3316 II->replaceAllUsesWith(UndefValue::get(II->getType()));
3317 EraseInstFromFunction(*II);
3318 return BinaryOperator::CreateMul(LHS, RHS);
3319 }
3320 break;
3321 default:
3322 break;
3323 }
3324 }
3325 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00003326 // Can't simplify extracts from other values. Note that nested extracts are
3327 // already simplified implicitely by the above (extract ( extract (insert) )
3328 // will be translated into extract ( insert ( extract ) ) first and then just
3329 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00003330 return 0;
3331}
3332
Chris Lattnera844fc4c2006-04-10 22:45:52 +00003333
Robert Bocchino1d7456d2006-01-13 22:48:06 +00003334
Chris Lattnerea1c4542004-12-08 23:43:58 +00003335
3336/// TryToSinkInstruction - Try to move the specified instruction from its
3337/// current block into the beginning of DestBlock, which can only happen if it's
3338/// safe to move the instruction past all of the instructions between it and the
3339/// end of its block.
3340static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3341 assert(I->hasOneUse() && "Invariants didn't hold!");
3342
Chris Lattner108e9022005-10-27 17:13:11 +00003343 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00003344 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00003345 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00003346
Chris Lattnerea1c4542004-12-08 23:43:58 +00003347 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00003348 if (isa<AllocaInst>(I) && I->getParent() ==
3349 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00003350 return false;
3351
Chris Lattner96a52a62004-12-09 07:14:34 +00003352 // We can only sink load instructions if there is nothing between the load and
3353 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00003354 if (I->mayReadFromMemory()) {
3355 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00003356 Scan != E; ++Scan)
3357 if (Scan->mayWriteToMemory())
3358 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00003359 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00003360
Dan Gohman02dea8b2008-05-23 21:05:58 +00003361 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00003362
Chris Lattner4bc5f802005-08-08 19:11:57 +00003363 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00003364 ++NumSunkInst;
3365 return true;
3366}
3367
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003368
3369/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
3370/// all reachable code to the worklist.
3371///
3372/// This has a couple of tricks to make the code faster and more powerful. In
3373/// particular, we constant fold and DCE instructions as we go, to avoid adding
3374/// them to the worklist (this significantly speeds up instcombine on code where
3375/// many instructions are dead or constant). Additionally, if we find a branch
3376/// whose condition is a known constant, we only visit the reachable successors.
3377///
Chris Lattner2ee743b2009-10-15 04:59:28 +00003378static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00003379 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00003380 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003381 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00003382 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00003383 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00003384 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +00003385
3386 std::vector<Instruction*> InstrsForInstCombineWorklist;
3387 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003388
Chris Lattner2ee743b2009-10-15 04:59:28 +00003389 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
3390
Chris Lattner2c7718a2007-03-23 19:17:18 +00003391 while (!Worklist.empty()) {
3392 BB = Worklist.back();
3393 Worklist.pop_back();
3394
3395 // We have now visited this block! If we've already been here, ignore it.
3396 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00003397
Chris Lattner2c7718a2007-03-23 19:17:18 +00003398 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3399 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003400
Chris Lattner2c7718a2007-03-23 19:17:18 +00003401 // DCE instruction if trivially dead.
3402 if (isInstructionTriviallyDead(Inst)) {
3403 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00003404 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00003405 Inst->eraseFromParent();
3406 continue;
3407 }
3408
3409 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003410 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00003411 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003412 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
3413 << *Inst << '\n');
3414 Inst->replaceAllUsesWith(C);
3415 ++NumConstProp;
3416 Inst->eraseFromParent();
3417 continue;
3418 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00003419
3420
3421
3422 if (TD) {
3423 // See if we can constant fold its operands.
3424 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
3425 i != e; ++i) {
3426 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
3427 if (CE == 0) continue;
3428
3429 // If we already folded this constant, don't try again.
3430 if (!FoldedConstants.insert(CE))
3431 continue;
3432
Chris Lattner7b550cc2009-11-06 04:27:31 +00003433 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00003434 if (NewC && NewC != CE) {
3435 *i = NewC;
3436 MadeIRChange = true;
3437 }
3438 }
3439 }
3440
Devang Patel7fe1dec2008-11-19 18:56:50 +00003441
Chris Lattner67f7d542009-10-12 03:58:40 +00003442 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003443 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00003444
3445 // Recursively visit successors. If this is a branch or switch on a
3446 // constant, only visit the reachable successor.
3447 TerminatorInst *TI = BB->getTerminator();
3448 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3449 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3450 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00003451 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00003452 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00003453 continue;
3454 }
3455 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3456 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3457 // See if this is an explicit destination.
3458 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
3459 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00003460 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00003461 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00003462 continue;
3463 }
3464
3465 // Otherwise it is the default destination.
3466 Worklist.push_back(SI->getSuccessor(0));
3467 continue;
3468 }
3469 }
3470
3471 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3472 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003473 }
Chris Lattner67f7d542009-10-12 03:58:40 +00003474
3475 // Once we've found all of the instructions to add to instcombine's worklist,
3476 // add them in reverse order. This way instcombine will visit from the top
3477 // of the function down. This jives well with the way that it adds all uses
3478 // of instructions to the worklist after doing a transformation, thus avoiding
3479 // some N^2 behavior in pathological cases.
3480 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
3481 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00003482
3483 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003484}
3485
Chris Lattnerec9c3582007-03-03 02:04:50 +00003486bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003487 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00003488
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00003489 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3490 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00003491
Chris Lattnerb3d59702005-07-07 20:40:38 +00003492 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00003493 // Do a depth-first traversal of the function, populate the worklist with
3494 // the reachable instructions. Ignore blocks that are not reachable. Keep
3495 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00003496 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00003497 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00003498
Chris Lattnerb3d59702005-07-07 20:40:38 +00003499 // Do a quick scan over the function. If we find any blocks that are
3500 // unreachable, remove any instructions inside of them. This prevents
3501 // the instcombine code from having to deal with some bad special cases.
3502 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
3503 if (!Visited.count(BB)) {
3504 Instruction *Term = BB->getTerminator();
3505 while (Term != BB->begin()) { // Remove instrs bottom-up
3506 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00003507
Chris Lattnerbdff5482009-08-23 04:37:46 +00003508 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00003509 // A debug intrinsic shouldn't force another iteration if we weren't
3510 // going to do one without it.
3511 if (!isa<DbgInfoIntrinsic>(I)) {
3512 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003513 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00003514 }
Devang Patel228ebd02009-10-13 22:56:32 +00003515
Devang Patel228ebd02009-10-13 22:56:32 +00003516 // If I is not void type then replaceAllUsesWith undef.
3517 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00003518 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00003519 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00003520 I->eraseFromParent();
3521 }
3522 }
3523 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00003524
Chris Lattner873ff012009-08-30 05:55:36 +00003525 while (!Worklist.isEmpty()) {
3526 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00003527 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00003528
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003529 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003530 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00003531 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00003532 EraseInstFromFunction(*I);
3533 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003534 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003535 continue;
3536 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003537
Chris Lattner8c8c66a2006-05-11 17:11:52 +00003538 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003539 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00003540 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003541 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00003542
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003543 // Add operands to the worklist.
3544 ReplaceInstUsesWith(*I, C);
3545 ++NumConstProp;
3546 EraseInstFromFunction(*I);
3547 MadeIRChange = true;
3548 continue;
3549 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003550
Chris Lattnerea1c4542004-12-08 23:43:58 +00003551 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00003552 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00003553 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00003554 Instruction *UserInst = cast<Instruction>(I->use_back());
3555 BasicBlock *UserParent;
3556
3557 // Get the block the use occurs in.
3558 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3559 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
3560 else
3561 UserParent = UserInst->getParent();
3562
Chris Lattnerea1c4542004-12-08 23:43:58 +00003563 if (UserParent != BB) {
3564 bool UserIsSuccessor = false;
3565 // See if the user is one of our successors.
3566 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
3567 if (*SI == UserParent) {
3568 UserIsSuccessor = true;
3569 break;
3570 }
3571
3572 // If the user is one of our immediate successors, and if that successor
3573 // only has us as a predecessors (we'd have to split the critical edge
3574 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00003575 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00003576 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003577 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00003578 }
3579 }
3580
Chris Lattner74381062009-08-30 07:44:24 +00003581 // Now that we have an instruction, try combining it to simplify it.
3582 Builder->SetInsertPoint(I->getParent(), I);
3583
Reid Spencera9b81012007-03-26 17:44:01 +00003584#ifndef NDEBUG
3585 std::string OrigI;
3586#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00003587 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00003588 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
3589
Chris Lattner90ac28c2002-08-02 19:29:35 +00003590 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003591 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003592 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003593 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00003594 DEBUG(errs() << "IC: Old = " << *I << '\n'
3595 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00003596
Chris Lattnerf523d062004-06-09 05:08:07 +00003597 // Everything uses the new instruction now.
3598 I->replaceAllUsesWith(Result);
3599
3600 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00003601 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003602 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003603
Chris Lattner6934a042007-02-11 01:23:03 +00003604 // Move the name to the new instruction first.
3605 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003606
3607 // Insert the new instruction into the basic block...
3608 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00003609 BasicBlock::iterator InsertPos = I;
3610
3611 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
3612 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
3613 ++InsertPos;
3614
3615 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003616
Chris Lattner7a1e9242009-08-30 06:13:40 +00003617 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00003618 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00003619#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00003620 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
3621 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00003622#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00003623
Chris Lattner90ac28c2002-08-02 19:29:35 +00003624 // If the instruction was modified, it's possible that it is now dead.
3625 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003626 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00003627 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003628 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00003629 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003630 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003631 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003632 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003633 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003634 }
3635 }
3636
Chris Lattner873ff012009-08-30 05:55:36 +00003637 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00003638 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003639}
3640
Chris Lattnerec9c3582007-03-03 02:04:50 +00003641
3642bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00003643 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003644 TD = getAnalysisIfAvailable<TargetData>();
3645
Chris Lattner74381062009-08-30 07:44:24 +00003646
3647 /// Builder - This is an IRBuilder that automatically inserts new
3648 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00003649 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00003650 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00003651 InstCombineIRInserter(Worklist));
3652 Builder = &TheBuilder;
3653
Chris Lattnerec9c3582007-03-03 02:04:50 +00003654 bool EverMadeChange = false;
3655
3656 // Iterate while there is work to do.
3657 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00003658 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00003659 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00003660
3661 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00003662 return EverMadeChange;
3663}
3664
Brian Gaeke96d4bf72004-07-27 17:43:21 +00003665FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003666 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003667}