blob: ce9dab9a51fae57602856884315265035fca4f78 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-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 Lattnerdeaa0dd2003-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 Spencer266e42b2006-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 Lattnerede3fe02003-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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer755d0e72007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000186
Reid Spencer266e42b2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner69193f92004-04-05 01:30:19 +0000229 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner623826c2004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
241
Chris Lattner7e794272004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248
Chris Lattnere79d2492006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000251
Reid Spencer13bc5d72006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000274 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000275
Chris Lattner2590e512006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner51ea1272004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattner3ac7c262003-08-13 20:16:26 +0000305 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencer266e42b2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Reid Spencer959a21d2007-03-23 21:24:59 +0000322 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
323 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000324 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
325 APInt& KnownZero, APInt& KnownOne,
326 unsigned Depth = 0);
327
Chris Lattner2deeaea2006-10-05 06:55:50 +0000328 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
329 uint64_t &UndefElts, unsigned Depth = 0);
330
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000331 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
332 // PHI node as operand #0, see if we can fold the instruction into the PHI
333 // (which is only possible if all operands to the PHI are constants).
334 Instruction *FoldOpIntoPhi(Instruction &I);
335
Chris Lattner7515cab2004-11-14 19:13:23 +0000336 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
337 // operator and they all are only used by the PHI, PHI together their
338 // inputs, and do the operation once, to the result of the PHI.
339 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000340 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
341
342
Zhou Sheng75b871f2007-01-11 12:24:14 +0000343 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
344 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000347 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000348 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000349 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000350 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000351 Instruction *MatchBSwap(BinaryOperator &I);
352
Reid Spencer74a528b2006-12-13 18:21:21 +0000353 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000354 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000355
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000356 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000357}
358
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000360// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361static unsigned getComplexity(Value *V) {
362 if (isa<Instruction>(V)) {
363 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000364 return 3;
365 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 if (isa<Argument>(V)) return 3;
368 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369}
Chris Lattner260ab202002-04-18 17:39:14 +0000370
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371// isOnlyUse - Return true if this instruction will be deleted if we stop using
372// it.
373static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000374 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375}
376
Chris Lattnere79e8542004-02-23 06:38:22 +0000377// getPromotedType - Return the specified type promoted as it would be to pass
378// though a va_arg area...
379static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000380 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
381 if (ITy->getBitWidth() < 32)
382 return Type::Int32Ty;
383 } else if (Ty == Type::FloatTy)
384 return Type::DoubleTy;
385 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000386}
387
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388/// getBitCastOperand - If the specified operand is a CastInst or a constant
389/// expression bitcast, return the operand value, otherwise return null.
390static Value *getBitCastOperand(Value *V) {
391 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000392 return I->getOperand(0);
393 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return CE->getOperand(0);
396 return 0;
397}
398
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399/// This function is a wrapper around CastInst::isEliminableCastPair. It
400/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401static Instruction::CastOps
402isEliminableCastPair(
403 const CastInst *CI, ///< The first cast instruction
404 unsigned opcode, ///< The opcode of the second cast instruction
405 const Type *DstTy, ///< The target type for the second cast instruction
406 TargetData *TD ///< The target data for pointer size
407) {
408
409 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
410 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000412 // Get the opcodes of the two Cast instructions
413 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
414 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000415
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000416 return Instruction::CastOps(
417 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
418 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000419}
420
421/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
422/// in any code being generated. It does not require codegen if V is simple
423/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000424static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
425 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000426 if (V->getType() == Ty || isa<Constant>(V)) return false;
427
Chris Lattner99155be2006-05-25 23:24:33 +0000428 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000430 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 return false;
432 return true;
433}
434
435/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
436/// InsertBefore instruction. This is specialized a bit to avoid inserting
437/// casts that are known to not do anything...
438///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000439Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
440 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000441 Instruction *InsertBefore) {
442 if (V->getType() == DestTy) return V;
443 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447}
448
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000449// SimplifyCommutative - This performs a few simplifications for commutative
450// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000451//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// 1. Order operands such that they are listed from right (least complex) to
453// left (most complex). This puts constants before unary operators before
454// binary operators.
455//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000456// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
457// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 bool Changed = false;
461 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
462 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000463
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000464 if (!I.isAssociative()) return Changed;
465 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
467 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
468 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000469 Constant *Folded = ConstantExpr::get(I.getOpcode(),
470 cast<Constant>(I.getOperand(1)),
471 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000472 I.setOperand(0, Op->getOperand(0));
473 I.setOperand(1, Folded);
474 return true;
475 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
476 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
477 isOnlyUse(Op) && isOnlyUse(Op1)) {
478 Constant *C1 = cast<Constant>(Op->getOperand(1));
479 Constant *C2 = cast<Constant>(Op1->getOperand(1));
480
481 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000482 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
484 Op1->getOperand(0),
485 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000486 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 I.setOperand(0, New);
488 I.setOperand(1, Folded);
489 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000490 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000491 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000493}
Chris Lattnerca081252001-12-14 16:52:21 +0000494
Reid Spencer266e42b2006-12-23 06:05:41 +0000495/// SimplifyCompare - For a CmpInst this function just orders the operands
496/// so that theyare listed from right (least complex) to left (most complex).
497/// This puts constants before unary operators before binary operators.
498bool InstCombiner::SimplifyCompare(CmpInst &I) {
499 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
500 return false;
501 I.swapOperands();
502 // Compare instructions are not associative so there's nothing else we can do.
503 return true;
504}
505
Chris Lattnerbb74e222003-03-10 23:06:50 +0000506// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
507// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000508//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509static inline Value *dyn_castNegVal(Value *V) {
510 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000511 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512
Chris Lattner9ad0d552004-12-14 20:08:06 +0000513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
515 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000516 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517}
518
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519static inline Value *dyn_castNotVal(Value *V) {
520 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000521 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522
523 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000524 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000525 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000526 return 0;
527}
528
Chris Lattner7fb29e12003-03-11 00:12:48 +0000529// dyn_castFoldableMul - If this value is a multiply that can be folded into
530// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000531// non-constant operand of the multiply, and set CST to point to the multiplier.
532// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000533//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000535 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000538 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 // The multiplier is really 1 << CST.
Reid Spencer624766f2007-03-25 19:55:33 +0000543 Constant *One = ConstantInt::get(V->getType(), 1);
544 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 return I->getOperand(0);
546 }
547 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000548 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000549}
Chris Lattner31ae8632002-08-14 17:51:49 +0000550
Chris Lattner0798af32005-01-13 20:14:25 +0000551/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
552/// expression, return it.
553static User *dyn_castGetElementPtr(Value *V) {
554 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556 if (CE->getOpcode() == Instruction::GetElementPtr)
557 return cast<User>(V);
558 return false;
559}
560
Reid Spencer80263aa2007-03-25 05:33:51 +0000561/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000562static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000563 APInt Val(C->getValue());
564 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000565}
Reid Spencer80263aa2007-03-25 05:33:51 +0000566/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000567static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000568 APInt Val(C->getValue());
569 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000570}
571/// Add - Add two ConstantInts together
572static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
573 return ConstantInt::get(C1->getValue() + C2->getValue());
574}
575/// And - Bitwise AND two ConstantInts together
576static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
577 return ConstantInt::get(C1->getValue() & C2->getValue());
578}
579/// Subtract - Subtract one ConstantInt from another
580static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
581 return ConstantInt::get(C1->getValue() - C2->getValue());
582}
583/// Multiply - Multiply two ConstantInts together
584static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
585 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000586}
587
Chris Lattner4534dd592006-02-09 07:38:58 +0000588/// ComputeMaskedBits - Determine which of the bits specified in Mask are
589/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000590/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
591/// processing.
592/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
593/// we cannot optimize based on the assumption that it is zero without changing
594/// it to be an explicit zero. If we don't change it to zero, other code could
595/// optimized based on the contradictory assumption that it is non-zero.
596/// Because instcombine aggressively folds operations with undef args anyway,
597/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000598static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000599 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000600 assert(V && "No Value?");
601 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000602 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaf4341d2007-03-13 02:23:10 +0000603 const IntegerType *VTy = cast<IntegerType>(V->getType());
604 assert(VTy->getBitWidth() == BitWidth &&
605 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000606 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000607 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000608 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
609 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000610 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000611 KnownZero = ~KnownOne & Mask;
612 return;
613 }
614
Reid Spenceraa696402007-03-08 01:46:38 +0000615 if (Depth == 6 || Mask == 0)
616 return; // Limit search depth.
617
618 Instruction *I = dyn_cast<Instruction>(V);
619 if (!I) return;
620
Zhou Shengaf4341d2007-03-13 02:23:10 +0000621 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000622 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000623
624 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000625 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000626 // If either the LHS or the RHS are Zero, the result is zero.
627 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000628 APInt Mask2(Mask & ~KnownZero);
629 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000630 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
631 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
632
633 // Output known-1 bits are only known if set in both the LHS & RHS.
634 KnownOne &= KnownOne2;
635 // Output known-0 are known to be clear if zero in either the LHS | RHS.
636 KnownZero |= KnownZero2;
637 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000638 }
639 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000640 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000641 APInt Mask2(Mask & ~KnownOne);
642 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000643 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
644 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
645
646 // Output known-0 bits are only known if clear in both the LHS & RHS.
647 KnownZero &= KnownZero2;
648 // Output known-1 are known to be set if set in either the LHS | RHS.
649 KnownOne |= KnownOne2;
650 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000651 }
Reid Spenceraa696402007-03-08 01:46:38 +0000652 case Instruction::Xor: {
653 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
654 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
656 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
657
658 // Output known-0 bits are known if clear or set in both the LHS & RHS.
659 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
660 // Output known-1 are known to be set if set in only one of the LHS, RHS.
661 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
662 KnownZero = KnownZeroOut;
663 return;
664 }
665 case Instruction::Select:
666 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
667 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
668 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
669 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
670
671 // Only known if known in both the LHS and RHS.
672 KnownOne &= KnownOne2;
673 KnownZero &= KnownZero2;
674 return;
675 case Instruction::FPTrunc:
676 case Instruction::FPExt:
677 case Instruction::FPToUI:
678 case Instruction::FPToSI:
679 case Instruction::SIToFP:
680 case Instruction::PtrToInt:
681 case Instruction::UIToFP:
682 case Instruction::IntToPtr:
683 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000684 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000685 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000686 uint32_t SrcBitWidth =
687 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Reid Spencerd8aad612007-03-25 02:03:12 +0000688 ComputeMaskedBits(I->getOperand(0), APInt(Mask).zext(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000689 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
690 KnownZero.trunc(BitWidth);
691 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000692 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000693 }
Reid Spenceraa696402007-03-08 01:46:38 +0000694 case Instruction::BitCast: {
695 const Type *SrcTy = I->getOperand(0)->getType();
696 if (SrcTy->isInteger()) {
697 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
698 return;
699 }
700 break;
701 }
702 case Instruction::ZExt: {
703 // Compute the bits in the result that are not present in the input.
704 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000705 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000706 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
707
Reid Spencerd8aad612007-03-25 02:03:12 +0000708 ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000709 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000710 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
711 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000712 KnownZero.zext(BitWidth);
713 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000714 KnownZero |= NewBits;
715 return;
716 }
717 case Instruction::SExt: {
718 // Compute the bits in the result that are not present in the input.
719 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000720 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000721 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
722
Reid Spencerd8aad612007-03-25 02:03:12 +0000723 ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth),
Zhou Shengaf4341d2007-03-13 02:23:10 +0000724 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000725 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000726 KnownZero.zext(BitWidth);
727 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000728
729 // If the sign bit of the input is known set or clear, then we know the
730 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000731 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Shengaf4341d2007-03-13 02:23:10 +0000732 InSignBit.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000733 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
734 KnownZero |= NewBits;
735 KnownOne &= ~NewBits;
736 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
737 KnownOne |= NewBits;
738 KnownZero &= ~NewBits;
739 } else { // Input sign bit unknown
740 KnownZero &= ~NewBits;
741 KnownOne &= ~NewBits;
742 }
743 return;
744 }
745 case Instruction::Shl:
746 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
747 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
748 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencerd8aad612007-03-25 02:03:12 +0000749 APInt Mask2(Mask.lshr(ShiftAmt));
750 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000752 KnownZero <<= ShiftAmt;
753 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000754 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000755 return;
756 }
757 break;
758 case Instruction::LShr:
759 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
760 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
761 // Compute the new bits that are at the top now.
762 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000763 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000764
765 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000766 APInt Mask2(Mask.shl(ShiftAmt));
767 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000768 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
769 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
770 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
771 KnownZero |= HighBits; // high bits known zero.
772 return;
773 }
774 break;
775 case Instruction::AShr:
776 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
777 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
778 // Compute the new bits that are at the top now.
779 uint64_t ShiftAmt = SA->getZExtValue();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000780 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000781
782 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000783 APInt Mask2(Mask.shl(ShiftAmt));
784 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000785 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
786 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
788
789 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000790 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000791
792 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
793 KnownZero |= HighBits;
794 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
795 KnownOne |= HighBits;
796 }
797 return;
798 }
799 break;
800 }
801}
802
Reid Spencerbb5741f2007-03-08 01:52:58 +0000803/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
804/// this predicate to simplify operations downstream. Mask is known to be zero
805/// for bits that V cannot have.
806static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000807 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000808 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
809 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
810 return (KnownZero & Mask) == Mask;
811}
812
Chris Lattner0157e7f2006-02-11 09:31:47 +0000813/// ShrinkDemandedConstant - Check to see if the specified operand of the
814/// specified instruction is a constant integer. If so, check to see if there
815/// are any bits set in the constant that are not demanded. If so, shrink the
816/// constant and return true.
817static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000818 APInt Demanded) {
819 assert(I && "No instruction?");
820 assert(OpNo < I->getNumOperands() && "Operand index too large");
821
822 // If the operand is not a constant integer, nothing to do.
823 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
824 if (!OpC) return false;
825
826 // If there are no bits set that aren't demanded, nothing to do.
827 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
828 if ((~Demanded & OpC->getValue()) == 0)
829 return false;
830
831 // This instruction is producing bits that are not demanded. Shrink the RHS.
832 Demanded &= OpC->getValue();
833 I->setOperand(OpNo, ConstantInt::get(Demanded));
834 return true;
835}
836
Chris Lattneree0f2802006-02-12 02:07:56 +0000837// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
838// set of known zero and one bits, compute the maximum and minimum values that
839// could have the specified known zero and known one bits, returning them in
840// min/max.
841static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000842 const APInt& KnownZero,
843 const APInt& KnownOne,
844 APInt& Min, APInt& Max) {
845 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
846 assert(KnownZero.getBitWidth() == BitWidth &&
847 KnownOne.getBitWidth() == BitWidth &&
848 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
849 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000850 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000851
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000852 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +0000853
854 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
855 // bit if it is unknown.
856 Min = KnownOne;
857 Max = KnownOne|UnknownBits;
858
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000859 if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +0000860 Min |= SignBit;
861 Max &= ~SignBit;
862 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000863}
864
865// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
866// a set of known zero and one bits, compute the maximum and minimum values that
867// could have the specified known zero and known one bits, returning them in
868// min/max.
869static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000870 const APInt& KnownZero,
871 const APInt& KnownOne,
872 APInt& Min,
873 APInt& Max) {
874 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
875 assert(KnownZero.getBitWidth() == BitWidth &&
876 KnownOne.getBitWidth() == BitWidth &&
877 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
878 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000879 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000880
881 // The minimum value is when the unknown bits are all zeros.
882 Min = KnownOne;
883 // The maximum value is when the unknown bits are all ones.
884 Max = KnownOne|UnknownBits;
885}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886
Reid Spencer1791f232007-03-12 17:25:59 +0000887/// SimplifyDemandedBits - This function attempts to replace V with a simpler
888/// value based on the demanded bits. When this function is called, it is known
889/// that only the bits set in DemandedMask of the result of V are ever used
890/// downstream. Consequently, depending on the mask and V, it may be possible
891/// to replace V with a constant or one of its operands. In such cases, this
892/// function does the replacement and returns true. In all other cases, it
893/// returns false after analyzing the expression and setting KnownOne and known
894/// to be one in the expression. KnownZero contains all the bits that are known
895/// to be zero in the expression. These are provided to potentially allow the
896/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
897/// the expression. KnownOne and KnownZero always follow the invariant that
898/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
899/// the bits in KnownOne and KnownZero may only be accurate for those bits set
900/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
901/// and KnownOne must all be the same.
902bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
903 APInt& KnownZero, APInt& KnownOne,
904 unsigned Depth) {
905 assert(V != 0 && "Null pointer of Value???");
906 assert(Depth <= 6 && "Limit Search Depth");
907 uint32_t BitWidth = DemandedMask.getBitWidth();
908 const IntegerType *VTy = cast<IntegerType>(V->getType());
909 assert(VTy->getBitWidth() == BitWidth &&
910 KnownZero.getBitWidth() == BitWidth &&
911 KnownOne.getBitWidth() == BitWidth &&
912 "Value *V, DemandedMask, KnownZero and KnownOne \
913 must have same BitWidth");
914 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
915 // We know all of the bits for a constant!
916 KnownOne = CI->getValue() & DemandedMask;
917 KnownZero = ~KnownOne & DemandedMask;
918 return false;
919 }
920
Zhou Shengb9128442007-03-14 03:21:24 +0000921 KnownZero.clear();
922 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000923 if (!V->hasOneUse()) { // Other users may use these bits.
924 if (Depth != 0) { // Not at the root.
925 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
926 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
927 return false;
928 }
929 // If this is the root being simplified, allow it to have multiple uses,
930 // just set the DemandedMask to all bits.
931 DemandedMask = APInt::getAllOnesValue(BitWidth);
932 } else if (DemandedMask == 0) { // Not demanding any bits from V.
933 if (V != UndefValue::get(VTy))
934 return UpdateValueUsesWith(V, UndefValue::get(VTy));
935 return false;
936 } else if (Depth == 6) { // Limit search depth.
937 return false;
938 }
939
940 Instruction *I = dyn_cast<Instruction>(V);
941 if (!I) return false; // Only analyze instructions.
942
Reid Spencer1791f232007-03-12 17:25:59 +0000943 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
944 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
945 switch (I->getOpcode()) {
946 default: break;
947 case Instruction::And:
948 // If either the LHS or the RHS are Zero, the result is zero.
949 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
950 RHSKnownZero, RHSKnownOne, Depth+1))
951 return true;
952 assert((RHSKnownZero & RHSKnownOne) == 0 &&
953 "Bits known to be one AND zero?");
954
955 // If something is known zero on the RHS, the bits aren't demanded on the
956 // LHS.
957 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
958 LHSKnownZero, LHSKnownOne, Depth+1))
959 return true;
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962
963 // If all of the demanded bits are known 1 on one side, return the other.
964 // These bits cannot contribute to the result of the 'and'.
965 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
966 (DemandedMask & ~LHSKnownZero))
967 return UpdateValueUsesWith(I, I->getOperand(0));
968 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
969 (DemandedMask & ~RHSKnownZero))
970 return UpdateValueUsesWith(I, I->getOperand(1));
971
972 // If all of the demanded bits in the inputs are known zeros, return zero.
973 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
974 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
975
976 // If the RHS is a constant, see if we can simplify it.
977 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
978 return UpdateValueUsesWith(I, I);
979
980 // Output known-1 bits are only known if set in both the LHS & RHS.
981 RHSKnownOne &= LHSKnownOne;
982 // Output known-0 are known to be clear if zero in either the LHS | RHS.
983 RHSKnownZero |= LHSKnownZero;
984 break;
985 case Instruction::Or:
986 // If either the LHS or the RHS are One, the result is One.
987 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
988 RHSKnownZero, RHSKnownOne, Depth+1))
989 return true;
990 assert((RHSKnownZero & RHSKnownOne) == 0 &&
991 "Bits known to be one AND zero?");
992 // If something is known one on the RHS, the bits aren't demanded on the
993 // LHS.
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
995 LHSKnownZero, LHSKnownOne, Depth+1))
996 return true;
997 assert((LHSKnownZero & LHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
999
1000 // If all of the demanded bits are known zero on one side, return the other.
1001 // These bits cannot contribute to the result of the 'or'.
1002 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1003 (DemandedMask & ~LHSKnownOne))
1004 return UpdateValueUsesWith(I, I->getOperand(0));
1005 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1006 (DemandedMask & ~RHSKnownOne))
1007 return UpdateValueUsesWith(I, I->getOperand(1));
1008
1009 // If all of the potentially set bits on one side are known to be set on
1010 // the other side, just use the 'other' side.
1011 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1012 (DemandedMask & (~RHSKnownZero)))
1013 return UpdateValueUsesWith(I, I->getOperand(0));
1014 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1015 (DemandedMask & (~LHSKnownZero)))
1016 return UpdateValueUsesWith(I, I->getOperand(1));
1017
1018 // If the RHS is a constant, see if we can simplify it.
1019 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1020 return UpdateValueUsesWith(I, I);
1021
1022 // Output known-0 bits are only known if clear in both the LHS & RHS.
1023 RHSKnownZero &= LHSKnownZero;
1024 // Output known-1 are known to be set if set in either the LHS | RHS.
1025 RHSKnownOne |= LHSKnownOne;
1026 break;
1027 case Instruction::Xor: {
1028 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1029 RHSKnownZero, RHSKnownOne, Depth+1))
1030 return true;
1031 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1032 "Bits known to be one AND zero?");
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1034 LHSKnownZero, LHSKnownOne, Depth+1))
1035 return true;
1036 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1037 "Bits known to be one AND zero?");
1038
1039 // If all of the demanded bits are known zero on one side, return the other.
1040 // These bits cannot contribute to the result of the 'xor'.
1041 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1042 return UpdateValueUsesWith(I, I->getOperand(0));
1043 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1044 return UpdateValueUsesWith(I, I->getOperand(1));
1045
1046 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1047 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1048 (RHSKnownOne & LHSKnownOne);
1049 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1050 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1051 (RHSKnownOne & LHSKnownZero);
1052
1053 // If all of the demanded bits are known to be zero on one side or the
1054 // other, turn this into an *inclusive* or.
1055 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1056 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1057 Instruction *Or =
1058 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1059 I->getName());
1060 InsertNewInstBefore(Or, *I);
1061 return UpdateValueUsesWith(I, Or);
1062 }
1063
1064 // If all of the demanded bits on one side are known, and all of the set
1065 // bits on that side are also known to be set on the other side, turn this
1066 // into an AND, as we know the bits will be cleared.
1067 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1068 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1069 // all known
1070 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1071 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1072 Instruction *And =
1073 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1074 InsertNewInstBefore(And, *I);
1075 return UpdateValueUsesWith(I, And);
1076 }
1077 }
1078
1079 // If the RHS is a constant, see if we can simplify it.
1080 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1081 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1082 return UpdateValueUsesWith(I, I);
1083
1084 RHSKnownZero = KnownZeroOut;
1085 RHSKnownOne = KnownOneOut;
1086 break;
1087 }
1088 case Instruction::Select:
1089 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1090 RHSKnownZero, RHSKnownOne, Depth+1))
1091 return true;
1092 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1093 LHSKnownZero, LHSKnownOne, Depth+1))
1094 return true;
1095 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1096 "Bits known to be one AND zero?");
1097 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1098 "Bits known to be one AND zero?");
1099
1100 // If the operands are constants, see if we can simplify them.
1101 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1102 return UpdateValueUsesWith(I, I);
1103 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1104 return UpdateValueUsesWith(I, I);
1105
1106 // Only known if known in both the LHS and RHS.
1107 RHSKnownOne &= LHSKnownOne;
1108 RHSKnownZero &= LHSKnownZero;
1109 break;
1110 case Instruction::Trunc: {
1111 uint32_t truncBf =
1112 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1113 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1114 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1115 return true;
1116 DemandedMask.trunc(BitWidth);
1117 RHSKnownZero.trunc(BitWidth);
1118 RHSKnownOne.trunc(BitWidth);
1119 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1120 "Bits known to be one AND zero?");
1121 break;
1122 }
1123 case Instruction::BitCast:
1124 if (!I->getOperand(0)->getType()->isInteger())
1125 return false;
1126
1127 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
1129 return true;
1130 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1131 "Bits known to be one AND zero?");
1132 break;
1133 case Instruction::ZExt: {
1134 // Compute the bits in the result that are not present in the input.
1135 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001136 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1137 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001138
1139 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1140 uint32_t zextBf = SrcTy->getBitWidth();
1141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1142 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1143 return true;
1144 DemandedMask.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
1147 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1148 "Bits known to be one AND zero?");
1149 // The top bits are known to be zero.
1150 RHSKnownZero |= NewBits;
1151 break;
1152 }
1153 case Instruction::SExt: {
1154 // Compute the bits in the result that are not present in the input.
1155 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001156 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1157 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001158
1159 // Get the sign bit for the source type
1160 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1161 InSignBit.zext(BitWidth);
1162 APInt InputDemandedBits = DemandedMask &
1163 SrcTy->getMask().zext(BitWidth);
1164
1165 // If any of the sign extended bits are demanded, we know that the sign
1166 // bit is demanded.
1167 if ((NewBits & DemandedMask) != 0)
1168 InputDemandedBits |= InSignBit;
1169
1170 uint32_t sextBf = SrcTy->getBitWidth();
1171 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1172 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1173 return true;
1174 InputDemandedBits.zext(BitWidth);
1175 RHSKnownZero.zext(BitWidth);
1176 RHSKnownOne.zext(BitWidth);
1177 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1178 "Bits known to be one AND zero?");
1179
1180 // If the sign bit of the input is known set or clear, then we know the
1181 // top bits of the result.
1182
1183 // If the input sign bit is known zero, or if the NewBits are not demanded
1184 // convert this into a zero extension.
1185 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1186 {
1187 // Convert to ZExt cast
1188 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1189 return UpdateValueUsesWith(I, NewCast);
1190 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1191 RHSKnownOne |= NewBits;
1192 RHSKnownZero &= ~NewBits;
1193 } else { // Input sign bit unknown
1194 RHSKnownZero &= ~NewBits;
1195 RHSKnownOne &= ~NewBits;
1196 }
1197 break;
1198 }
1199 case Instruction::Add: {
1200 // Figure out what the input bits are. If the top bits of the and result
1201 // are not demanded, then the add doesn't demand them from its input
1202 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001203 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001204
1205 // If there is a constant on the RHS, there are a variety of xformations
1206 // we can do.
1207 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1208 // If null, this should be simplified elsewhere. Some of the xforms here
1209 // won't work if the RHS is zero.
1210 if (RHS->isZero())
1211 break;
1212
1213 // If the top bit of the output is demanded, demand everything from the
1214 // input. Otherwise, we demand all the input bits except NLZ top bits.
1215 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1216
1217 // Find information about known zero/one bits in the input.
1218 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1219 LHSKnownZero, LHSKnownOne, Depth+1))
1220 return true;
1221
1222 // If the RHS of the add has bits set that can't affect the input, reduce
1223 // the constant.
1224 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1225 return UpdateValueUsesWith(I, I);
1226
1227 // Avoid excess work.
1228 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1229 break;
1230
1231 // Turn it into OR if input bits are zero.
1232 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1233 Instruction *Or =
1234 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1235 I->getName());
1236 InsertNewInstBefore(Or, *I);
1237 return UpdateValueUsesWith(I, Or);
1238 }
1239
1240 // We can say something about the output known-zero and known-one bits,
1241 // depending on potential carries from the input constant and the
1242 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1243 // bits set and the RHS constant is 0x01001, then we know we have a known
1244 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1245
1246 // To compute this, we first compute the potential carry bits. These are
1247 // the bits which may be modified. I'm not aware of a better way to do
1248 // this scan.
1249 APInt RHSVal(RHS->getValue());
1250
1251 bool CarryIn = false;
1252 APInt CarryBits(BitWidth, 0);
1253 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1254 *RHSRawVal = RHSVal.getRawData();
1255 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1256 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1257 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1258 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1259 if (AddVal < RHSRawVal[i])
1260 CarryIn = true;
1261 else
1262 CarryIn = false;
1263 CarryBits.setWordToValue(i, WordCarryBits);
1264 }
1265
1266 // Now that we know which bits have carries, compute the known-1/0 sets.
1267
1268 // Bits are known one if they are known zero in one operand and one in the
1269 // other, and there is no input carry.
1270 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1271 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1272
1273 // Bits are known zero if they are known zero in both operands and there
1274 // is no input carry.
1275 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1276 } else {
1277 // If the high-bits of this ADD are not demanded, then it does not demand
1278 // the high bits of its LHS or RHS.
1279 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1280 // Right fill the mask of bits for this ADD to demand the most
1281 // significant bit and all those below it.
1282 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1283 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1284 LHSKnownZero, LHSKnownOne, Depth+1))
1285 return true;
1286 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1287 LHSKnownZero, LHSKnownOne, Depth+1))
1288 return true;
1289 }
1290 }
1291 break;
1292 }
1293 case Instruction::Sub:
1294 // If the high-bits of this SUB are not demanded, then it does not demand
1295 // the high bits of its LHS or RHS.
1296 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1297 // Right fill the mask of bits for this SUB to demand the most
1298 // significant bit and all those below it.
Reid Spencer52830322007-03-25 21:11:44 +00001299 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001300 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1301 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1303 return true;
1304 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1305 LHSKnownZero, LHSKnownOne, Depth+1))
1306 return true;
1307 }
1308 break;
1309 case Instruction::Shl:
1310 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1311 uint64_t ShiftAmt = SA->getZExtValue();
1312 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1313 RHSKnownZero, RHSKnownOne, Depth+1))
1314 return true;
1315 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1316 "Bits known to be one AND zero?");
1317 RHSKnownZero <<= ShiftAmt;
1318 RHSKnownOne <<= ShiftAmt;
1319 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001320 if (ShiftAmt)
1321 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001322 }
1323 break;
1324 case Instruction::LShr:
1325 // For a logical shift right
1326 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1327 unsigned ShiftAmt = SA->getZExtValue();
1328
1329 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1330 // Unsigned shift right.
1331 if (SimplifyDemandedBits(I->getOperand(0),
1332 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1333 RHSKnownZero, RHSKnownOne, Depth+1))
1334 return true;
1335 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1336 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001337 RHSKnownZero &= TypeMask;
1338 RHSKnownOne &= TypeMask;
1339 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001341 if (ShiftAmt) {
1342 // Compute the new bits that are at the top now.
1343 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
1344 BitWidth - ShiftAmt));
1345 RHSKnownZero |= HighBits; // high bits known zero.
1346 }
Reid Spencer1791f232007-03-12 17:25:59 +00001347 }
1348 break;
1349 case Instruction::AShr:
1350 // If this is an arithmetic shift right and only the low-bit is set, we can
1351 // always convert this into a logical shr, even if the shift amount is
1352 // variable. The low bit of the shift cannot be an input sign bit unless
1353 // the shift amount is >= the size of the datatype, which is undefined.
1354 if (DemandedMask == 1) {
1355 // Perform the logical shift right.
1356 Value *NewVal = BinaryOperator::createLShr(
1357 I->getOperand(0), I->getOperand(1), I->getName());
1358 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1359 return UpdateValueUsesWith(I, NewVal);
1360 }
1361
1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1363 unsigned ShiftAmt = SA->getZExtValue();
1364
1365 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1366 // Signed shift right.
1367 if (SimplifyDemandedBits(I->getOperand(0),
1368 (DemandedMask.shl(ShiftAmt)) & TypeMask,
1369 RHSKnownZero, RHSKnownOne, Depth+1))
1370 return true;
1371 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1372 "Bits known to be one AND zero?");
1373 // Compute the new bits that are at the top now.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001374 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001375 RHSKnownZero &= TypeMask;
1376 RHSKnownOne &= TypeMask;
1377 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379
1380 // Handle the sign bits.
1381 APInt SignBit(APInt::getSignBit(BitWidth));
1382 // Adjust to where it is now in the mask.
1383 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1384
1385 // If the input sign bit is known to be zero, or if none of the top bits
1386 // are demanded, turn this into an unsigned shift right.
1387 if ((RHSKnownZero & SignBit) != 0 ||
1388 (HighBits & ~DemandedMask) == HighBits) {
1389 // Perform the logical shift right.
1390 Value *NewVal = BinaryOperator::createLShr(
1391 I->getOperand(0), SA, I->getName());
1392 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393 return UpdateValueUsesWith(I, NewVal);
1394 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395 RHSKnownOne |= HighBits;
1396 }
1397 }
1398 break;
1399 }
1400
1401 // If the client is only demanding bits that we know, return the known
1402 // constant.
1403 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405 return false;
1406}
1407
Chris Lattner2deeaea2006-10-05 06:55:50 +00001408
1409/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410/// 64 or fewer elements. DemandedElts contains the set of elements that are
1411/// actually used by the caller. This method analyzes which elements of the
1412/// operand are undef and returns that information in UndefElts.
1413///
1414/// If the information about demanded elements can be used to simplify the
1415/// operation, the operation is simplified, then the resultant value is
1416/// returned. This returns null if no change was made.
1417Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418 uint64_t &UndefElts,
1419 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001420 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001421 assert(VWidth <= 64 && "Vector too wide to analyze!");
1422 uint64_t EltMask = ~0ULL >> (64-VWidth);
1423 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424 "Invalid DemandedElts!");
1425
1426 if (isa<UndefValue>(V)) {
1427 // If the entire vector is undefined, just return this info.
1428 UndefElts = EltMask;
1429 return 0;
1430 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431 UndefElts = EltMask;
1432 return UndefValue::get(V->getType());
1433 }
1434
1435 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001436 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001438 Constant *Undef = UndefValue::get(EltTy);
1439
1440 std::vector<Constant*> Elts;
1441 for (unsigned i = 0; i != VWidth; ++i)
1442 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1443 Elts.push_back(Undef);
1444 UndefElts |= (1ULL << i);
1445 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1446 Elts.push_back(Undef);
1447 UndefElts |= (1ULL << i);
1448 } else { // Otherwise, defined.
1449 Elts.push_back(CP->getOperand(i));
1450 }
1451
1452 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001453 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001454 return NewCP != CP ? NewCP : 0;
1455 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001456 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001457 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001458 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001459 Constant *Zero = Constant::getNullValue(EltTy);
1460 Constant *Undef = UndefValue::get(EltTy);
1461 std::vector<Constant*> Elts;
1462 for (unsigned i = 0; i != VWidth; ++i)
1463 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001465 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001466 }
1467
1468 if (!V->hasOneUse()) { // Other users may use these bits.
1469 if (Depth != 0) { // Not at the root.
1470 // TODO: Just compute the UndefElts information recursively.
1471 return false;
1472 }
1473 return false;
1474 } else if (Depth == 10) { // Limit search depth.
1475 return false;
1476 }
1477
1478 Instruction *I = dyn_cast<Instruction>(V);
1479 if (!I) return false; // Only analyze instructions.
1480
1481 bool MadeChange = false;
1482 uint64_t UndefElts2;
1483 Value *TmpV;
1484 switch (I->getOpcode()) {
1485 default: break;
1486
1487 case Instruction::InsertElement: {
1488 // If this is a variable index, we don't know which element it overwrites.
1489 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001490 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001491 if (Idx == 0) {
1492 // Note that we can't propagate undef elt info, because we don't know
1493 // which elt is getting updated.
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495 UndefElts2, Depth+1);
1496 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497 break;
1498 }
1499
1500 // If this is inserting an element that isn't demanded, remove this
1501 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001502 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001503 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504 return AddSoonDeadInstToWorklist(*I, 0);
1505
1506 // Otherwise, the element inserted overwrites whatever was there, so the
1507 // input demanded set is simpler than the output set.
1508 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509 DemandedElts & ~(1ULL << IdxNo),
1510 UndefElts, Depth+1);
1511 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513 // The inserted element is defined.
1514 UndefElts |= 1ULL << IdxNo;
1515 break;
1516 }
1517
1518 case Instruction::And:
1519 case Instruction::Or:
1520 case Instruction::Xor:
1521 case Instruction::Add:
1522 case Instruction::Sub:
1523 case Instruction::Mul:
1524 // div/rem demand all inputs, because they don't want divide by zero.
1525 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526 UndefElts, Depth+1);
1527 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1529 UndefElts2, Depth+1);
1530 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1531
1532 // Output elements are undefined if both are undefined. Consider things
1533 // like undef&0. The result is known zero, not undef.
1534 UndefElts &= UndefElts2;
1535 break;
1536
1537 case Instruction::Call: {
1538 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1539 if (!II) break;
1540 switch (II->getIntrinsicID()) {
1541 default: break;
1542
1543 // Binary vector operations that work column-wise. A dest element is a
1544 // function of the corresponding input elements from the two inputs.
1545 case Intrinsic::x86_sse_sub_ss:
1546 case Intrinsic::x86_sse_mul_ss:
1547 case Intrinsic::x86_sse_min_ss:
1548 case Intrinsic::x86_sse_max_ss:
1549 case Intrinsic::x86_sse2_sub_sd:
1550 case Intrinsic::x86_sse2_mul_sd:
1551 case Intrinsic::x86_sse2_min_sd:
1552 case Intrinsic::x86_sse2_max_sd:
1553 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1554 UndefElts, Depth+1);
1555 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1556 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1557 UndefElts2, Depth+1);
1558 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1559
1560 // If only the low elt is demanded and this is a scalarizable intrinsic,
1561 // scalarize it now.
1562 if (DemandedElts == 1) {
1563 switch (II->getIntrinsicID()) {
1564 default: break;
1565 case Intrinsic::x86_sse_sub_ss:
1566 case Intrinsic::x86_sse_mul_ss:
1567 case Intrinsic::x86_sse2_sub_sd:
1568 case Intrinsic::x86_sse2_mul_sd:
1569 // TODO: Lower MIN/MAX/ABS/etc
1570 Value *LHS = II->getOperand(1);
1571 Value *RHS = II->getOperand(2);
1572 // Extract the element as scalars.
1573 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1574 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1575
1576 switch (II->getIntrinsicID()) {
1577 default: assert(0 && "Case stmts out of sync!");
1578 case Intrinsic::x86_sse_sub_ss:
1579 case Intrinsic::x86_sse2_sub_sd:
1580 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1581 II->getName()), *II);
1582 break;
1583 case Intrinsic::x86_sse_mul_ss:
1584 case Intrinsic::x86_sse2_mul_sd:
1585 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1586 II->getName()), *II);
1587 break;
1588 }
1589
1590 Instruction *New =
1591 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1592 II->getName());
1593 InsertNewInstBefore(New, *II);
1594 AddSoonDeadInstToWorklist(*II, 0);
1595 return New;
1596 }
1597 }
1598
1599 // Output elements are undefined if both are undefined. Consider things
1600 // like undef&0. The result is known zero, not undef.
1601 UndefElts &= UndefElts2;
1602 break;
1603 }
1604 break;
1605 }
1606 }
1607 return MadeChange ? I : 0;
1608}
1609
Reid Spencer266e42b2006-12-23 06:05:41 +00001610/// @returns true if the specified compare instruction is
1611/// true when both operands are equal...
1612/// @brief Determine if the ICmpInst returns true if both operands are equal
1613static bool isTrueWhenEqual(ICmpInst &ICI) {
1614 ICmpInst::Predicate pred = ICI.getPredicate();
1615 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1616 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1617 pred == ICmpInst::ICMP_SLE;
1618}
1619
Chris Lattnerb8b97502003-08-13 19:01:45 +00001620/// AssociativeOpt - Perform an optimization on an associative operator. This
1621/// function is designed to check a chain of associative operators for a
1622/// potential to apply a certain optimization. Since the optimization may be
1623/// applicable if the expression was reassociated, this checks the chain, then
1624/// reassociates the expression as necessary to expose the optimization
1625/// opportunity. This makes use of a special Functor, which must define
1626/// 'shouldApply' and 'apply' methods.
1627///
1628template<typename Functor>
1629Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1630 unsigned Opcode = Root.getOpcode();
1631 Value *LHS = Root.getOperand(0);
1632
1633 // Quick check, see if the immediate LHS matches...
1634 if (F.shouldApply(LHS))
1635 return F.apply(Root);
1636
1637 // Otherwise, if the LHS is not of the same opcode as the root, return.
1638 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001639 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001640 // Should we apply this transform to the RHS?
1641 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1642
1643 // If not to the RHS, check to see if we should apply to the LHS...
1644 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1645 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1646 ShouldApply = true;
1647 }
1648
1649 // If the functor wants to apply the optimization to the RHS of LHSI,
1650 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1651 if (ShouldApply) {
1652 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001653
Chris Lattnerb8b97502003-08-13 19:01:45 +00001654 // Now all of the instructions are in the current basic block, go ahead
1655 // and perform the reassociation.
1656 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1657
1658 // First move the selected RHS to the LHS of the root...
1659 Root.setOperand(0, LHSI->getOperand(1));
1660
1661 // Make what used to be the LHS of the root be the user of the root...
1662 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001663 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001664 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1665 return 0;
1666 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001667 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001668 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001669 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1670 BasicBlock::iterator ARI = &Root; ++ARI;
1671 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1672 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001673
1674 // Now propagate the ExtraOperand down the chain of instructions until we
1675 // get to LHSI.
1676 while (TmpLHSI != LHSI) {
1677 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001678 // Move the instruction to immediately before the chain we are
1679 // constructing to avoid breaking dominance properties.
1680 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1681 BB->getInstList().insert(ARI, NextLHSI);
1682 ARI = NextLHSI;
1683
Chris Lattnerb8b97502003-08-13 19:01:45 +00001684 Value *NextOp = NextLHSI->getOperand(1);
1685 NextLHSI->setOperand(1, ExtraOperand);
1686 TmpLHSI = NextLHSI;
1687 ExtraOperand = NextOp;
1688 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001689
Chris Lattnerb8b97502003-08-13 19:01:45 +00001690 // Now that the instructions are reassociated, have the functor perform
1691 // the transformation...
1692 return F.apply(Root);
1693 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001694
Chris Lattnerb8b97502003-08-13 19:01:45 +00001695 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1696 }
1697 return 0;
1698}
1699
1700
1701// AddRHS - Implements: X + X --> X << 1
1702struct AddRHS {
1703 Value *RHS;
1704 AddRHS(Value *rhs) : RHS(rhs) {}
1705 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1706 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001707 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001708 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001709 }
1710};
1711
1712// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1713// iff C1&C2 == 0
1714struct AddMaskingAnd {
1715 Constant *C2;
1716 AddMaskingAnd(Constant *c) : C2(c) {}
1717 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001718 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001719 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001720 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001721 }
1722 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001723 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001724 }
1725};
1726
Chris Lattner86102b82005-01-01 16:22:27 +00001727static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001728 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001729 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001730 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001731 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001732
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001733 return IC->InsertNewInstBefore(CastInst::create(
1734 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001735 }
1736
Chris Lattner183b3362004-04-09 19:05:30 +00001737 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001738 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1739 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001740
Chris Lattner183b3362004-04-09 19:05:30 +00001741 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1742 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001743 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1744 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001745 }
1746
1747 Value *Op0 = SO, *Op1 = ConstOperand;
1748 if (!ConstIsRHS)
1749 std::swap(Op0, Op1);
1750 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001751 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1752 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001753 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1754 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1755 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001756 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001757 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001758 abort();
1759 }
Chris Lattner86102b82005-01-01 16:22:27 +00001760 return IC->InsertNewInstBefore(New, I);
1761}
1762
1763// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1764// constant as the other operand, try to fold the binary operator into the
1765// select arguments. This also works for Cast instructions, which obviously do
1766// not have a second operand.
1767static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1768 InstCombiner *IC) {
1769 // Don't modify shared select instructions
1770 if (!SI->hasOneUse()) return 0;
1771 Value *TV = SI->getOperand(1);
1772 Value *FV = SI->getOperand(2);
1773
1774 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001775 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001776 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001777
Chris Lattner86102b82005-01-01 16:22:27 +00001778 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1779 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1780
1781 return new SelectInst(SI->getCondition(), SelectTrueVal,
1782 SelectFalseVal);
1783 }
1784 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001785}
1786
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001787
1788/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1789/// node as operand #0, see if we can fold the instruction into the PHI (which
1790/// is only possible if all operands to the PHI are constants).
1791Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1792 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001793 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001794 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001795
Chris Lattner04689872006-09-09 22:02:56 +00001796 // Check to see if all of the operands of the PHI are constants. If there is
1797 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001798 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001799 BasicBlock *NonConstBB = 0;
1800 for (unsigned i = 0; i != NumPHIValues; ++i)
1801 if (!isa<Constant>(PN->getIncomingValue(i))) {
1802 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001803 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001804 NonConstBB = PN->getIncomingBlock(i);
1805
1806 // If the incoming non-constant value is in I's block, we have an infinite
1807 // loop.
1808 if (NonConstBB == I.getParent())
1809 return 0;
1810 }
1811
1812 // If there is exactly one non-constant value, we can insert a copy of the
1813 // operation in that block. However, if this is a critical edge, we would be
1814 // inserting the computation one some other paths (e.g. inside a loop). Only
1815 // do this if the pred block is unconditionally branching into the phi block.
1816 if (NonConstBB) {
1817 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1818 if (!BI || !BI->isUnconditional()) return 0;
1819 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001820
1821 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001822 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001823 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001824 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001825 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001826
1827 // Next, add all of the operands to the PHI.
1828 if (I.getNumOperands() == 2) {
1829 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001830 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001831 Value *InV;
1832 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001833 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1834 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1835 else
1836 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001837 } else {
1838 assert(PN->getIncomingBlock(i) == NonConstBB);
1839 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1840 InV = BinaryOperator::create(BO->getOpcode(),
1841 PN->getIncomingValue(i), C, "phitmp",
1842 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001843 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1844 InV = CmpInst::create(CI->getOpcode(),
1845 CI->getPredicate(),
1846 PN->getIncomingValue(i), C, "phitmp",
1847 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001848 else
1849 assert(0 && "Unknown binop!");
1850
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001851 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001852 }
1853 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001854 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001855 } else {
1856 CastInst *CI = cast<CastInst>(&I);
1857 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001858 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001859 Value *InV;
1860 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001861 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001862 } else {
1863 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001864 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1865 I.getType(), "phitmp",
1866 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001867 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001868 }
1869 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001870 }
1871 }
1872 return ReplaceInstUsesWith(I, NewPN);
1873}
1874
Chris Lattner113f4f42002-06-25 16:13:24 +00001875Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001876 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001877 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001878
Chris Lattnercf4a9962004-04-10 22:01:55 +00001879 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001880 // X + undef -> undef
1881 if (isa<UndefValue>(RHS))
1882 return ReplaceInstUsesWith(I, RHS);
1883
Chris Lattnercf4a9962004-04-10 22:01:55 +00001884 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001885 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001886 if (RHSC->isNullValue())
1887 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001888 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1889 if (CFP->isExactlyValue(-0.0))
1890 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001891 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001892
Chris Lattnercf4a9962004-04-10 22:01:55 +00001893 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001894 // X + (signbit) --> X ^ signbit
Reid Spencer959a21d2007-03-23 21:24:59 +00001895 APInt Val(CI->getValue());
1896 unsigned BitWidth = Val.getBitWidth();
1897 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001898 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001899
1900 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1901 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001902 if (!isa<VectorType>(I.getType())) {
1903 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1904 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1905 KnownZero, KnownOne))
1906 return &I;
1907 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001908 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001909
1910 if (isa<PHINode>(LHS))
1911 if (Instruction *NV = FoldOpIntoPhi(I))
1912 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001913
Chris Lattner330628a2006-01-06 17:59:59 +00001914 ConstantInt *XorRHS = 0;
1915 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001916 if (isa<ConstantInt>(RHSC) &&
1917 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001918 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00001919 APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001920
Reid Spencer959a21d2007-03-23 21:24:59 +00001921 unsigned Size = TySizeBits / 2;
1922 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1923 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001924 do {
1925 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001926 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1927 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001928 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1929 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001930 // This is a sign extend if the top bits are known zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00001931 APInt Mask(APInt::getAllOnesValue(TySizeBits));
1932 Mask <<= Size;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001933 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001934 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001935 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001936 }
1937 }
1938 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001939 C0080Val = APIntOps::lshr(C0080Val, Size);
1940 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1941 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001942
Reid Spencera5c18bf2007-03-28 01:36:16 +00001943 // FIXME: This shouldn't be necessary. When the backends can handle types
1944 // with funny bit widths then this whole cascade of if statements should
1945 // be removed. It is just here to get the size of the "middle" type back
1946 // up to something that the back ends can handle.
1947 const Type *MiddleType = 0;
1948 switch (Size) {
1949 default: break;
1950 case 32: MiddleType = Type::Int32Ty; break;
1951 case 16: MiddleType = Type::Int16Ty; break;
1952 case 8: MiddleType = Type::Int8Ty; break;
1953 }
1954 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001955 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001956 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001957 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001958 }
1959 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001960 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001961
Chris Lattnerb8b97502003-08-13 19:01:45 +00001962 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001963 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001964 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001965
1966 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1967 if (RHSI->getOpcode() == Instruction::Sub)
1968 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1969 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1970 }
1971 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1972 if (LHSI->getOpcode() == Instruction::Sub)
1973 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1974 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1975 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001976 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001977
Chris Lattner147e9752002-05-08 22:46:53 +00001978 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001979 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001980 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001981
1982 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001983 if (!isa<Constant>(RHS))
1984 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001985 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001986
Misha Brukmanb1c93172005-04-21 23:48:37 +00001987
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001988 ConstantInt *C2;
1989 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1990 if (X == RHS) // X*C + X --> X * (C+1)
1991 return BinaryOperator::createMul(RHS, AddOne(C2));
1992
1993 // X*C1 + X*C2 --> X * (C1+C2)
1994 ConstantInt *C1;
1995 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001996 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001997 }
1998
1999 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002000 if (dyn_castFoldableMul(RHS, C2) == LHS)
2001 return BinaryOperator::createMul(LHS, AddOne(C2));
2002
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002003 // X + ~X --> -1 since ~X = -X-1
2004 if (dyn_castNotVal(LHS) == RHS ||
2005 dyn_castNotVal(RHS) == LHS)
2006 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2007
Chris Lattner57c8d992003-02-18 19:57:07 +00002008
Chris Lattnerb8b97502003-08-13 19:01:45 +00002009 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002010 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002011 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2012 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002013
Chris Lattnerb9cde762003-10-02 15:11:26 +00002014 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002015 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00002016 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2017 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00002018
Chris Lattnerbff91d92004-10-08 05:07:56 +00002019 // (X & FF00) + xx00 -> (X+xx00) & FF00
2020 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002021 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00002022 if (Anded == CRHS) {
2023 // See if all bits from the first bit set in the Add RHS up are included
2024 // in the mask. First, get the rightmost bit.
Reid Spencer959a21d2007-03-23 21:24:59 +00002025 APInt AddRHSV(CRHS->getValue());
Chris Lattnerbff91d92004-10-08 05:07:56 +00002026
2027 // Form a mask of all bits from the lowest bit added through the top.
Reid Spencer959a21d2007-03-23 21:24:59 +00002028 APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2029 AddRHSHighBits &= C2->getType()->getMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002030
2031 // See if the and mask includes all of these bits.
Reid Spencer959a21d2007-03-23 21:24:59 +00002032 APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002033
Chris Lattnerbff91d92004-10-08 05:07:56 +00002034 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2035 // Okay, the xform is safe. Insert the new add pronto.
2036 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2037 LHS->getName()), I);
2038 return BinaryOperator::createAnd(NewAdd, C2);
2039 }
2040 }
2041 }
2042
Chris Lattnerd4252a72004-07-30 07:50:03 +00002043 // Try to fold constant add into select arguments.
2044 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002045 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002046 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002047 }
2048
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002049 // add (cast *A to intptrtype) B ->
2050 // cast (GEP (cast *A to sbyte*) B) ->
2051 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002052 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002053 CastInst *CI = dyn_cast<CastInst>(LHS);
2054 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002055 if (!CI) {
2056 CI = dyn_cast<CastInst>(RHS);
2057 Other = LHS;
2058 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002059 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002060 (CI->getType()->getPrimitiveSizeInBits() ==
2061 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002062 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002063 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002064 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002065 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002066 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002067 }
2068 }
2069
Chris Lattner113f4f42002-06-25 16:13:24 +00002070 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002071}
2072
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002073// isSignBit - Return true if the value represented by the constant only has the
2074// highest order bit set.
2075static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002076 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002077 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002078}
2079
Chris Lattner113f4f42002-06-25 16:13:24 +00002080Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002081 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002082
Chris Lattnere6794492002-08-12 21:17:25 +00002083 if (Op0 == Op1) // sub X, X -> 0
2084 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002085
Chris Lattnere6794492002-08-12 21:17:25 +00002086 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002087 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002088 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002089
Chris Lattner81a7a232004-10-16 18:11:37 +00002090 if (isa<UndefValue>(Op0))
2091 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2092 if (isa<UndefValue>(Op1))
2093 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2094
Chris Lattner8f2f5982003-11-05 01:06:05 +00002095 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2096 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002097 if (C->isAllOnesValue())
2098 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002099
Chris Lattner8f2f5982003-11-05 01:06:05 +00002100 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002101 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002102 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002103 return BinaryOperator::createAdd(X, AddOne(C));
2104
Chris Lattner27df1db2007-01-15 07:02:54 +00002105 // -(X >>u 31) -> (X >>s 31)
2106 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002107 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002108 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002109 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002110 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002111 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002112 if (CU->getZExtValue() ==
2113 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002114 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002115 return BinaryOperator::create(Instruction::AShr,
2116 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002117 }
2118 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002119 }
2120 else if (SI->getOpcode() == Instruction::AShr) {
2121 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2122 // Check to see if we are shifting out everything but the sign bit.
2123 if (CU->getZExtValue() ==
2124 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002125 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002126 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002127 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002128 }
2129 }
2130 }
Chris Lattner022167f2004-03-13 00:11:49 +00002131 }
Chris Lattner183b3362004-04-09 19:05:30 +00002132
2133 // Try to fold constant sub into select arguments.
2134 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002136 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002137
2138 if (isa<PHINode>(Op0))
2139 if (Instruction *NV = FoldOpIntoPhi(I))
2140 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002141 }
2142
Chris Lattnera9be4492005-04-07 16:15:25 +00002143 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2144 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002145 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002146 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002147 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002148 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002149 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002150 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2151 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2152 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002153 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002154 Op1I->getOperand(0));
2155 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002156 }
2157
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002158 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002159 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2160 // is not used by anyone else...
2161 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002162 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002163 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002164 // Swap the two operands of the subexpr...
2165 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2166 Op1I->setOperand(0, IIOp1);
2167 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002168
Chris Lattner3082c5a2003-02-18 19:28:33 +00002169 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002170 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002171 }
2172
2173 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2174 //
2175 if (Op1I->getOpcode() == Instruction::And &&
2176 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2177 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2178
Chris Lattner396dbfe2004-06-09 05:08:07 +00002179 Value *NewNot =
2180 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002181 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002182 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002183
Reid Spencer3c514952006-10-16 23:08:08 +00002184 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002185 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002186 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002187 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002188 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002189 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002190 ConstantExpr::getNeg(DivRHS));
2191
Chris Lattner57c8d992003-02-18 19:57:07 +00002192 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002193 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002194 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002195 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002196 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002197 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002198 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002199 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002200
Chris Lattner7a002fe2006-12-02 00:13:08 +00002201 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002202 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2203 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002204 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2205 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2206 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2207 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002208 } else if (Op0I->getOpcode() == Instruction::Sub) {
2209 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2210 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002211 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002212
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002213 ConstantInt *C1;
2214 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002215 if (X == Op1) // X*C - X --> X * (C-1)
2216 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002217
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002218 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2219 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002220 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002221 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002222 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002223}
2224
Reid Spencer266e42b2006-12-23 06:05:41 +00002225/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002226/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002227static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2228 switch (pred) {
2229 case ICmpInst::ICMP_SLT:
2230 // True if LHS s< RHS and RHS == 0
2231 return RHS->isNullValue();
2232 case ICmpInst::ICMP_SLE:
2233 // True if LHS s<= RHS and RHS == -1
2234 return RHS->isAllOnesValue();
2235 case ICmpInst::ICMP_UGE:
2236 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002237 return RHS->getValue() ==
2238 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002239 case ICmpInst::ICMP_UGT:
2240 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002241 return RHS->getValue() ==
2242 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002243 default:
2244 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002245 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002246}
2247
Chris Lattner113f4f42002-06-25 16:13:24 +00002248Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002249 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002250 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002251
Chris Lattner81a7a232004-10-16 18:11:37 +00002252 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2253 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2254
Chris Lattnere6794492002-08-12 21:17:25 +00002255 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002256 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2257 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002258
2259 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002260 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002261 if (SI->getOpcode() == Instruction::Shl)
2262 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002263 return BinaryOperator::createMul(SI->getOperand(0),
2264 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002265
Chris Lattnercce81be2003-09-11 22:24:54 +00002266 if (CI->isNullValue())
2267 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2268 if (CI->equalsInt(1)) // X * 1 == X
2269 return ReplaceInstUsesWith(I, Op0);
2270 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002271 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002272
Reid Spencer6d392062007-03-23 20:05:17 +00002273 APInt Val(cast<ConstantInt>(CI)->getValue());
2274 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002275 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002276 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002277 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002278 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002279 if (Op1F->isNullValue())
2280 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002281
Chris Lattner3082c5a2003-02-18 19:28:33 +00002282 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2283 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2284 if (Op1F->getValue() == 1.0)
2285 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2286 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002287
2288 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2289 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2290 isa<ConstantInt>(Op0I->getOperand(1))) {
2291 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2292 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2293 Op1, "tmp");
2294 InsertNewInstBefore(Add, I);
2295 Value *C1C2 = ConstantExpr::getMul(Op1,
2296 cast<Constant>(Op0I->getOperand(1)));
2297 return BinaryOperator::createAdd(Add, C1C2);
2298
2299 }
Chris Lattner183b3362004-04-09 19:05:30 +00002300
2301 // Try to fold constant mul into select arguments.
2302 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002303 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002304 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002305
2306 if (isa<PHINode>(Op0))
2307 if (Instruction *NV = FoldOpIntoPhi(I))
2308 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002309 }
2310
Chris Lattner934a64cf2003-03-10 23:23:04 +00002311 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2312 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002313 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002314
Chris Lattner2635b522004-02-23 05:39:21 +00002315 // If one of the operands of the multiply is a cast from a boolean value, then
2316 // we know the bool is either zero or one, so this is a 'masking' multiply.
2317 // See if we can simplify things based on how the boolean was originally
2318 // formed.
2319 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002320 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002321 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002322 BoolCast = CI;
2323 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002324 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002325 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002326 BoolCast = CI;
2327 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002328 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002329 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2330 const Type *SCOpTy = SCIOp0->getType();
2331
Reid Spencer266e42b2006-12-23 06:05:41 +00002332 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002333 // multiply into a shift/and combination.
2334 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002335 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002336 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002337 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002338 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002339 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002340 InsertNewInstBefore(
2341 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002342 BoolCast->getOperand(0)->getName()+
2343 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002344
2345 // If the multiply type is not the same as the source type, sign extend
2346 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002347 if (I.getType() != V->getType()) {
2348 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2349 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2350 Instruction::CastOps opcode =
2351 (SrcBits == DstBits ? Instruction::BitCast :
2352 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2353 V = InsertCastBefore(opcode, V, I.getType(), I);
2354 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002355
Chris Lattner2635b522004-02-23 05:39:21 +00002356 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002357 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002358 }
2359 }
2360 }
2361
Chris Lattner113f4f42002-06-25 16:13:24 +00002362 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002363}
2364
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002365/// This function implements the transforms on div instructions that work
2366/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2367/// used by the visitors to those instructions.
2368/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002369Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002370 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002371
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 // undef / X -> 0
2373 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002375
2376 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002377 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002379
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002380 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002381 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2382 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002383 // same basic block, then we replace the select with Y, and the condition
2384 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002385 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002387 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2388 if (ST->isNullValue()) {
2389 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2390 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002391 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002392 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2393 I.setOperand(1, SI->getOperand(2));
2394 else
2395 UpdateValueUsesWith(SI, SI->getOperand(2));
2396 return &I;
2397 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002398
Chris Lattnerd79dc792006-09-09 20:26:32 +00002399 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2400 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2401 if (ST->isNullValue()) {
2402 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2403 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002404 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002405 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2406 I.setOperand(1, SI->getOperand(1));
2407 else
2408 UpdateValueUsesWith(SI, SI->getOperand(1));
2409 return &I;
2410 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002411 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002412
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002413 return 0;
2414}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002415
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416/// This function implements the transforms common to both integer division
2417/// instructions (udiv and sdiv). It is called by the visitors to those integer
2418/// division instructions.
2419/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002420Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2422
2423 if (Instruction *Common = commonDivTransforms(I))
2424 return Common;
2425
2426 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2427 // div X, 1 == X
2428 if (RHS->equalsInt(1))
2429 return ReplaceInstUsesWith(I, Op0);
2430
2431 // (X / C1) / C2 -> X / (C1*C2)
2432 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2433 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2434 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2435 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002436 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002437 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002438
Reid Spencer6d392062007-03-23 20:05:17 +00002439 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002440 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2441 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2442 return R;
2443 if (isa<PHINode>(Op0))
2444 if (Instruction *NV = FoldOpIntoPhi(I))
2445 return NV;
2446 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002447 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002448
Chris Lattner3082c5a2003-02-18 19:28:33 +00002449 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002450 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002451 if (LHS->equalsInt(0))
2452 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2453
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002454 return 0;
2455}
2456
2457Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2459
2460 // Handle the integer div common cases
2461 if (Instruction *Common = commonIDivTransforms(I))
2462 return Common;
2463
2464 // X udiv C^2 -> X >> C
2465 // Check to see if this is an unsigned division with an exact power of 2,
2466 // if so, convert to a right shift.
2467 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002468 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002469 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002470 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002471 }
2472
2473 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002474 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002475 if (RHSI->getOpcode() == Instruction::Shl &&
2476 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002477 APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2478 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002479 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002480 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002481 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002482 Constant *C2V = ConstantInt::get(NTy, C2);
2483 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002484 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002485 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002486 }
2487 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002488 }
2489
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002490 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2491 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002492 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002493 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002494 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Reid Spencer6d392062007-03-23 20:05:17 +00002495 APInt TVA(STO->getValue()), FVA(SFO->getValue());
2496 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002497 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002498 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002499 // Construct the "on true" case of the select
2500 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2501 Instruction *TSI = BinaryOperator::createLShr(
2502 Op0, TC, SI->getName()+".t");
2503 TSI = InsertNewInstBefore(TSI, I);
2504
2505 // Construct the "on false" case of the select
2506 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2507 Instruction *FSI = BinaryOperator::createLShr(
2508 Op0, FC, SI->getName()+".f");
2509 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002510
Reid Spencer3939b1a2007-03-05 23:36:13 +00002511 // construct the select instruction and return it.
2512 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002513 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002514 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002515 return 0;
2516}
2517
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002518Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2520
2521 // Handle the integer div common cases
2522 if (Instruction *Common = commonIDivTransforms(I))
2523 return Common;
2524
2525 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2526 // sdiv X, -1 == -X
2527 if (RHS->isAllOnesValue())
2528 return BinaryOperator::createNeg(Op0);
2529
2530 // -X/C -> X/-C
2531 if (Value *LHSNeg = dyn_castNegVal(Op0))
2532 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2533 }
2534
2535 // If the sign bits of both operands are zero (i.e. we can prove they are
2536 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002537 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002538 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002539 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2540 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2541 }
2542 }
2543
2544 return 0;
2545}
2546
2547Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2548 return commonDivTransforms(I);
2549}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002550
Chris Lattner85dda9a2006-03-02 06:50:58 +00002551/// GetFactor - If we can prove that the specified value is at least a multiple
2552/// of some factor, return that factor.
2553static Constant *GetFactor(Value *V) {
2554 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2555 return CI;
2556
2557 // Unless we can be tricky, we know this is a multiple of 1.
2558 Constant *Result = ConstantInt::get(V->getType(), 1);
2559
2560 Instruction *I = dyn_cast<Instruction>(V);
2561 if (!I) return Result;
2562
2563 if (I->getOpcode() == Instruction::Mul) {
2564 // Handle multiplies by a constant, etc.
2565 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2566 GetFactor(I->getOperand(1)));
2567 } else if (I->getOpcode() == Instruction::Shl) {
2568 // (X<<C) -> X * (1 << C)
2569 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2570 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2571 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2572 }
2573 } else if (I->getOpcode() == Instruction::And) {
2574 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2575 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002576 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002577 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2578 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002579 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002580 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002581 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002582 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002583 if (!CI->isIntegerCast())
2584 return Result;
2585 Value *Op = CI->getOperand(0);
2586 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002587 }
2588 return Result;
2589}
2590
Reid Spencer7eb55b32006-11-02 01:53:59 +00002591/// This function implements the transforms on rem instructions that work
2592/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2593/// is used by the visitors to those instructions.
2594/// @brief Transforms common to all three rem instructions
2595Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002596 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002597
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002598 // 0 % X == 0, we don't need to preserve faults!
2599 if (Constant *LHS = dyn_cast<Constant>(Op0))
2600 if (LHS->isNullValue())
2601 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2602
2603 if (isa<UndefValue>(Op0)) // undef % X -> 0
2604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2605 if (isa<UndefValue>(Op1))
2606 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002607
2608 // Handle cases involving: rem X, (select Cond, Y, Z)
2609 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2610 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2611 // the same basic block, then we replace the select with Y, and the
2612 // condition of the select with false (if the cond value is in the same
2613 // BB). If the select has uses other than the div, this allows them to be
2614 // simplified also.
2615 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2616 if (ST->isNullValue()) {
2617 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2618 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002619 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002620 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2621 I.setOperand(1, SI->getOperand(2));
2622 else
2623 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002624 return &I;
2625 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002626 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2627 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2628 if (ST->isNullValue()) {
2629 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2630 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002631 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002632 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2633 I.setOperand(1, SI->getOperand(1));
2634 else
2635 UpdateValueUsesWith(SI, SI->getOperand(1));
2636 return &I;
2637 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002638 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002639
Reid Spencer7eb55b32006-11-02 01:53:59 +00002640 return 0;
2641}
2642
2643/// This function implements the transforms common to both integer remainder
2644/// instructions (urem and srem). It is called by the visitors to those integer
2645/// remainder instructions.
2646/// @brief Common integer remainder transforms
2647Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650 if (Instruction *common = commonRemTransforms(I))
2651 return common;
2652
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002653 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002654 // X % 0 == undef, we don't need to preserve faults!
2655 if (RHS->equalsInt(0))
2656 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2657
Chris Lattner3082c5a2003-02-18 19:28:33 +00002658 if (RHS->equalsInt(1)) // X % 1 == 0
2659 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2660
Chris Lattnerb70f1412006-02-28 05:49:21 +00002661 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2662 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2663 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2664 return R;
2665 } else if (isa<PHINode>(Op0I)) {
2666 if (Instruction *NV = FoldOpIntoPhi(I))
2667 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002668 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002669 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2670 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002671 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002672 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002673 }
2674
Reid Spencer7eb55b32006-11-02 01:53:59 +00002675 return 0;
2676}
2677
2678Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2679 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2680
2681 if (Instruction *common = commonIRemTransforms(I))
2682 return common;
2683
2684 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2685 // X urem C^2 -> X and C
2686 // Check to see if this is an unsigned remainder with an exact power of 2,
2687 // if so, convert to a bitwise and.
2688 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002689 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002690 return BinaryOperator::createAnd(Op0, SubOne(C));
2691 }
2692
Chris Lattner2e90b732006-02-05 07:54:04 +00002693 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002694 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2695 if (RHSI->getOpcode() == Instruction::Shl &&
2696 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002697 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002698 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2699 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2700 "tmp"), I);
2701 return BinaryOperator::createAnd(Op0, Add);
2702 }
2703 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002704 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002705
Reid Spencer7eb55b32006-11-02 01:53:59 +00002706 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2707 // where C1&C2 are powers of two.
2708 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2709 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2710 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2711 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002712 if ((STO->getValue().isPowerOf2()) &&
2713 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002714 Value *TrueAnd = InsertNewInstBefore(
2715 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2716 Value *FalseAnd = InsertNewInstBefore(
2717 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2718 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2719 }
2720 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002721 }
2722
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002723 return 0;
2724}
2725
Reid Spencer7eb55b32006-11-02 01:53:59 +00002726Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2728
2729 if (Instruction *common = commonIRemTransforms(I))
2730 return common;
2731
2732 if (Value *RHSNeg = dyn_castNegVal(Op1))
2733 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002734 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002735 // X % -Y -> X % Y
2736 AddUsesToWorkList(I);
2737 I.setOperand(1, RHSNeg);
2738 return &I;
2739 }
2740
2741 // If the top bits of both operands are zero (i.e. we can prove they are
2742 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002743 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002744 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2745 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2746 return BinaryOperator::createURem(Op0, Op1, I.getName());
2747 }
2748
2749 return 0;
2750}
2751
2752Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002753 return commonRemTransforms(I);
2754}
2755
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002756// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002757static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002758 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002759 if (isSigned) {
2760 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002761 APInt Val(APInt::getSignedMaxValue(TypeBits));
2762 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002763 }
Reid Spenceref599b02007-03-19 21:10:28 +00002764 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002765}
2766
2767// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002768static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2769 if (isSigned) {
2770 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002771 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2772 APInt Val(APInt::getSignedMinValue(TypeBits));
2773 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002774 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002775 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002776}
2777
Chris Lattner35167c32004-06-09 07:59:58 +00002778// isOneBitSet - Return true if there is exactly one bit set in the specified
2779// constant.
2780static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002781 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002782}
2783
Chris Lattner8fc5af42004-09-23 21:46:38 +00002784// isHighOnes - Return true if the constant is of the form 1+0+.
2785// This is the same as lowones(~X).
2786static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002787 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002788}
2789
Reid Spencer266e42b2006-12-23 06:05:41 +00002790/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791/// are carefully arranged to allow folding of expressions such as:
2792///
2793/// (A < B) | (A > B) --> (A != B)
2794///
Reid Spencer266e42b2006-12-23 06:05:41 +00002795/// Note that this is only valid if the first and second predicates have the
2796/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002797///
Reid Spencer266e42b2006-12-23 06:05:41 +00002798/// Three bits are used to represent the condition, as follows:
2799/// 0 A > B
2800/// 1 A == B
2801/// 2 A < B
2802///
2803/// <=> Value Definition
2804/// 000 0 Always false
2805/// 001 1 A > B
2806/// 010 2 A == B
2807/// 011 3 A >= B
2808/// 100 4 A < B
2809/// 101 5 A != B
2810/// 110 6 A <= B
2811/// 111 7 Always true
2812///
2813static unsigned getICmpCode(const ICmpInst *ICI) {
2814 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002815 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002816 case ICmpInst::ICMP_UGT: return 1; // 001
2817 case ICmpInst::ICMP_SGT: return 1; // 001
2818 case ICmpInst::ICMP_EQ: return 2; // 010
2819 case ICmpInst::ICMP_UGE: return 3; // 011
2820 case ICmpInst::ICMP_SGE: return 3; // 011
2821 case ICmpInst::ICMP_ULT: return 4; // 100
2822 case ICmpInst::ICMP_SLT: return 4; // 100
2823 case ICmpInst::ICMP_NE: return 5; // 101
2824 case ICmpInst::ICMP_ULE: return 6; // 110
2825 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002826 // True -> 7
2827 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002828 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002829 return 0;
2830 }
2831}
2832
Reid Spencer266e42b2006-12-23 06:05:41 +00002833/// getICmpValue - This is the complement of getICmpCode, which turns an
2834/// opcode and two operands into either a constant true or false, or a brand
2835/// new /// ICmp instruction. The sign is passed in to determine which kind
2836/// of predicate to use in new icmp instructions.
2837static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2838 switch (code) {
2839 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002840 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002841 case 1:
2842 if (sign)
2843 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2844 else
2845 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2846 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2847 case 3:
2848 if (sign)
2849 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2850 else
2851 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2852 case 4:
2853 if (sign)
2854 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2855 else
2856 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2857 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2858 case 6:
2859 if (sign)
2860 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2861 else
2862 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002863 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002864 }
2865}
2866
Reid Spencer266e42b2006-12-23 06:05:41 +00002867static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2868 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2869 (ICmpInst::isSignedPredicate(p1) &&
2870 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2871 (ICmpInst::isSignedPredicate(p2) &&
2872 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2873}
2874
2875namespace {
2876// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2877struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002878 InstCombiner &IC;
2879 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002880 ICmpInst::Predicate pred;
2881 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2882 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2883 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002884 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002885 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2886 if (PredicatesFoldable(pred, ICI->getPredicate()))
2887 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2888 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002889 return false;
2890 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002891 Instruction *apply(Instruction &Log) const {
2892 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2893 if (ICI->getOperand(0) != LHS) {
2894 assert(ICI->getOperand(1) == LHS);
2895 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002896 }
2897
Chris Lattnerd1bce952007-03-13 14:27:42 +00002898 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002899 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002900 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002901 unsigned Code;
2902 switch (Log.getOpcode()) {
2903 case Instruction::And: Code = LHSCode & RHSCode; break;
2904 case Instruction::Or: Code = LHSCode | RHSCode; break;
2905 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002906 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002907 }
2908
Chris Lattnerd1bce952007-03-13 14:27:42 +00002909 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2910 ICmpInst::isSignedPredicate(ICI->getPredicate());
2911
2912 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002913 if (Instruction *I = dyn_cast<Instruction>(RV))
2914 return I;
2915 // Otherwise, it's a constant boolean value...
2916 return IC.ReplaceInstUsesWith(Log, RV);
2917 }
2918};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002919} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002920
Chris Lattnerba1cb382003-09-19 17:17:26 +00002921// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2922// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002923// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002924Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002925 ConstantInt *OpRHS,
2926 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002927 BinaryOperator &TheAnd) {
2928 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002929 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002930 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002931 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002932
Chris Lattnerba1cb382003-09-19 17:17:26 +00002933 switch (Op->getOpcode()) {
2934 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002935 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002936 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002937 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002938 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002939 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002940 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002941 }
2942 break;
2943 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002944 if (Together == AndRHS) // (X | C) & C --> C
2945 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002946
Chris Lattner86102b82005-01-01 16:22:27 +00002947 if (Op->hasOneUse() && Together != OpRHS) {
2948 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002949 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002950 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002951 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002952 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002953 }
2954 break;
2955 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002956 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002957 // Adding a one to a single bit bit-field should be turned into an XOR
2958 // of the bit. First thing to check is to see if this AND is with a
2959 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00002960 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00002961
2962 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002963 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002964 // Ok, at this point, we know that we are masking the result of the
2965 // ADD down to exactly one bit. If the constant we are adding has
2966 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00002967 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002968
Chris Lattnerba1cb382003-09-19 17:17:26 +00002969 // Check to see if any bits below the one bit set in AndRHSV are set.
2970 if ((AddRHS & (AndRHSV-1)) == 0) {
2971 // If not, the only thing that can effect the output of the AND is
2972 // the bit specified by AndRHSV. If that bit is set, the effect of
2973 // the XOR is to toggle the bit. If it is clear, then the ADD has
2974 // no effect.
2975 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2976 TheAnd.setOperand(0, X);
2977 return &TheAnd;
2978 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002979 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002980 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002981 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002982 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002983 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002984 }
2985 }
2986 }
2987 }
2988 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002989
2990 case Instruction::Shl: {
2991 // We know that the AND will not produce any of the bits shifted in, so if
2992 // the anded constant includes them, clear them now!
2993 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002994 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002995 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2996 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002997
Chris Lattner7e794272004-09-24 15:21:34 +00002998 if (CI == ShlMask) { // Masking out bits that the shift already masks
2999 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3000 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003001 TheAnd.setOperand(1, CI);
3002 return &TheAnd;
3003 }
3004 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003005 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003006 case Instruction::LShr:
3007 {
Chris Lattner2da29172003-09-19 19:05:02 +00003008 // We know that the AND will not produce any of the bits shifted in, so if
3009 // the anded constant includes them, clear them now! This only applies to
3010 // unsigned shifts, because a signed shr may bring in set bits!
3011 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003012 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003013 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3014 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003015
Reid Spencerfdff9382006-11-08 06:47:33 +00003016 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3017 return ReplaceInstUsesWith(TheAnd, Op);
3018 } else if (CI != AndRHS) {
3019 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3020 return &TheAnd;
3021 }
3022 break;
3023 }
3024 case Instruction::AShr:
3025 // Signed shr.
3026 // See if this is shifting in some sign extension, then masking it out
3027 // with an and.
3028 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003029 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003030 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003031 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3032 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003033 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003034 // Make the argument unsigned.
3035 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003036 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003037 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003038 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003039 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003040 }
Chris Lattner2da29172003-09-19 19:05:02 +00003041 }
3042 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003043 }
3044 return 0;
3045}
3046
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003047
Chris Lattner6862fbd2004-09-29 17:40:11 +00003048/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3049/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003050/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3051/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003052/// insert new instructions.
3053Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003054 bool isSigned, bool Inside,
3055 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003056 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003057 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003058 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003059
Chris Lattner6862fbd2004-09-29 17:40:11 +00003060 if (Inside) {
3061 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003062 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003063
Reid Spencer266e42b2006-12-23 06:05:41 +00003064 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003065 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003066 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003067 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3068 return new ICmpInst(pred, V, Hi);
3069 }
3070
3071 // Emit V-Lo <u Hi-Lo
3072 Constant *NegLo = ConstantExpr::getNeg(Lo);
3073 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003074 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003075 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3076 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003077 }
3078
3079 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003080 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003081
Reid Spencerf4071162007-03-21 23:19:50 +00003082 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003083 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003084 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003085 ICmpInst::Predicate pred = (isSigned ?
3086 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3087 return new ICmpInst(pred, V, Hi);
3088 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003089
Reid Spencerf4071162007-03-21 23:19:50 +00003090 // Emit V-Lo >u Hi-1-Lo
3091 // Note that Hi has already had one subtracted from it, above.
3092 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003093 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003094 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003095 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3096 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003097}
3098
Chris Lattnerb4b25302005-09-18 07:22:02 +00003099// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3100// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3101// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3102// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003103static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencera962d182007-03-24 00:42:08 +00003104 APInt V = Val->getValue();
3105 uint32_t BitWidth = Val->getType()->getBitWidth();
3106 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003107
3108 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003109 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003110 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003111 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003112 return true;
3113}
3114
Chris Lattnerb4b25302005-09-18 07:22:02 +00003115/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3116/// where isSub determines whether the operator is a sub. If we can fold one of
3117/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003118///
3119/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3120/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3121/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3122///
3123/// return (A +/- B).
3124///
3125Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003126 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003127 Instruction &I) {
3128 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3129 if (!LHSI || LHSI->getNumOperands() != 2 ||
3130 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3131
3132 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3133
3134 switch (LHSI->getOpcode()) {
3135 default: return 0;
3136 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003137 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003138 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003139 if ((Mask->getValue().countLeadingZeros() +
3140 Mask->getValue().countPopulation()) ==
3141 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003142 break;
3143
3144 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3145 // part, we don't need any explicit masks to take them out of A. If that
3146 // is all N is, ignore it.
Reid Spencer755d0e72007-03-26 17:44:01 +00003147 unsigned MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003148 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003149 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3150 APInt Mask(APInt::getAllOnesValue(BitWidth));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003151 Mask = Mask.lshr(BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003152 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003153 break;
3154 }
3155 }
Chris Lattneraf517572005-09-18 04:24:45 +00003156 return 0;
3157 case Instruction::Or:
3158 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003159 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003160 if ((Mask->getValue().countLeadingZeros() +
3161 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003162 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003163 break;
3164 return 0;
3165 }
3166
3167 Instruction *New;
3168 if (isSub)
3169 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3170 else
3171 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3172 return InsertNewInstBefore(New, I);
3173}
3174
Chris Lattner113f4f42002-06-25 16:13:24 +00003175Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003176 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003178
Chris Lattner81a7a232004-10-16 18:11:37 +00003179 if (isa<UndefValue>(Op1)) // X & undef -> 0
3180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3181
Chris Lattner86102b82005-01-01 16:22:27 +00003182 // and X, X = X
3183 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003184 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003185
Chris Lattner5b2edb12006-02-12 08:02:11 +00003186 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003187 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003188 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003189 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3190 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3191 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003192 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003193 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003194 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003195 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003196 if (CP->isAllOnesValue())
3197 return ReplaceInstUsesWith(I, I.getOperand(0));
3198 }
3199 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003200
Zhou Sheng75b871f2007-01-11 12:24:14 +00003201 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003202 APInt AndRHSMask(AndRHS->getValue());
3203 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3204 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003205
Chris Lattnerba1cb382003-09-19 17:17:26 +00003206 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003207 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003208 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003209 Value *Op0LHS = Op0I->getOperand(0);
3210 Value *Op0RHS = Op0I->getOperand(1);
3211 switch (Op0I->getOpcode()) {
3212 case Instruction::Xor:
3213 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003214 // If the mask is only needed on one incoming arm, push it up.
3215 if (Op0I->hasOneUse()) {
3216 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3217 // Not masking anything out for the LHS, move to RHS.
3218 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3219 Op0RHS->getName()+".masked");
3220 InsertNewInstBefore(NewRHS, I);
3221 return BinaryOperator::create(
3222 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003223 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003224 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003225 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3226 // Not masking anything out for the RHS, move to LHS.
3227 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3228 Op0LHS->getName()+".masked");
3229 InsertNewInstBefore(NewLHS, I);
3230 return BinaryOperator::create(
3231 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3232 }
3233 }
3234
Chris Lattner86102b82005-01-01 16:22:27 +00003235 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003236 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003237 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3238 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3239 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3240 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3241 return BinaryOperator::createAnd(V, AndRHS);
3242 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3243 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003244 break;
3245
3246 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003247 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3248 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3249 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3250 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3251 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003252 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003253 }
3254
Chris Lattner16464b32003-07-23 19:25:52 +00003255 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003256 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003257 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003258 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003259 // If this is an integer truncation or change from signed-to-unsigned, and
3260 // if the source is an and/or with immediate, transform it. This
3261 // frequently occurs for bitfield accesses.
3262 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003263 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003264 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003265 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003266 if (CastOp->getOpcode() == Instruction::And) {
3267 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003268 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3269 // This will fold the two constants together, which may allow
3270 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003271 Instruction *NewCast = CastInst::createTruncOrBitCast(
3272 CastOp->getOperand(0), I.getType(),
3273 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003274 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003275 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003276 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003277 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003278 return BinaryOperator::createAnd(NewCast, C3);
3279 } else if (CastOp->getOpcode() == Instruction::Or) {
3280 // Change: and (cast (or X, C1) to T), C2
3281 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003282 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003283 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3284 return ReplaceInstUsesWith(I, AndRHS);
3285 }
3286 }
Chris Lattner33217db2003-07-23 19:36:21 +00003287 }
Chris Lattner183b3362004-04-09 19:05:30 +00003288
3289 // Try to fold constant and into select arguments.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003291 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003292 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003293 if (isa<PHINode>(Op0))
3294 if (Instruction *NV = FoldOpIntoPhi(I))
3295 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003296 }
3297
Chris Lattnerbb74e222003-03-10 23:06:50 +00003298 Value *Op0NotVal = dyn_castNotVal(Op0);
3299 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003300
Chris Lattner023a4832004-06-18 06:07:51 +00003301 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3303
Misha Brukman9c003d82004-07-30 12:50:08 +00003304 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003305 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003306 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3307 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003308 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003309 return BinaryOperator::createNot(Or);
3310 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003311
3312 {
3313 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003314 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3315 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3316 return ReplaceInstUsesWith(I, Op1);
3317 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3318 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3319 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003320
3321 if (Op0->hasOneUse() &&
3322 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3323 if (A == Op1) { // (A^B)&A -> A&(A^B)
3324 I.swapOperands(); // Simplify below
3325 std::swap(Op0, Op1);
3326 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3327 cast<BinaryOperator>(Op0)->swapOperands();
3328 I.swapOperands(); // Simplify below
3329 std::swap(Op0, Op1);
3330 }
3331 }
3332 if (Op1->hasOneUse() &&
3333 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3334 if (B == Op0) { // B&(A^B) -> B&(B^A)
3335 cast<BinaryOperator>(Op1)->swapOperands();
3336 std::swap(A, B);
3337 }
3338 if (A == Op0) { // A&(A^B) -> A & ~B
3339 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3340 InsertNewInstBefore(NotB, I);
3341 return BinaryOperator::createAnd(A, NotB);
3342 }
3343 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003344 }
3345
Reid Spencer266e42b2006-12-23 06:05:41 +00003346 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3347 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3348 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003349 return R;
3350
Chris Lattner623826c2004-09-28 21:48:02 +00003351 Value *LHSVal, *RHSVal;
3352 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003353 ICmpInst::Predicate LHSCC, RHSCC;
3354 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3355 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3356 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3357 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3358 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3359 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3360 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3361 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003362 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003363 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3364 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3365 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3366 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003367 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003368 std::swap(LHS, RHS);
3369 std::swap(LHSCst, RHSCst);
3370 std::swap(LHSCC, RHSCC);
3371 }
3372
Reid Spencer266e42b2006-12-23 06:05:41 +00003373 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003374 // comparing a value against two constants and and'ing the result
3375 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003376 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3377 // (from the FoldICmpLogical check above), that the two constants
3378 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003379 assert(LHSCst != RHSCst && "Compares not folded above?");
3380
3381 switch (LHSCC) {
3382 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003383 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003384 switch (RHSCC) {
3385 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003386 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3387 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3388 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003389 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003390 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3391 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3392 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003393 return ReplaceInstUsesWith(I, LHS);
3394 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003395 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003396 switch (RHSCC) {
3397 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003398 case ICmpInst::ICMP_ULT:
3399 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3400 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3401 break; // (X != 13 & X u< 15) -> no change
3402 case ICmpInst::ICMP_SLT:
3403 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3404 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3405 break; // (X != 13 & X s< 15) -> no change
3406 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3407 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3408 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003409 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003410 case ICmpInst::ICMP_NE:
3411 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003412 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3413 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3414 LHSVal->getName()+".off");
3415 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003416 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3417 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003418 }
3419 break; // (X != 13 & X != 15) -> no change
3420 }
3421 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003422 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003423 switch (RHSCC) {
3424 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003425 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3426 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003427 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003428 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3429 break;
3430 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3431 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003432 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003433 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3434 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003435 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003436 break;
3437 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003438 switch (RHSCC) {
3439 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003440 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3441 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003442 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003443 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3444 break;
3445 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3446 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003447 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003448 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3449 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003450 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003451 break;
3452 case ICmpInst::ICMP_UGT:
3453 switch (RHSCC) {
3454 default: assert(0 && "Unknown integer condition code!");
3455 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3456 return ReplaceInstUsesWith(I, LHS);
3457 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3458 return ReplaceInstUsesWith(I, RHS);
3459 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3460 break;
3461 case ICmpInst::ICMP_NE:
3462 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3463 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3464 break; // (X u> 13 & X != 15) -> no change
3465 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3466 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3467 true, I);
3468 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3469 break;
3470 }
3471 break;
3472 case ICmpInst::ICMP_SGT:
3473 switch (RHSCC) {
3474 default: assert(0 && "Unknown integer condition code!");
3475 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3476 return ReplaceInstUsesWith(I, LHS);
3477 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3478 return ReplaceInstUsesWith(I, RHS);
3479 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3480 break;
3481 case ICmpInst::ICMP_NE:
3482 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3483 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3484 break; // (X s> 13 & X != 15) -> no change
3485 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3486 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3487 true, I);
3488 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3489 break;
3490 }
3491 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003492 }
3493 }
3494 }
3495
Chris Lattner3af10532006-05-05 06:39:07 +00003496 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003497 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3498 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3499 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3500 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003501 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003502 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003503 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3504 I.getType(), TD) &&
3505 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3506 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003507 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3508 Op1C->getOperand(0),
3509 I.getName());
3510 InsertNewInstBefore(NewOp, I);
3511 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3512 }
Chris Lattner3af10532006-05-05 06:39:07 +00003513 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003514
3515 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003516 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3517 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3518 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003519 SI0->getOperand(1) == SI1->getOperand(1) &&
3520 (SI0->hasOneUse() || SI1->hasOneUse())) {
3521 Instruction *NewOp =
3522 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3523 SI1->getOperand(0),
3524 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003525 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3526 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003527 }
Chris Lattner3af10532006-05-05 06:39:07 +00003528 }
3529
Chris Lattner113f4f42002-06-25 16:13:24 +00003530 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003531}
3532
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003533/// CollectBSwapParts - Look to see if the specified value defines a single byte
3534/// in the result. If it does, and if the specified byte hasn't been filled in
3535/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003536static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003537 Instruction *I = dyn_cast<Instruction>(V);
3538 if (I == 0) return true;
3539
3540 // If this is an or instruction, it is an inner node of the bswap.
3541 if (I->getOpcode() == Instruction::Or)
3542 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3543 CollectBSwapParts(I->getOperand(1), ByteValues);
3544
3545 // If this is a shift by a constant int, and it is "24", then its operand
3546 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003547 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003548 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003549 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003550 8*(ByteValues.size()-1))
3551 return true;
3552
3553 unsigned DestNo;
3554 if (I->getOpcode() == Instruction::Shl) {
3555 // X << 24 defines the top byte with the lowest of the input bytes.
3556 DestNo = ByteValues.size()-1;
3557 } else {
3558 // X >>u 24 defines the low byte with the highest of the input bytes.
3559 DestNo = 0;
3560 }
3561
3562 // If the destination byte value is already defined, the values are or'd
3563 // together, which isn't a bswap (unless it's an or of the same bits).
3564 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3565 return true;
3566 ByteValues[DestNo] = I->getOperand(0);
3567 return false;
3568 }
3569
3570 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3571 // don't have this.
3572 Value *Shift = 0, *ShiftLHS = 0;
3573 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3574 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3575 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3576 return true;
3577 Instruction *SI = cast<Instruction>(Shift);
3578
3579 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003580 if (ShiftAmt->getZExtValue() & 7 ||
3581 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003582 return true;
3583
3584 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3585 unsigned DestByte;
3586 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003587 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003588 break;
3589 // Unknown mask for bswap.
3590 if (DestByte == ByteValues.size()) return true;
3591
Reid Spencere0fc4df2006-10-20 07:07:24 +00003592 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003593 unsigned SrcByte;
3594 if (SI->getOpcode() == Instruction::Shl)
3595 SrcByte = DestByte - ShiftBytes;
3596 else
3597 SrcByte = DestByte + ShiftBytes;
3598
3599 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3600 if (SrcByte != ByteValues.size()-DestByte-1)
3601 return true;
3602
3603 // If the destination byte value is already defined, the values are or'd
3604 // together, which isn't a bswap (unless it's an or of the same bits).
3605 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3606 return true;
3607 ByteValues[DestByte] = SI->getOperand(0);
3608 return false;
3609}
3610
3611/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3612/// If so, insert the new bswap intrinsic and return it.
3613Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003614 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003615 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003616 return 0;
3617
3618 /// ByteValues - For each byte of the result, we keep track of which value
3619 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003620 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003621 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003622
3623 // Try to find all the pieces corresponding to the bswap.
3624 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3625 CollectBSwapParts(I.getOperand(1), ByteValues))
3626 return 0;
3627
3628 // Check to see if all of the bytes come from the same value.
3629 Value *V = ByteValues[0];
3630 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3631
3632 // Check to make sure that all of the bytes come from the same value.
3633 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3634 if (ByteValues[i] != V)
3635 return 0;
3636
3637 // If they do then *success* we can turn this into a bswap. Figure out what
3638 // bswap to make it into.
3639 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003640 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003641 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003642 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003643 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003644 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003645 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003646 FnName = "llvm.bswap.i64";
3647 else
3648 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003649 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003650 return new CallInst(F, V);
3651}
3652
3653
Chris Lattner113f4f42002-06-25 16:13:24 +00003654Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003655 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003656 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003657
Chris Lattner3a8248f2007-03-24 23:56:43 +00003658 if (isa<UndefValue>(Op1)) // X | undef -> -1
3659 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003660
Chris Lattner5b2edb12006-02-12 08:02:11 +00003661 // or X, X = X
3662 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003663 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003664
Chris Lattner5b2edb12006-02-12 08:02:11 +00003665 // See if we can simplify any instructions used by the instruction whose sole
3666 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003667 if (!isa<VectorType>(I.getType())) {
3668 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3669 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3670 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3671 KnownZero, KnownOne))
3672 return &I;
3673 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003674
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003675 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003676 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003677 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003678 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3679 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003680 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003681 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003682 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003683 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3684 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003685
Chris Lattnerd4252a72004-07-30 07:50:03 +00003686 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3687 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003688 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003689 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003690 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003691 return BinaryOperator::createXor(Or,
3692 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003693 }
Chris Lattner183b3362004-04-09 19:05:30 +00003694
3695 // Try to fold constant and into select arguments.
3696 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003697 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003698 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003699 if (isa<PHINode>(Op0))
3700 if (Instruction *NV = FoldOpIntoPhi(I))
3701 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003702 }
3703
Chris Lattner330628a2006-01-06 17:59:59 +00003704 Value *A = 0, *B = 0;
3705 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003706
3707 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3708 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3709 return ReplaceInstUsesWith(I, Op1);
3710 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3711 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3712 return ReplaceInstUsesWith(I, Op0);
3713
Chris Lattnerb7845d62006-07-10 20:25:24 +00003714 // (A | B) | C and A | (B | C) -> bswap if possible.
3715 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003716 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003717 match(Op1, m_Or(m_Value(), m_Value())) ||
3718 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3719 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003720 if (Instruction *BSwap = MatchBSwap(I))
3721 return BSwap;
3722 }
3723
Chris Lattnerb62f5082005-05-09 04:58:36 +00003724 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3725 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003726 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003727 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3728 InsertNewInstBefore(NOr, I);
3729 NOr->takeName(Op0);
3730 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003731 }
3732
3733 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3734 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003735 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003736 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3737 InsertNewInstBefore(NOr, I);
3738 NOr->takeName(Op0);
3739 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003740 }
3741
Chris Lattner15212982005-09-18 03:42:07 +00003742 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003743 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003744 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3745
3746 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3747 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3748
3749
Chris Lattner01f56c62005-09-18 06:02:59 +00003750 // If we have: ((V + N) & C1) | (V & C2)
3751 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3752 // replace with V+N.
3753 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003754 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003755 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003756 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3757 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003758 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003759 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003760 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003761 return ReplaceInstUsesWith(I, A);
3762 }
3763 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003764 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003765 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3766 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003767 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003768 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003769 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003770 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003771 }
3772 }
3773 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003774
3775 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003776 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3777 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3778 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003779 SI0->getOperand(1) == SI1->getOperand(1) &&
3780 (SI0->hasOneUse() || SI1->hasOneUse())) {
3781 Instruction *NewOp =
3782 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3783 SI1->getOperand(0),
3784 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003785 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3786 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003787 }
3788 }
Chris Lattner812aab72003-08-12 19:11:07 +00003789
Chris Lattnerd4252a72004-07-30 07:50:03 +00003790 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3791 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003792 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003793 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003794 } else {
3795 A = 0;
3796 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003797 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003798 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3799 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003800 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003801 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003802
Misha Brukman9c003d82004-07-30 12:50:08 +00003803 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003804 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3805 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3806 I.getName()+".demorgan"), I);
3807 return BinaryOperator::createNot(And);
3808 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003809 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003810
Reid Spencer266e42b2006-12-23 06:05:41 +00003811 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3812 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3813 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003814 return R;
3815
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003816 Value *LHSVal, *RHSVal;
3817 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003818 ICmpInst::Predicate LHSCC, RHSCC;
3819 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3820 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3821 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3822 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3823 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3824 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3825 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3826 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003827 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003828 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3829 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3830 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3831 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003832 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003833 std::swap(LHS, RHS);
3834 std::swap(LHSCst, RHSCst);
3835 std::swap(LHSCC, RHSCC);
3836 }
3837
Reid Spencer266e42b2006-12-23 06:05:41 +00003838 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003839 // comparing a value against two constants and or'ing the result
3840 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003841 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3842 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003843 // equal.
3844 assert(LHSCst != RHSCst && "Compares not folded above?");
3845
3846 switch (LHSCC) {
3847 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003848 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003849 switch (RHSCC) {
3850 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003851 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003852 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3853 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3854 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3855 LHSVal->getName()+".off");
3856 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003857 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003858 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003859 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003860 break; // (X == 13 | X == 15) -> no change
3861 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3862 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003863 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003864 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3865 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3866 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003867 return ReplaceInstUsesWith(I, RHS);
3868 }
3869 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003870 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003871 switch (RHSCC) {
3872 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003873 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3874 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3875 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003876 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003877 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3878 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3879 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003881 }
3882 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003883 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003884 switch (RHSCC) {
3885 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003886 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003887 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003888 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3889 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3890 false, I);
3891 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3892 break;
3893 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3894 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003895 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003896 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3897 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003898 }
3899 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003900 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003901 switch (RHSCC) {
3902 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003903 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3904 break;
3905 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3906 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3907 false, I);
3908 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3909 break;
3910 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3911 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3912 return ReplaceInstUsesWith(I, RHS);
3913 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3914 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003915 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003916 break;
3917 case ICmpInst::ICMP_UGT:
3918 switch (RHSCC) {
3919 default: assert(0 && "Unknown integer condition code!");
3920 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3921 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3922 return ReplaceInstUsesWith(I, LHS);
3923 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3924 break;
3925 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3926 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003927 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003928 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3929 break;
3930 }
3931 break;
3932 case ICmpInst::ICMP_SGT:
3933 switch (RHSCC) {
3934 default: assert(0 && "Unknown integer condition code!");
3935 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3936 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3937 return ReplaceInstUsesWith(I, LHS);
3938 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3939 break;
3940 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3941 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003942 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003943 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3944 break;
3945 }
3946 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003947 }
3948 }
3949 }
Chris Lattner3af10532006-05-05 06:39:07 +00003950
3951 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003952 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003953 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003954 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3955 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003956 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003957 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003958 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3959 I.getType(), TD) &&
3960 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3961 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003962 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3963 Op1C->getOperand(0),
3964 I.getName());
3965 InsertNewInstBefore(NewOp, I);
3966 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3967 }
Chris Lattner3af10532006-05-05 06:39:07 +00003968 }
Chris Lattner3af10532006-05-05 06:39:07 +00003969
Chris Lattner15212982005-09-18 03:42:07 +00003970
Chris Lattner113f4f42002-06-25 16:13:24 +00003971 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003972}
3973
Chris Lattnerc2076352004-02-16 01:20:27 +00003974// XorSelf - Implements: X ^ X --> 0
3975struct XorSelf {
3976 Value *RHS;
3977 XorSelf(Value *rhs) : RHS(rhs) {}
3978 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3979 Instruction *apply(BinaryOperator &Xor) const {
3980 return &Xor;
3981 }
3982};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003983
3984
Chris Lattner113f4f42002-06-25 16:13:24 +00003985Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003986 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003988
Chris Lattner81a7a232004-10-16 18:11:37 +00003989 if (isa<UndefValue>(Op1))
3990 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3991
Chris Lattnerc2076352004-02-16 01:20:27 +00003992 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3993 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3994 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003996 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003997
3998 // See if we can simplify any instructions used by the instruction whose sole
3999 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004000 if (!isa<VectorType>(I.getType())) {
4001 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4002 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4003 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4004 KnownZero, KnownOne))
4005 return &I;
4006 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004007
Zhou Sheng75b871f2007-01-11 12:24:14 +00004008 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004009 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4010 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004011 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004012 return new ICmpInst(ICI->getInversePredicate(),
4013 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004014
Reid Spencer266e42b2006-12-23 06:05:41 +00004015 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004016 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004017 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4018 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004019 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4020 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004021 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004022 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004023 }
Chris Lattner023a4832004-06-18 06:07:51 +00004024
4025 // ~(~X & Y) --> (X | ~Y)
4026 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4027 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4028 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4029 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004030 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004031 Op0I->getOperand(1)->getName()+".not");
4032 InsertNewInstBefore(NotY, I);
4033 return BinaryOperator::createOr(Op0NotVal, NotY);
4034 }
4035 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004036
Chris Lattner97638592003-07-23 21:37:07 +00004037 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004038 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004039 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004040 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004041 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4042 return BinaryOperator::createSub(
4043 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004044 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004045 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004046 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004047 } else if (Op0I->getOpcode() == Instruction::Or) {
4048 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004049 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004050 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4051 // Anything in both C1 and C2 is known to be zero, remove it from
4052 // NewRHS.
4053 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4054 NewRHS = ConstantExpr::getAnd(NewRHS,
4055 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004056 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004057 I.setOperand(0, Op0I->getOperand(0));
4058 I.setOperand(1, NewRHS);
4059 return &I;
4060 }
Chris Lattner97638592003-07-23 21:37:07 +00004061 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004062 }
Chris Lattner183b3362004-04-09 19:05:30 +00004063
4064 // Try to fold constant and into select arguments.
4065 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004066 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004067 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004068 if (isa<PHINode>(Op0))
4069 if (Instruction *NV = FoldOpIntoPhi(I))
4070 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004071 }
4072
Chris Lattnerbb74e222003-03-10 23:06:50 +00004073 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004074 if (X == Op1)
4075 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004076 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004077
Chris Lattnerbb74e222003-03-10 23:06:50 +00004078 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004079 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004080 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004081
Chris Lattner07418422007-03-18 22:51:34 +00004082
4083 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4084 if (Op1I) {
4085 Value *A, *B;
4086 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4087 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004088 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004089 I.swapOperands();
4090 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004091 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004092 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004093 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004094 }
Chris Lattner07418422007-03-18 22:51:34 +00004095 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4096 if (Op0 == A) // A^(A^B) == B
4097 return ReplaceInstUsesWith(I, B);
4098 else if (Op0 == B) // A^(B^A) == B
4099 return ReplaceInstUsesWith(I, A);
4100 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4101 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004102 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004103 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004104 I.swapOperands(); // Simplified below.
4105 std::swap(Op0, Op1);
4106 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004107 }
Chris Lattner07418422007-03-18 22:51:34 +00004108 }
4109
4110 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4111 if (Op0I) {
4112 Value *A, *B;
4113 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4114 if (A == Op1) // (B|A)^B == (A|B)^B
4115 std::swap(A, B);
4116 if (B == Op1) { // (A|B)^B == A & ~B
4117 Instruction *NotB =
4118 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4119 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004120 }
Chris Lattner07418422007-03-18 22:51:34 +00004121 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4122 if (Op1 == A) // (A^B)^A == B
4123 return ReplaceInstUsesWith(I, B);
4124 else if (Op1 == B) // (B^A)^A == B
4125 return ReplaceInstUsesWith(I, A);
4126 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4127 if (A == Op1) // (A&B)^A -> (B&A)^A
4128 std::swap(A, B);
4129 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004130 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004131 Instruction *N =
4132 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004133 return BinaryOperator::createAnd(N, Op1);
4134 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004135 }
Chris Lattner07418422007-03-18 22:51:34 +00004136 }
4137
4138 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4139 if (Op0I && Op1I && Op0I->isShift() &&
4140 Op0I->getOpcode() == Op1I->getOpcode() &&
4141 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4142 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4143 Instruction *NewOp =
4144 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4145 Op1I->getOperand(0),
4146 Op0I->getName()), I);
4147 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4148 Op1I->getOperand(1));
4149 }
4150
4151 if (Op0I && Op1I) {
4152 Value *A, *B, *C, *D;
4153 // (A & B)^(A | B) -> A ^ B
4154 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4155 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4156 if ((A == C && B == D) || (A == D && B == C))
4157 return BinaryOperator::createXor(A, B);
4158 }
4159 // (A | B)^(A & B) -> A ^ B
4160 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4161 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4162 if ((A == C && B == D) || (A == D && B == C))
4163 return BinaryOperator::createXor(A, B);
4164 }
4165
4166 // (A & B)^(C & D)
4167 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4168 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4169 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4170 // (X & Y)^(X & Y) -> (Y^Z) & X
4171 Value *X = 0, *Y = 0, *Z = 0;
4172 if (A == C)
4173 X = A, Y = B, Z = D;
4174 else if (A == D)
4175 X = A, Y = B, Z = C;
4176 else if (B == C)
4177 X = B, Y = A, Z = D;
4178 else if (B == D)
4179 X = B, Y = A, Z = C;
4180
4181 if (X) {
4182 Instruction *NewOp =
4183 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4184 return BinaryOperator::createAnd(NewOp, X);
4185 }
4186 }
4187 }
4188
Reid Spencer266e42b2006-12-23 06:05:41 +00004189 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4190 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4191 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004192 return R;
4193
Chris Lattner3af10532006-05-05 06:39:07 +00004194 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004195 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004196 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004197 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4198 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004199 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004200 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004201 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4202 I.getType(), TD) &&
4203 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4204 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004205 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4206 Op1C->getOperand(0),
4207 I.getName());
4208 InsertNewInstBefore(NewOp, I);
4209 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4210 }
Chris Lattner3af10532006-05-05 06:39:07 +00004211 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004212
Chris Lattner113f4f42002-06-25 16:13:24 +00004213 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004214}
4215
Chris Lattner6862fbd2004-09-29 17:40:11 +00004216/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4217/// overflowed for this type.
4218static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004219 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004220 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4221
Reid Spencerf4071162007-03-21 23:19:50 +00004222 if (IsSigned)
4223 if (In2->getValue().isNegative())
4224 return Result->getValue().sgt(In1->getValue());
4225 else
4226 return Result->getValue().slt(In1->getValue());
4227 else
4228 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004229}
4230
Chris Lattner0798af32005-01-13 20:14:25 +00004231/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4232/// code necessary to compute the offset from the base pointer (without adding
4233/// in the base pointer). Return the result as a signed integer of intptr size.
4234static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4235 TargetData &TD = IC.getTargetData();
4236 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004237 const Type *IntPtrTy = TD.getIntPtrType();
4238 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004239
4240 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004241 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004242
Chris Lattner0798af32005-01-13 20:14:25 +00004243 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4244 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004245 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004246 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004247 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4248 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004249 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004250 Scale = ConstantExpr::getMul(OpC, Scale);
4251 if (Constant *RC = dyn_cast<Constant>(Result))
4252 Result = ConstantExpr::getAdd(RC, Scale);
4253 else {
4254 // Emit an add instruction.
4255 Result = IC.InsertNewInstBefore(
4256 BinaryOperator::createAdd(Result, Scale,
4257 GEP->getName()+".offs"), I);
4258 }
4259 }
4260 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004261 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004262 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004263 Op->getName()+".c"), I);
4264 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004265 // We'll let instcombine(mul) convert this to a shl if possible.
4266 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4267 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004268
4269 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004270 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004271 GEP->getName()+".offs"), I);
4272 }
4273 }
4274 return Result;
4275}
4276
Reid Spencer266e42b2006-12-23 06:05:41 +00004277/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004278/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004279Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4280 ICmpInst::Predicate Cond,
4281 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004282 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004283
4284 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4285 if (isa<PointerType>(CI->getOperand(0)->getType()))
4286 RHS = CI->getOperand(0);
4287
Chris Lattner0798af32005-01-13 20:14:25 +00004288 Value *PtrBase = GEPLHS->getOperand(0);
4289 if (PtrBase == RHS) {
4290 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004291 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4292 // each index is zero or not.
4293 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004294 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004295 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4296 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004297 bool EmitIt = true;
4298 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4299 if (isa<UndefValue>(C)) // undef index -> undef.
4300 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4301 if (C->isNullValue())
4302 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004303 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4304 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004305 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004306 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004307 ConstantInt::get(Type::Int1Ty,
4308 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004309 }
4310
4311 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004312 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004313 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004314 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4315 if (InVal == 0)
4316 InVal = Comp;
4317 else {
4318 InVal = InsertNewInstBefore(InVal, I);
4319 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004320 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004321 InVal = BinaryOperator::createOr(InVal, Comp);
4322 else // True if all are equal
4323 InVal = BinaryOperator::createAnd(InVal, Comp);
4324 }
4325 }
4326 }
4327
4328 if (InVal)
4329 return InVal;
4330 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004331 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004332 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4333 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004334 }
Chris Lattner0798af32005-01-13 20:14:25 +00004335
Reid Spencer266e42b2006-12-23 06:05:41 +00004336 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004337 // the result to fold to a constant!
4338 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4339 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4340 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004341 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4342 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004343 }
4344 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004345 // If the base pointers are different, but the indices are the same, just
4346 // compare the base pointer.
4347 if (PtrBase != GEPRHS->getOperand(0)) {
4348 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004349 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004350 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004351 if (IndicesTheSame)
4352 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4353 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4354 IndicesTheSame = false;
4355 break;
4356 }
4357
4358 // If all indices are the same, just compare the base pointers.
4359 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004360 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4361 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004362
4363 // Otherwise, the base pointers are different and the indices are
4364 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004365 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004366 }
Chris Lattner0798af32005-01-13 20:14:25 +00004367
Chris Lattner81e84172005-01-13 22:25:21 +00004368 // If one of the GEPs has all zero indices, recurse.
4369 bool AllZeros = true;
4370 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4371 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4372 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4373 AllZeros = false;
4374 break;
4375 }
4376 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004377 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4378 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004379
4380 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004381 AllZeros = true;
4382 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4383 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4384 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4385 AllZeros = false;
4386 break;
4387 }
4388 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004389 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004390
Chris Lattner4fa89822005-01-14 00:20:05 +00004391 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4392 // If the GEPs only differ by one index, compare it.
4393 unsigned NumDifferences = 0; // Keep track of # differences.
4394 unsigned DiffOperand = 0; // The operand that differs.
4395 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4396 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004397 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4398 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004399 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004400 NumDifferences = 2;
4401 break;
4402 } else {
4403 if (NumDifferences++) break;
4404 DiffOperand = i;
4405 }
4406 }
4407
4408 if (NumDifferences == 0) // SAME GEP?
4409 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004410 ConstantInt::get(Type::Int1Ty,
4411 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004412 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004413 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4414 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004415 // Make sure we do a signed comparison here.
4416 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004417 }
4418 }
4419
Reid Spencer266e42b2006-12-23 06:05:41 +00004420 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004421 // the result to fold to a constant!
4422 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4423 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4424 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4425 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4426 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004427 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004428 }
4429 }
4430 return 0;
4431}
4432
Reid Spencer266e42b2006-12-23 06:05:41 +00004433Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4434 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004436
Chris Lattner6ee923f2007-01-14 19:42:17 +00004437 // Fold trivial predicates.
4438 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4439 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4440 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4441 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4442
4443 // Simplify 'fcmp pred X, X'
4444 if (Op0 == Op1) {
4445 switch (I.getPredicate()) {
4446 default: assert(0 && "Unknown predicate!");
4447 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4448 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4449 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4450 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4451 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4452 case FCmpInst::FCMP_OLT: // True if ordered and less than
4453 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4454 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4455
4456 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4457 case FCmpInst::FCMP_ULT: // True if unordered or less than
4458 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4459 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4460 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4461 I.setPredicate(FCmpInst::FCMP_UNO);
4462 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4463 return &I;
4464
4465 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4466 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4467 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4468 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4469 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4470 I.setPredicate(FCmpInst::FCMP_ORD);
4471 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4472 return &I;
4473 }
4474 }
4475
Reid Spencer266e42b2006-12-23 06:05:41 +00004476 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004477 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004478
Reid Spencer266e42b2006-12-23 06:05:41 +00004479 // Handle fcmp with constant RHS
4480 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4481 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4482 switch (LHSI->getOpcode()) {
4483 case Instruction::PHI:
4484 if (Instruction *NV = FoldOpIntoPhi(I))
4485 return NV;
4486 break;
4487 case Instruction::Select:
4488 // If either operand of the select is a constant, we can fold the
4489 // comparison into the select arms, which will cause one to be
4490 // constant folded and the select turned into a bitwise or.
4491 Value *Op1 = 0, *Op2 = 0;
4492 if (LHSI->hasOneUse()) {
4493 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4494 // Fold the known value into the constant operand.
4495 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4496 // Insert a new FCmp of the other select operand.
4497 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4498 LHSI->getOperand(2), RHSC,
4499 I.getName()), I);
4500 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4501 // Fold the known value into the constant operand.
4502 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4503 // Insert a new FCmp of the other select operand.
4504 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4505 LHSI->getOperand(1), RHSC,
4506 I.getName()), I);
4507 }
4508 }
4509
4510 if (Op1)
4511 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4512 break;
4513 }
4514 }
4515
4516 return Changed ? &I : 0;
4517}
4518
4519Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4520 bool Changed = SimplifyCompare(I);
4521 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4522 const Type *Ty = Op0->getType();
4523
4524 // icmp X, X
4525 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004526 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4527 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004528
4529 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004530 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004531
4532 // icmp of GlobalValues can never equal each other as long as they aren't
4533 // external weak linkage type.
4534 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4535 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4536 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004537 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4538 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004539
4540 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004541 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004542 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4543 isa<ConstantPointerNull>(Op0)) &&
4544 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004545 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004546 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4547 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004548
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004550 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004551 switch (I.getPredicate()) {
4552 default: assert(0 && "Invalid icmp instruction!");
4553 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004554 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004555 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004556 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004557 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004559 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004560
Reid Spencer266e42b2006-12-23 06:05:41 +00004561 case ICmpInst::ICMP_UGT:
4562 case ICmpInst::ICMP_SGT:
4563 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004564 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 case ICmpInst::ICMP_ULT:
4566 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004567 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4568 InsertNewInstBefore(Not, I);
4569 return BinaryOperator::createAnd(Not, Op1);
4570 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004571 case ICmpInst::ICMP_UGE:
4572 case ICmpInst::ICMP_SGE:
4573 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004574 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004575 case ICmpInst::ICMP_ULE:
4576 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004577 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4578 InsertNewInstBefore(Not, I);
4579 return BinaryOperator::createOr(Not, Op1);
4580 }
4581 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004582 }
4583
Chris Lattner2dd01742004-06-09 04:24:29 +00004584 // See if we are doing a comparison between a constant and an instruction that
4585 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004586 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004587 switch (I.getPredicate()) {
4588 default: break;
4589 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4590 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004592 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4593 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4594 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4595 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4596 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004597
Reid Spencer266e42b2006-12-23 06:05:41 +00004598 case ICmpInst::ICMP_SLT:
4599 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004600 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004601 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4602 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4603 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4604 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4605 break;
4606
4607 case ICmpInst::ICMP_UGT:
4608 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004609 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004610 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4611 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4612 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4613 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4614 break;
4615
4616 case ICmpInst::ICMP_SGT:
4617 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004618 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004619 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4620 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4621 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4622 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4623 break;
4624
4625 case ICmpInst::ICMP_ULE:
4626 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004627 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004628 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4629 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4630 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4631 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4632 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004633
Reid Spencer266e42b2006-12-23 06:05:41 +00004634 case ICmpInst::ICMP_SLE:
4635 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004636 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004637 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4638 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4639 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4640 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4641 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004642
Reid Spencer266e42b2006-12-23 06:05:41 +00004643 case ICmpInst::ICMP_UGE:
4644 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004645 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004646 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4647 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4648 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4649 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4650 break;
4651
4652 case ICmpInst::ICMP_SGE:
4653 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004654 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004655 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4656 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4657 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4658 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4659 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004660 }
4661
Reid Spencer266e42b2006-12-23 06:05:41 +00004662 // If we still have a icmp le or icmp ge instruction, turn it into the
4663 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004664 // already been handled above, this requires little checking.
4665 //
Reid Spencer624766f2007-03-25 19:55:33 +00004666 switch (I.getPredicate()) {
4667 default: break;
4668 case ICmpInst::ICMP_ULE:
4669 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4670 case ICmpInst::ICMP_SLE:
4671 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4672 case ICmpInst::ICMP_UGE:
4673 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4674 case ICmpInst::ICMP_SGE:
4675 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4676 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004677
4678 // See if we can fold the comparison based on bits known to be zero or one
4679 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004680 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4681 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4682 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004683 KnownZero, KnownOne, 0))
4684 return &I;
4685
4686 // Given the known and unknown bits, compute a range that the LHS could be
4687 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004688 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004689 // Compute the Min, Max and RHS values based on the known bits. For the
4690 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004691 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004692 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004693 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4694 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004695 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004696 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4697 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004698 }
4699 switch (I.getPredicate()) { // LE/GE have been folded already.
4700 default: assert(0 && "Unknown icmp opcode!");
4701 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004702 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004703 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004704 break;
4705 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004706 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004707 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004708 break;
4709 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004710 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004712 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004714 break;
4715 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004716 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004717 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004718 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004719 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004720 break;
4721 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004722 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004723 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004724 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004725 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004726 break;
4727 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004728 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004729 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004730 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004731 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004732 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004733 }
4734 }
4735
Reid Spencer266e42b2006-12-23 06:05:41 +00004736 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004737 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004738 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004739 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004740 switch (LHSI->getOpcode()) {
4741 case Instruction::And:
4742 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4743 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004744 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4745
Reid Spencer266e42b2006-12-23 06:05:41 +00004746 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004747 // and/compare to be the input width without changing the value
4748 // produced, eliminating a cast.
4749 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4750 // We can do this transformation if either the AND constant does not
4751 // have its sign bit set or if it is an equality comparison.
4752 // Extending a relational comparison when we're checking the sign
4753 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004754 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004755 (I.isEquality() || AndCST->getValue().isPositive() &&
4756 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004757 ConstantInt *NewCST;
4758 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004759 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4760 uint32_t BitWidth = cast<IntegerType>(
4761 Cast->getOperand(0)->getType())->getBitWidth();
4762 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4763 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00004764 Instruction *NewAnd =
4765 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4766 LHSI->getName());
4767 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004768 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004769 }
4770 }
4771
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004772 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4773 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4774 // happens a LOT in code produced by the C front-end, for bitfield
4775 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004776 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4777 if (Shift && !Shift->isShift())
4778 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004779
Reid Spencere0fc4df2006-10-20 07:07:24 +00004780 ConstantInt *ShAmt;
4781 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004782 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4783 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004784
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004785 // We can fold this as long as we can't shift unknown bits
4786 // into the mask. This can only happen with signed shift
4787 // rights, as they sign-extend.
4788 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004789 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004790 if (!CanFold) {
4791 // To test for the bad case of the signed shr, see if any
4792 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004793 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004794 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4795
Reid Spencer2341c222007-02-02 02:16:23 +00004796 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004798 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4799 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004800 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4801 CanFold = true;
4802 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004803
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004804 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004805 Constant *NewCst;
4806 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004807 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004808 else
4809 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004810
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004811 // Check to see if we are shifting out any of the bits being
4812 // compared.
4813 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4814 // If we shifted bits out, the fold is not going to work out.
4815 // As a special case, check to see if this means that the
4816 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004817 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004818 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004819 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004820 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004821 } else {
4822 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004823 Constant *NewAndCST;
4824 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004825 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004826 else
4827 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4828 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004829 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004830 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004831 AddUsesToWorkList(I);
4832 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004833 }
4834 }
Chris Lattner35167c32004-06-09 07:59:58 +00004835 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004836
4837 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4838 // preferable because it allows the C<<Y expression to be hoisted out
4839 // of a loop if Y is invariant and X is not.
4840 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004841 I.isEquality() && !Shift->isArithmeticShift() &&
4842 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004843 // Compute C << Y.
4844 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004845 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004846 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004847 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004848 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004849 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004850 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004851 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004852 }
4853 InsertNewInstBefore(cast<Instruction>(NS), I);
4854
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004855 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004856 Instruction *NewAnd = BinaryOperator::createAnd(
4857 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004858 InsertNewInstBefore(NewAnd, I);
4859
4860 I.setOperand(0, NewAnd);
4861 return &I;
4862 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004863 }
4864 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004865
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004867 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004868 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004869 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4870
4871 // Check that the shift amount is in range. If not, don't perform
4872 // undefined shifts. When the shift is visited it will be
4873 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004874 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004875 break;
4876
Chris Lattner272d5ca2004-09-28 18:22:15 +00004877 // If we are comparing against bits always shifted out, the
4878 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004879 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004880 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004881 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004882 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004883 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004884 return ReplaceInstUsesWith(I, Cst);
4885 }
4886
4887 if (LHSI->hasOneUse()) {
4888 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004889 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Reid Spencer52830322007-03-25 21:11:44 +00004890 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4891 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004892
Chris Lattner272d5ca2004-09-28 18:22:15 +00004893 Instruction *AndI =
4894 BinaryOperator::createAnd(LHSI->getOperand(0),
4895 Mask, LHSI->getName()+".mask");
4896 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004897 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004898 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004899 }
4900 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004901 }
4902 break;
4903
Reid Spencer266e42b2006-12-23 06:05:41 +00004904 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004905 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004906 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004907 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004908 // Check that the shift amount is in range. If not, don't perform
4909 // undefined shifts. When the shift is visited it will be
4910 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004911 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004912 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004913 break;
4914
Chris Lattner1023b872004-09-27 16:18:50 +00004915 // If we are comparing against bits always shifted out, the
4916 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004917 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004918 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004919 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4920 ShAmt);
4921 else
4922 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4923 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004924
Chris Lattner1023b872004-09-27 16:18:50 +00004925 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004926 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004927 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004928 return ReplaceInstUsesWith(I, Cst);
4929 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004930
Chris Lattner1023b872004-09-27 16:18:50 +00004931 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004932 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004933
Chris Lattner1023b872004-09-27 16:18:50 +00004934 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004935 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4936 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004937
Chris Lattner1023b872004-09-27 16:18:50 +00004938 Instruction *AndI =
4939 BinaryOperator::createAnd(LHSI->getOperand(0),
4940 Mask, LHSI->getName()+".mask");
4941 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004943 ConstantExpr::getShl(CI, ShAmt));
4944 }
Chris Lattner1023b872004-09-27 16:18:50 +00004945 }
4946 }
4947 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004948
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004949 case Instruction::SDiv:
4950 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004951 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004952 // Fold this div into the comparison, producing a range check.
4953 // Determine, based on the divide type, what the range is being
4954 // checked. If there is an overflow on the low or high side, remember
4955 // it, otherwise compute the range [low, hi) bounding the new value.
4956 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004957 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004958 // FIXME: If the operand types don't match the type of the divide
4959 // then don't attempt this transform. The code below doesn't have the
4960 // logic to deal with a signed divide and an unsigned compare (and
4961 // vice versa). This is because (x /s C1) <s C2 produces different
4962 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4963 // (x /u C1) <u C2. Simply casting the operands and result won't
4964 // work. :( The if statement below tests that condition and bails
4965 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4967 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004968 break;
Reid Spencerf4071162007-03-21 23:19:50 +00004969 if (DivRHS->isZero())
4970 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004971
4972 // Initialize the variables that will indicate the nature of the
4973 // range check.
4974 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004975 ConstantInt *LoBound = 0, *HiBound = 0;
4976
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004977 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4978 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4979 // C2 (CI). By solving for X we can turn this into a range check
4980 // instead of computing a divide.
4981 ConstantInt *Prod =
4982 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004983
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004984 // Determine if the product overflows by seeing if the product is
4985 // not equal to the divide. Make sure we do the same kind of divide
4986 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00004987 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4988 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004989
Reid Spencer266e42b2006-12-23 06:05:41 +00004990 // Get the ICmp opcode
4991 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004992
Reid Spencerf4071162007-03-21 23:19:50 +00004993 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004994 LoBound = Prod;
4995 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00004996 HiOverflow = ProdOV ||
4997 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00004998 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004999 if (CI->isNullValue()) { // (X / pos) op 0
5000 // Can't overflow.
5001 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5002 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00005003 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005004 LoBound = Prod;
5005 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00005006 HiOverflow = ProdOV ||
5007 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005008 } else { // (X / pos) op neg
5009 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5010 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00005011 cast<ConstantInt>(DivRHSH), true);
5012 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005013 HiOverflow = ProdOV;
5014 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005015 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005016 if (CI->isNullValue()) { // (X / neg) op 0
5017 LoBound = AddOne(DivRHS);
5018 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005019 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005020 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00005021 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005022 HiOverflow = LoOverflow = ProdOV;
5023 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005024 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5025 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005026 HiBound = AddOne(Prod);
5027 } else { // (X / neg) op neg
5028 LoBound = Prod;
5029 LoOverflow = HiOverflow = ProdOV;
5030 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5031 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005032
Chris Lattnera92af962004-10-11 19:40:04 +00005033 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005034 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005035 }
5036
5037 if (LoBound) {
5038 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 switch (predicate) {
5040 default: assert(0 && "Unhandled icmp opcode!");
5041 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005042 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005043 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005044 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5046 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005047 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5049 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005050 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005051 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5052 true, I);
5053 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005054 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005055 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005056 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5058 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005059 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005060 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5061 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005062 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005063 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5064 false, I);
5065 case ICmpInst::ICMP_ULT:
5066 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005067 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005068 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005069 return new ICmpInst(predicate, X, LoBound);
5070 case ICmpInst::ICMP_UGT:
5071 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005072 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005074 if (predicate == ICmpInst::ICMP_UGT)
5075 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5076 else
5077 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005078 }
5079 }
5080 }
5081 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005082 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005083
Reid Spencer266e42b2006-12-23 06:05:41 +00005084 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005085 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005086 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005087
Reid Spencere0fc4df2006-10-20 07:07:24 +00005088 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5089 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5091 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005092 case Instruction::SRem:
5093 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005094 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005095 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005096 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5097 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005098 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5099 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005100 return new ICmpInst(I.getPredicate(), NewRem,
5101 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005102 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005103 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005104 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005105 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005106 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5107 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005108 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005109 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5110 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005111 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005112 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5113 // efficiently invertible, or if the add has just this one use.
5114 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005115
Chris Lattnerc992add2003-08-13 05:33:12 +00005116 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005117 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005118 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005119 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005120 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005121 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005122 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005123 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005124 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005125 }
5126 }
5127 break;
5128 case Instruction::Xor:
5129 // For the xor case, we can xor two constants together, eliminating
5130 // the explicit xor.
5131 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005132 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5133 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005134
5135 // FALLTHROUGH
5136 case Instruction::Sub:
5137 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005138 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005139 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5140 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005141 break;
5142
5143 case Instruction::Or:
5144 // If bits are being or'd in that are not present in the constant we
5145 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005146 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005147 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005148 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005149 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5150 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005151 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005152 break;
5153
5154 case Instruction::And:
5155 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005156 // If bits are being compared against that are and'd out, then the
5157 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005158 if (!ConstantExpr::getAnd(CI,
5159 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005160 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5161 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005162
Chris Lattner35167c32004-06-09 07:59:58 +00005163 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005164 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005165 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5166 ICmpInst::ICMP_NE, Op0,
5167 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005168
Reid Spencer266e42b2006-12-23 06:05:41 +00005169 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005170 if (isSignBit(BOC)) {
5171 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005172 Constant *Zero = Constant::getNullValue(X->getType());
5173 ICmpInst::Predicate pred = isICMP_NE ?
5174 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5175 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005176 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005177
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005178 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005179 if (CI->isNullValue() && isHighOnes(BOC)) {
5180 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005181 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005182 ICmpInst::Predicate pred = isICMP_NE ?
5183 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5184 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005185 }
5186
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005187 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005188 default: break;
5189 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005190 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5191 // Handle set{eq|ne} <intrinsic>, intcst.
5192 switch (II->getIntrinsicID()) {
5193 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005194 case Intrinsic::bswap_i16:
5195 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005196 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005197 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005198 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005199 ByteSwap_16(CI->getZExtValue())));
5200 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005201 case Intrinsic::bswap_i32:
5202 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005203 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005204 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005205 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005206 ByteSwap_32(CI->getZExtValue())));
5207 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005208 case Intrinsic::bswap_i64:
5209 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005210 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005211 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005212 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005213 ByteSwap_64(CI->getZExtValue())));
5214 return &I;
5215 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005216 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005217 } else { // Not a ICMP_EQ/ICMP_NE
5218 // If the LHS is a cast from an integral value of the same size, then
5219 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005220 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5221 Value *CastOp = Cast->getOperand(0);
5222 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005223 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005224 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005225 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005226 // If this is an unsigned comparison, try to make the comparison use
5227 // smaller constant values.
5228 switch (I.getPredicate()) {
5229 default: break;
5230 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5231 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005232 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005233 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005234 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005235 break;
5236 }
5237 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5238 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005239 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005240 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5241 Constant::getNullValue(SrcTy));
5242 break;
5243 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005244 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005245
Chris Lattner2b55ea32004-02-23 07:16:20 +00005246 }
5247 }
Chris Lattnere967b342003-06-04 05:10:11 +00005248 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005249 }
5250
Reid Spencer266e42b2006-12-23 06:05:41 +00005251 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005252 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5253 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5254 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005255 case Instruction::GetElementPtr:
5256 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005257 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005258 bool isAllZeros = true;
5259 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5260 if (!isa<Constant>(LHSI->getOperand(i)) ||
5261 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5262 isAllZeros = false;
5263 break;
5264 }
5265 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005266 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005267 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5268 }
5269 break;
5270
Chris Lattner77c32c32005-04-23 15:31:55 +00005271 case Instruction::PHI:
5272 if (Instruction *NV = FoldOpIntoPhi(I))
5273 return NV;
5274 break;
5275 case Instruction::Select:
5276 // If either operand of the select is a constant, we can fold the
5277 // comparison into the select arms, which will cause one to be
5278 // constant folded and the select turned into a bitwise or.
5279 Value *Op1 = 0, *Op2 = 0;
5280 if (LHSI->hasOneUse()) {
5281 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5282 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005283 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5284 // Insert a new ICmp of the other select operand.
5285 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5286 LHSI->getOperand(2), RHSC,
5287 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005288 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5289 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005290 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5291 // Insert a new ICmp of the other select operand.
5292 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5293 LHSI->getOperand(1), RHSC,
5294 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005295 }
5296 }
Jeff Cohen82639852005-04-23 21:38:35 +00005297
Chris Lattner77c32c32005-04-23 15:31:55 +00005298 if (Op1)
5299 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5300 break;
5301 }
5302 }
5303
Reid Spencer266e42b2006-12-23 06:05:41 +00005304 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005305 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005306 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005307 return NI;
5308 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005309 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5310 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005311 return NI;
5312
Reid Spencer266e42b2006-12-23 06:05:41 +00005313 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005314 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5315 // now.
5316 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5317 if (isa<PointerType>(Op0->getType()) &&
5318 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005319 // We keep moving the cast from the left operand over to the right
5320 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005321 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005322
Chris Lattner64d87b02007-01-06 01:45:59 +00005323 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5324 // so eliminate it as well.
5325 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5326 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005327
Chris Lattner16930792003-11-03 04:25:02 +00005328 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005329 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005330 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005331 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005332 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005333 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005334 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005335 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005336 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005337 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005338 }
5339
5340 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005341 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005342 // This comes up when you have code like
5343 // int X = A < B;
5344 // if (X) ...
5345 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005346 // with a constant or another cast from the same type.
5347 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005348 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005349 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005350 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005351
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005352 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005353 Value *A, *B, *C, *D;
5354 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5355 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5356 Value *OtherVal = A == Op1 ? B : A;
5357 return new ICmpInst(I.getPredicate(), OtherVal,
5358 Constant::getNullValue(A->getType()));
5359 }
5360
5361 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5362 // A^c1 == C^c2 --> A == C^(c1^c2)
5363 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5364 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5365 if (Op1->hasOneUse()) {
5366 Constant *NC = ConstantExpr::getXor(C1, C2);
5367 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5368 return new ICmpInst(I.getPredicate(), A,
5369 InsertNewInstBefore(Xor, I));
5370 }
5371
5372 // A^B == A^D -> B == D
5373 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5374 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5375 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5376 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5377 }
5378 }
5379
5380 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5381 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005382 // A == (A^B) -> B == 0
5383 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005384 return new ICmpInst(I.getPredicate(), OtherVal,
5385 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005386 }
5387 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005388 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005389 return new ICmpInst(I.getPredicate(), B,
5390 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005391 }
5392 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005393 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005394 return new ICmpInst(I.getPredicate(), B,
5395 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005396 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005397
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005398 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5399 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5400 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5401 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5402 Value *X = 0, *Y = 0, *Z = 0;
5403
5404 if (A == C) {
5405 X = B; Y = D; Z = A;
5406 } else if (A == D) {
5407 X = B; Y = C; Z = A;
5408 } else if (B == C) {
5409 X = A; Y = D; Z = B;
5410 } else if (B == D) {
5411 X = A; Y = C; Z = B;
5412 }
5413
5414 if (X) { // Build (X^Y) & Z
5415 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5416 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5417 I.setOperand(0, Op1);
5418 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5419 return &I;
5420 }
5421 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005422 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005423 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005424}
5425
Reid Spencer266e42b2006-12-23 06:05:41 +00005426// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005427// We only handle extending casts so far.
5428//
Reid Spencer266e42b2006-12-23 06:05:41 +00005429Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5430 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005431 Value *LHSCIOp = LHSCI->getOperand(0);
5432 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005433 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005434 Value *RHSCIOp;
5435
Reid Spencer266e42b2006-12-23 06:05:41 +00005436 // We only handle extension cast instructions, so far. Enforce this.
5437 if (LHSCI->getOpcode() != Instruction::ZExt &&
5438 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005439 return 0;
5440
Reid Spencer266e42b2006-12-23 06:05:41 +00005441 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5442 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005443
Reid Spencer266e42b2006-12-23 06:05:41 +00005444 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005445 // Not an extension from the same type?
5446 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005447 if (RHSCIOp->getType() != LHSCIOp->getType())
5448 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005449
5450 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5451 // and the other is a zext), then we can't handle this.
5452 if (CI->getOpcode() != LHSCI->getOpcode())
5453 return 0;
5454
5455 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5456 // then we can't handle this.
5457 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5458 return 0;
5459
5460 // Okay, just insert a compare of the reduced operands now!
5461 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005462 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005463
Reid Spencer266e42b2006-12-23 06:05:41 +00005464 // If we aren't dealing with a constant on the RHS, exit early
5465 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5466 if (!CI)
5467 return 0;
5468
5469 // Compute the constant that would happen if we truncated to SrcTy then
5470 // reextended to DestTy.
5471 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5472 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5473
5474 // If the re-extended constant didn't change...
5475 if (Res2 == CI) {
5476 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5477 // For example, we might have:
5478 // %A = sext short %X to uint
5479 // %B = icmp ugt uint %A, 1330
5480 // It is incorrect to transform this into
5481 // %B = icmp ugt short %X, 1330
5482 // because %A may have negative value.
5483 //
5484 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5485 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005486 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005487 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5488 else
5489 return 0;
5490 }
5491
5492 // The re-extended constant changed so the constant cannot be represented
5493 // in the shorter type. Consequently, we cannot emit a simple comparison.
5494
5495 // First, handle some easy cases. We know the result cannot be equal at this
5496 // point so handle the ICI.isEquality() cases
5497 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005498 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005499 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005500 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005501
5502 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5503 // should have been folded away previously and not enter in here.
5504 Value *Result;
5505 if (isSignedCmp) {
5506 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005507 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005508 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005509 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005510 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005511 } else {
5512 // We're performing an unsigned comparison.
5513 if (isSignedExt) {
5514 // We're performing an unsigned comp with a sign extended value.
5515 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005516 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005517 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5518 NegOne, ICI.getName()), ICI);
5519 } else {
5520 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005521 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005522 }
5523 }
5524
5525 // Finally, return the value computed.
5526 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5527 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5528 return ReplaceInstUsesWith(ICI, Result);
5529 } else {
5530 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5531 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5532 "ICmp should be folded!");
5533 if (Constant *CI = dyn_cast<Constant>(Result))
5534 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5535 else
5536 return BinaryOperator::createNot(Result);
5537 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005538}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005539
Reid Spencer2341c222007-02-02 02:16:23 +00005540Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5541 return commonShiftTransforms(I);
5542}
5543
5544Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5545 return commonShiftTransforms(I);
5546}
5547
5548Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5549 return commonShiftTransforms(I);
5550}
5551
5552Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5553 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005555
5556 // shl X, 0 == X and shr X, 0 == X
5557 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005558 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005559 Op0 == Constant::getNullValue(Op0->getType()))
5560 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005561
Reid Spencer266e42b2006-12-23 06:05:41 +00005562 if (isa<UndefValue>(Op0)) {
5563 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005564 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005565 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5567 }
5568 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005569 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5570 return ReplaceInstUsesWith(I, Op0);
5571 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005572 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005573 }
5574
Chris Lattnerd4dee402006-11-10 23:38:52 +00005575 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5576 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005577 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005578 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005579 return ReplaceInstUsesWith(I, CSI);
5580
Chris Lattner183b3362004-04-09 19:05:30 +00005581 // Try to fold constant and into select arguments.
5582 if (isa<Constant>(Op0))
5583 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005584 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005585 return R;
5586
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005587 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005588 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005589 if (MaskedValueIsZero(Op0,
5590 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005591 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005592 }
5593 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005594
Reid Spencere0fc4df2006-10-20 07:07:24 +00005595 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005596 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5597 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005598 return 0;
5599}
5600
Reid Spencere0fc4df2006-10-20 07:07:24 +00005601Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005602 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005603 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005604
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005605 // See if we can simplify any instructions used by the instruction whose sole
5606 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005607 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5608 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5609 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005610 KnownZero, KnownOne))
5611 return &I;
5612
Chris Lattner14553932006-01-06 07:12:35 +00005613 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5614 // of a signed value.
5615 //
Reid Spencer6274c722007-03-23 18:46:34 +00005616 if (Op1->getZExtValue() >= TypeBits) { // shift amount always <= 32 bits
Chris Lattnerd5fea612007-02-02 05:29:55 +00005617 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005618 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5619 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005620 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005621 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005622 }
Chris Lattner14553932006-01-06 07:12:35 +00005623 }
5624
5625 // ((X*C1) << C2) == (X * (C1 << C2))
5626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5627 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5628 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5629 return BinaryOperator::createMul(BO->getOperand(0),
5630 ConstantExpr::getShl(BOOp, Op1));
5631
5632 // Try to fold constant and into select arguments.
5633 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5634 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5635 return R;
5636 if (isa<PHINode>(Op0))
5637 if (Instruction *NV = FoldOpIntoPhi(I))
5638 return NV;
5639
5640 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005641 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5642 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5643 Value *V1, *V2;
5644 ConstantInt *CC;
5645 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005646 default: break;
5647 case Instruction::Add:
5648 case Instruction::And:
5649 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005650 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005651 // These operators commute.
5652 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005653 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5654 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005655 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005656 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005657 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005658 Op0BO->getName());
5659 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005660 Instruction *X =
5661 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5662 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005663 InsertNewInstBefore(X, I); // (X + (Y << C))
5664 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005665 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005666 return BinaryOperator::createAnd(X, C2);
5667 }
Chris Lattner14553932006-01-06 07:12:35 +00005668
Chris Lattner797dee72005-09-18 06:30:59 +00005669 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005670 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005671 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005672 match(Op0BOOp1,
5673 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005674 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5675 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005676 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005677 Op0BO->getOperand(0), Op1,
5678 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005679 InsertNewInstBefore(YS, I); // (Y << C)
5680 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005681 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005682 V1->getName()+".mask");
5683 InsertNewInstBefore(XM, I); // X & (CC << C)
5684
5685 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5686 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005687 }
Chris Lattner14553932006-01-06 07:12:35 +00005688
Reid Spencer2f34b982007-02-02 14:41:37 +00005689 // FALL THROUGH.
5690 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005691 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005692 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5693 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005694 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005695 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005696 Op0BO->getOperand(1), Op1,
5697 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005698 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005699 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005700 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005701 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005702 InsertNewInstBefore(X, I); // (X + (Y << C))
5703 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005704 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005705 return BinaryOperator::createAnd(X, C2);
5706 }
Chris Lattner14553932006-01-06 07:12:35 +00005707
Chris Lattner1df0e982006-05-31 21:14:00 +00005708 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005709 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5710 match(Op0BO->getOperand(0),
5711 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005712 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005713 cast<BinaryOperator>(Op0BO->getOperand(0))
5714 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005715 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005716 Op0BO->getOperand(1), Op1,
5717 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005718 InsertNewInstBefore(YS, I); // (Y << C)
5719 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005720 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005721 V1->getName()+".mask");
5722 InsertNewInstBefore(XM, I); // X & (CC << C)
5723
Chris Lattner1df0e982006-05-31 21:14:00 +00005724 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005725 }
Chris Lattner14553932006-01-06 07:12:35 +00005726
Chris Lattner27cb9db2005-09-18 05:12:10 +00005727 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005728 }
Chris Lattner14553932006-01-06 07:12:35 +00005729 }
5730
5731
5732 // If the operand is an bitwise operator with a constant RHS, and the
5733 // shift is the only use, we can pull it out of the shift.
5734 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5735 bool isValid = true; // Valid only for And, Or, Xor
5736 bool highBitSet = false; // Transform if high bit of constant set?
5737
5738 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005739 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005740 case Instruction::Add:
5741 isValid = isLeftShift;
5742 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005743 case Instruction::Or:
5744 case Instruction::Xor:
5745 highBitSet = false;
5746 break;
5747 case Instruction::And:
5748 highBitSet = true;
5749 break;
Chris Lattner14553932006-01-06 07:12:35 +00005750 }
5751
5752 // If this is a signed shift right, and the high bit is modified
5753 // by the logical operation, do not perform the transformation.
5754 // The highBitSet boolean indicates the value of the high bit of
5755 // the constant which would cause it to be modified for this
5756 // operation.
5757 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005758 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005759 isValid = ((Op0C->getValue() & APInt::getSignBit(TypeBits)) != 0) ==
5760 highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005761 }
5762
5763 if (isValid) {
5764 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5765
5766 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005767 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005768 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005769 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005770
5771 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5772 NewRHS);
5773 }
5774 }
5775 }
5776 }
5777
Chris Lattnereb372a02006-01-06 07:52:12 +00005778 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005779 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5780 if (ShiftOp && !ShiftOp->isShift())
5781 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005782
Reid Spencere0fc4df2006-10-20 07:07:24 +00005783 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005784 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005785 // These shift amounts are always <= 32 bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005786 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5787 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005788 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5789 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5790 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005791
Chris Lattner3e009e82007-02-05 00:57:54 +00005792 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005793 if (AmtSum > TypeBits)
5794 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005795
5796 const IntegerType *Ty = cast<IntegerType>(I.getType());
5797
5798 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005799 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005800 return BinaryOperator::create(I.getOpcode(), X,
5801 ConstantInt::get(Ty, AmtSum));
5802 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5803 I.getOpcode() == Instruction::AShr) {
5804 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5805 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5806 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5807 I.getOpcode() == Instruction::LShr) {
5808 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5809 Instruction *Shift =
5810 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5811 InsertNewInstBefore(Shift, I);
5812
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005813 APInt Mask(Ty->getMask().lshr(ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005814 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005815 }
5816
Chris Lattner3e009e82007-02-05 00:57:54 +00005817 // Okay, if we get here, one shift must be left, and the other shift must be
5818 // right. See if the amounts are equal.
5819 if (ShiftAmt1 == ShiftAmt2) {
5820 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5821 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005822 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005823 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005824 }
5825 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5826 if (I.getOpcode() == Instruction::LShr) {
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00005827 APInt Mask(Ty->getMask().lshr(ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005828 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005829 }
5830 // We can simplify ((X << C) >>s C) into a trunc + sext.
5831 // NOTE: we could do this for any C, but that would make 'unusual' integer
5832 // types. For now, just stick to ones well-supported by the code
5833 // generators.
5834 const Type *SExtType = 0;
5835 switch (Ty->getBitWidth() - ShiftAmt1) {
Reid Spencer6274c722007-03-23 18:46:34 +00005836 case 1 : SExtType = Type::Int1Ty; break;
5837 case 8 : SExtType = Type::Int8Ty; break;
5838 case 16 : SExtType = Type::Int16Ty; break;
5839 case 32 : SExtType = Type::Int32Ty; break;
5840 case 64 : SExtType = Type::Int64Ty; break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005841 default: break;
5842 }
5843 if (SExtType) {
5844 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5845 InsertNewInstBefore(NewTrunc, I);
5846 return new SExtInst(NewTrunc, Ty);
5847 }
5848 // Otherwise, we can't handle it yet.
5849 } else if (ShiftAmt1 < ShiftAmt2) {
5850 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005851
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005852 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005853 if (I.getOpcode() == Instruction::Shl) {
5854 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5855 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005856 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005857 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005858 InsertNewInstBefore(Shift, I);
5859
Reid Spencer52830322007-03-25 21:11:44 +00005860 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5861 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005862 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005863
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005864 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005865 if (I.getOpcode() == Instruction::LShr) {
5866 assert(ShiftOp->getOpcode() == Instruction::Shl);
5867 Instruction *Shift =
5868 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5869 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005870
Reid Spencer769a5a82007-03-26 17:18:58 +00005871 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005872 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005873 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005874
5875 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5876 } else {
5877 assert(ShiftAmt2 < ShiftAmt1);
5878 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5879
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005880 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005881 if (I.getOpcode() == Instruction::Shl) {
5882 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5883 ShiftOp->getOpcode() == Instruction::AShr);
5884 Instruction *Shift =
5885 BinaryOperator::create(ShiftOp->getOpcode(), X,
5886 ConstantInt::get(Ty, ShiftDiff));
5887 InsertNewInstBefore(Shift, I);
5888
Reid Spencer52830322007-03-25 21:11:44 +00005889 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005890 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005891 }
5892
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005893 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005894 if (I.getOpcode() == Instruction::LShr) {
5895 assert(ShiftOp->getOpcode() == Instruction::Shl);
5896 Instruction *Shift =
5897 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5898 InsertNewInstBefore(Shift, I);
5899
Reid Spencer441486c2007-03-26 23:45:51 +00005900 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005901 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005902 }
5903
5904 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005905 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005906 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005907 return 0;
5908}
5909
Chris Lattner48a44f72002-05-02 17:06:02 +00005910
Chris Lattner8f663e82005-10-29 04:36:15 +00005911/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5912/// expression. If so, decompose it, returning some value X, such that Val is
5913/// X*Scale+Offset.
5914///
5915static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5916 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005917 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005918 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005919 Offset = CI->getZExtValue();
5920 Scale = 1;
5921 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005922 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5923 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005924 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005925 if (I->getOpcode() == Instruction::Shl) {
5926 // This is a value scaled by '1 << the shift amt'.
5927 Scale = 1U << CUI->getZExtValue();
5928 Offset = 0;
5929 return I->getOperand(0);
5930 } else if (I->getOpcode() == Instruction::Mul) {
5931 // This value is scaled by 'CUI'.
5932 Scale = CUI->getZExtValue();
5933 Offset = 0;
5934 return I->getOperand(0);
5935 } else if (I->getOpcode() == Instruction::Add) {
5936 // We have X+C. Check to see if we really have (X*C2)+C1,
5937 // where C1 is divisible by C2.
5938 unsigned SubScale;
5939 Value *SubVal =
5940 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5941 Offset += CUI->getZExtValue();
5942 if (SubScale > 1 && (Offset % SubScale == 0)) {
5943 Scale = SubScale;
5944 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005945 }
5946 }
5947 }
5948 }
5949 }
5950
5951 // Otherwise, we can't look past this.
5952 Scale = 1;
5953 Offset = 0;
5954 return Val;
5955}
5956
5957
Chris Lattner216be912005-10-24 06:03:58 +00005958/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5959/// try to eliminate the cast by moving the type information into the alloc.
5960Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5961 AllocationInst &AI) {
5962 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005963 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005964
Chris Lattnerac87beb2005-10-24 06:22:12 +00005965 // Remove any uses of AI that are dead.
5966 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005967
Chris Lattnerac87beb2005-10-24 06:22:12 +00005968 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5969 Instruction *User = cast<Instruction>(*UI++);
5970 if (isInstructionTriviallyDead(User)) {
5971 while (UI != E && *UI == User)
5972 ++UI; // If this instruction uses AI more than once, don't break UI.
5973
Chris Lattnerac87beb2005-10-24 06:22:12 +00005974 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005975 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005976 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005977 }
5978 }
5979
Chris Lattner216be912005-10-24 06:03:58 +00005980 // Get the type really allocated and the type casted to.
5981 const Type *AllocElTy = AI.getAllocatedType();
5982 const Type *CastElTy = PTy->getElementType();
5983 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005984
Chris Lattner945e4372007-02-14 05:52:17 +00005985 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5986 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005987 if (CastElTyAlign < AllocElTyAlign) return 0;
5988
Chris Lattner46705b22005-10-24 06:35:18 +00005989 // If the allocation has multiple uses, only promote it if we are strictly
5990 // increasing the alignment of the resultant allocation. If we keep it the
5991 // same, we open the door to infinite loops of various kinds.
5992 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5993
Chris Lattner216be912005-10-24 06:03:58 +00005994 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5995 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005996 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005997
Chris Lattner8270c332005-10-29 03:19:53 +00005998 // See if we can satisfy the modulus by pulling a scale out of the array
5999 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006000 unsigned ArraySizeScale, ArrayOffset;
6001 Value *NumElements = // See if the array size is a decomposable linear expr.
6002 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6003
Chris Lattner8270c332005-10-29 03:19:53 +00006004 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6005 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006006 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6007 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006008
Chris Lattner8270c332005-10-29 03:19:53 +00006009 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6010 Value *Amt = 0;
6011 if (Scale == 1) {
6012 Amt = NumElements;
6013 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006014 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006015 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6016 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006017 Amt = ConstantExpr::getMul(
6018 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6019 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006020 else if (Scale != 1) {
6021 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6022 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006023 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006024 }
6025
Chris Lattner8f663e82005-10-29 04:36:15 +00006026 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006027 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006028 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6029 Amt = InsertNewInstBefore(Tmp, AI);
6030 }
6031
Chris Lattner216be912005-10-24 06:03:58 +00006032 AllocationInst *New;
6033 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006034 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006035 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006036 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006037 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006038 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006039
6040 // If the allocation has multiple uses, insert a cast and change all things
6041 // that used it to use the new cast. This will also hack on CI, but it will
6042 // die soon.
6043 if (!AI.hasOneUse()) {
6044 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006045 // New is the allocation instruction, pointer typed. AI is the original
6046 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6047 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006048 InsertNewInstBefore(NewCast, AI);
6049 AI.replaceAllUsesWith(NewCast);
6050 }
Chris Lattner216be912005-10-24 06:03:58 +00006051 return ReplaceInstUsesWith(CI, New);
6052}
6053
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006054/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006055/// and return it as type Ty without inserting any new casts and without
6056/// changing the computed value. This is used by code that tries to decide
6057/// whether promoting or shrinking integer operations to wider or smaller types
6058/// will allow us to eliminate a truncate or extend.
6059///
6060/// This is a truncation operation if Ty is smaller than V->getType(), or an
6061/// extension operation if Ty is larger.
6062static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006063 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006064 // We can always evaluate constants in another type.
6065 if (isa<ConstantInt>(V))
6066 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006067
6068 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006069 if (!I) return false;
6070
6071 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006072
6073 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006074 case Instruction::Add:
6075 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006076 case Instruction::And:
6077 case Instruction::Or:
6078 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006079 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006080 // These operators can all arbitrarily be extended or truncated.
6081 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6082 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006083
Chris Lattner960acb02006-11-29 07:18:39 +00006084 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006085 if (!I->hasOneUse()) return false;
6086 // If we are truncating the result of this SHL, and if it's a shift of a
6087 // constant amount, we can always perform a SHL in a smaller type.
6088 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6089 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6090 CI->getZExtValue() < Ty->getBitWidth())
6091 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6092 }
6093 break;
6094 case Instruction::LShr:
6095 if (!I->hasOneUse()) return false;
6096 // If this is a truncate of a logical shr, we can truncate it to a smaller
6097 // lshr iff we know that the bits we would otherwise be shifting in are
6098 // already zeros.
6099 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006100 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006101 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006102 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006103 APInt::getAllOnesValue(BitWidth) &
6104 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6105 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006106 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6107 }
6108 }
Chris Lattner960acb02006-11-29 07:18:39 +00006109 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006110 case Instruction::Trunc:
6111 case Instruction::ZExt:
6112 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006113 // If this is a cast from the destination type, we can trivially eliminate
6114 // it, and this will remove a cast overall.
6115 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006116 // If the first operand is itself a cast, and is eliminable, do not count
6117 // this as an eliminable cast. We would prefer to eliminate those two
6118 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006119 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006120 return true;
6121
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006122 ++NumCastsRemoved;
6123 return true;
6124 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006125 break;
6126 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006127 // TODO: Can handle more cases here.
6128 break;
6129 }
6130
6131 return false;
6132}
6133
6134/// EvaluateInDifferentType - Given an expression that
6135/// CanEvaluateInDifferentType returns true for, actually insert the code to
6136/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006137Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006138 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006139 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006140 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006141
6142 // Otherwise, it must be an instruction.
6143 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006144 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006145 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006146 case Instruction::Add:
6147 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006148 case Instruction::And:
6149 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006150 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006151 case Instruction::AShr:
6152 case Instruction::LShr:
6153 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006154 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006155 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6156 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6157 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006158 break;
6159 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006160 case Instruction::Trunc:
6161 case Instruction::ZExt:
6162 case Instruction::SExt:
6163 case Instruction::BitCast:
6164 // If the source type of the cast is the type we're trying for then we can
6165 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006166 if (I->getOperand(0)->getType() == Ty)
6167 return I->getOperand(0);
6168
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169 // Some other kind of cast, which shouldn't happen, so just ..
6170 // FALL THROUGH
6171 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006172 // TODO: Can handle more cases here.
6173 assert(0 && "Unreachable!");
6174 break;
6175 }
6176
6177 return InsertNewInstBefore(Res, *I);
6178}
6179
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006180/// @brief Implement the transforms common to all CastInst visitors.
6181Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006182 Value *Src = CI.getOperand(0);
6183
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006184 // Casting undef to anything results in undef so might as just replace it and
6185 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006186 if (isa<UndefValue>(Src)) // cast undef -> undef
6187 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6188
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006189 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6190 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006191 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006192 if (Instruction::CastOps opc =
6193 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6194 // The first cast (CSrc) is eliminable so we need to fix up or replace
6195 // the second cast (CI). CSrc will then have a good chance of being dead.
6196 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006197 }
6198 }
Chris Lattner03841652004-05-25 04:29:21 +00006199
Chris Lattnerd0d51602003-06-21 23:12:02 +00006200 // If casting the result of a getelementptr instruction with no offset, turn
6201 // this into a cast of the original pointer!
6202 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006203 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006204 bool AllZeroOperands = true;
6205 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6206 if (!isa<Constant>(GEP->getOperand(i)) ||
6207 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6208 AllZeroOperands = false;
6209 break;
6210 }
6211 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006212 // Changing the cast operand is usually not a good idea but it is safe
6213 // here because the pointer operand is being replaced with another
6214 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006215 CI.setOperand(0, GEP->getOperand(0));
6216 return &CI;
6217 }
6218 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006219
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006220 // If we are casting a malloc or alloca to a pointer to a type of the same
6221 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006222 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006223 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6224 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006225
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006226 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006227 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6228 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6229 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006230
6231 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006232 if (isa<PHINode>(Src))
6233 if (Instruction *NV = FoldOpIntoPhi(CI))
6234 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006235
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006236 return 0;
6237}
6238
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006239/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6240/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006241/// cases.
6242/// @brief Implement the transforms common to CastInst with integer operands
6243Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6244 if (Instruction *Result = commonCastTransforms(CI))
6245 return Result;
6246
6247 Value *Src = CI.getOperand(0);
6248 const Type *SrcTy = Src->getType();
6249 const Type *DestTy = CI.getType();
6250 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6251 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6252
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006253 // See if we can simplify any instructions used by the LHS whose sole
6254 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006255 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6256 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006257 KnownZero, KnownOne))
6258 return &CI;
6259
6260 // If the source isn't an instruction or has more than one use then we
6261 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006262 Instruction *SrcI = dyn_cast<Instruction>(Src);
6263 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006264 return 0;
6265
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006266 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006267 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006268 if (!isa<BitCastInst>(CI) &&
6269 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6270 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006271 // If this cast is a truncate, evaluting in a different type always
6272 // eliminates the cast, so it is always a win. If this is a noop-cast
6273 // this just removes a noop cast which isn't pointful, but simplifies
6274 // the code. If this is a zero-extension, we need to do an AND to
6275 // maintain the clear top-part of the computation, so we require that
6276 // the input have eliminated at least one cast. If this is a sign
6277 // extension, we insert two new casts (to do the extension) so we
6278 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006279 bool DoXForm;
6280 switch (CI.getOpcode()) {
6281 default:
6282 // All the others use floating point so we shouldn't actually
6283 // get here because of the check above.
6284 assert(0 && "Unknown cast type");
6285 case Instruction::Trunc:
6286 DoXForm = true;
6287 break;
6288 case Instruction::ZExt:
6289 DoXForm = NumCastsRemoved >= 1;
6290 break;
6291 case Instruction::SExt:
6292 DoXForm = NumCastsRemoved >= 2;
6293 break;
6294 case Instruction::BitCast:
6295 DoXForm = false;
6296 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006297 }
6298
6299 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006300 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6301 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006302 assert(Res->getType() == DestTy);
6303 switch (CI.getOpcode()) {
6304 default: assert(0 && "Unknown cast type!");
6305 case Instruction::Trunc:
6306 case Instruction::BitCast:
6307 // Just replace this cast with the result.
6308 return ReplaceInstUsesWith(CI, Res);
6309 case Instruction::ZExt: {
6310 // We need to emit an AND to clear the high bits.
6311 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencer4154e732007-03-22 20:56:53 +00006312 Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
6313 C = ConstantExpr::getZExt(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006314 return BinaryOperator::createAnd(Res, C);
6315 }
6316 case Instruction::SExt:
6317 // We need to emit a cast to truncate, then a cast to sext.
6318 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006319 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6320 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006321 }
6322 }
6323 }
6324
6325 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6326 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6327
6328 switch (SrcI->getOpcode()) {
6329 case Instruction::Add:
6330 case Instruction::Mul:
6331 case Instruction::And:
6332 case Instruction::Or:
6333 case Instruction::Xor:
6334 // If we are discarding information, or just changing the sign,
6335 // rewrite.
6336 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6337 // Don't insert two casts if they cannot be eliminated. We allow
6338 // two casts to be inserted if the sizes are the same. This could
6339 // only be converting signedness, which is a noop.
6340 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006341 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6342 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006343 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006344 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6345 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6346 return BinaryOperator::create(
6347 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006348 }
6349 }
6350
6351 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6352 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6353 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006354 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006355 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006356 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006357 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6358 }
6359 break;
6360 case Instruction::SDiv:
6361 case Instruction::UDiv:
6362 case Instruction::SRem:
6363 case Instruction::URem:
6364 // If we are just changing the sign, rewrite.
6365 if (DestBitSize == SrcBitSize) {
6366 // Don't insert two casts if they cannot be eliminated. We allow
6367 // two casts to be inserted if the sizes are the same. This could
6368 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006369 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6370 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006371 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6372 Op0, DestTy, SrcI);
6373 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6374 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006375 return BinaryOperator::create(
6376 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6377 }
6378 }
6379 break;
6380
6381 case Instruction::Shl:
6382 // Allow changing the sign of the source operand. Do not allow
6383 // changing the size of the shift, UNLESS the shift amount is a
6384 // constant. We must not change variable sized shifts to a smaller
6385 // size, because it is undefined to shift more bits out than exist
6386 // in the value.
6387 if (DestBitSize == SrcBitSize ||
6388 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006389 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6390 Instruction::BitCast : Instruction::Trunc);
6391 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006392 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006393 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006394 }
6395 break;
6396 case Instruction::AShr:
6397 // If this is a signed shr, and if all bits shifted in are about to be
6398 // truncated off, turn it into an unsigned shr to allow greater
6399 // simplifications.
6400 if (DestBitSize < SrcBitSize &&
6401 isa<ConstantInt>(Op1)) {
6402 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6403 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6404 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006405 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006406 }
6407 }
6408 break;
6409
Reid Spencer266e42b2006-12-23 06:05:41 +00006410 case Instruction::ICmp:
6411 // If we are just checking for a icmp eq of a single bit and casting it
6412 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006413 // cast to integer to avoid the comparison.
6414 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00006415 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6417 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6418 // cast (X == 1) to int --> X iff X has only the low bit set.
6419 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6420 // cast (X != 0) to int --> X iff X has only the low bit set.
6421 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6422 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6423 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006424 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006425 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006426 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6427 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6428 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006429 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006430
6431 // This only works for EQ and NE
6432 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6433 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6434 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006435
Zhou Sheng0900993e2007-03-23 03:13:21 +00006436 APInt KnownZeroMask(KnownZero ^ TypeMask);
6437 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006438 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006439 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006440 // (X&4) == 2 --> false
6441 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006442 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006443 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006444 return ReplaceInstUsesWith(CI, Res);
6445 }
6446
Zhou Sheng0900993e2007-03-23 03:13:21 +00006447 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006448 Value *In = Op0;
6449 if (ShiftAmt) {
6450 // Perform a logical shr by shiftamt.
6451 // Insert the shift to put the result in the low bit.
6452 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006453 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006454 ConstantInt::get(In->getType(), ShiftAmt),
6455 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006456 }
6457
Reid Spencer266e42b2006-12-23 06:05:41 +00006458 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006459 Constant *One = ConstantInt::get(In->getType(), 1);
6460 In = BinaryOperator::createXor(In, One, "tmp");
6461 InsertNewInstBefore(cast<Instruction>(In), CI);
6462 }
6463
6464 if (CI.getType() == In->getType())
6465 return ReplaceInstUsesWith(CI, In);
6466 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006467 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006468 }
6469 }
6470 }
6471 break;
6472 }
6473 return 0;
6474}
6475
6476Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006477 if (Instruction *Result = commonIntCastTransforms(CI))
6478 return Result;
6479
6480 Value *Src = CI.getOperand(0);
6481 const Type *Ty = CI.getType();
6482 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00006483 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006484
6485 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6486 switch (SrcI->getOpcode()) {
6487 default: break;
6488 case Instruction::LShr:
6489 // We can shrink lshr to something smaller if we know the bits shifted in
6490 // are already zeros.
6491 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6492 unsigned ShAmt = ShAmtV->getZExtValue();
6493
6494 // Get a mask for the bits shifting in.
Reid Spencer4154e732007-03-22 20:56:53 +00006495 APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
6496 SrcBitWidth-ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006497 Value* SrcIOp0 = SrcI->getOperand(0);
6498 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006499 if (ShAmt >= DestBitWidth) // All zeros.
6500 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6501
6502 // Okay, we can shrink this. Truncate the input, then return a new
6503 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006504 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6505 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6506 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006507 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006508 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006509 } else { // This is a variable shr.
6510
6511 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6512 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6513 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006514 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006515 Value *One = ConstantInt::get(SrcI->getType(), 1);
6516
Reid Spencer2341c222007-02-02 02:16:23 +00006517 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006518 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006519 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006520 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6521 SrcI->getOperand(0),
6522 "tmp"), CI);
6523 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006524 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006525 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006526 }
6527 break;
6528 }
6529 }
6530
6531 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006532}
6533
6534Instruction *InstCombiner::visitZExt(CastInst &CI) {
6535 // If one of the common conversion will work ..
6536 if (Instruction *Result = commonIntCastTransforms(CI))
6537 return Result;
6538
6539 Value *Src = CI.getOperand(0);
6540
6541 // If this is a cast of a cast
6542 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006543 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6544 // types and if the sizes are just right we can convert this into a logical
6545 // 'and' which will be much cheaper than the pair of casts.
6546 if (isa<TruncInst>(CSrc)) {
6547 // Get the sizes of the types involved
6548 Value *A = CSrc->getOperand(0);
6549 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6550 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6551 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6552 // If we're actually extending zero bits and the trunc is a no-op
6553 if (MidSize < DstSize && SrcSize == DstSize) {
6554 // Replace both of the casts with an And of the type mask.
Reid Spencer4154e732007-03-22 20:56:53 +00006555 APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
6556 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006557 Instruction *And =
6558 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6559 // Unfortunately, if the type changed, we need to cast it back.
6560 if (And->getType() != CI.getType()) {
6561 And->setName(CSrc->getName()+".mask");
6562 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006563 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006564 }
6565 return And;
6566 }
6567 }
6568 }
6569
6570 return 0;
6571}
6572
6573Instruction *InstCombiner::visitSExt(CastInst &CI) {
6574 return commonIntCastTransforms(CI);
6575}
6576
6577Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6578 return commonCastTransforms(CI);
6579}
6580
6581Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6582 return commonCastTransforms(CI);
6583}
6584
6585Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006586 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006587}
6588
6589Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006590 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006591}
6592
6593Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6594 return commonCastTransforms(CI);
6595}
6596
6597Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6598 return commonCastTransforms(CI);
6599}
6600
6601Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006602 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006603}
6604
6605Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6606 return commonCastTransforms(CI);
6607}
6608
6609Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6610
6611 // If the operands are integer typed then apply the integer transforms,
6612 // otherwise just apply the common ones.
6613 Value *Src = CI.getOperand(0);
6614 const Type *SrcTy = Src->getType();
6615 const Type *DestTy = CI.getType();
6616
Chris Lattner03c49532007-01-15 02:27:26 +00006617 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006618 if (Instruction *Result = commonIntCastTransforms(CI))
6619 return Result;
6620 } else {
6621 if (Instruction *Result = commonCastTransforms(CI))
6622 return Result;
6623 }
6624
6625
6626 // Get rid of casts from one type to the same type. These are useless and can
6627 // be replaced by the operand.
6628 if (DestTy == Src->getType())
6629 return ReplaceInstUsesWith(CI, Src);
6630
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006631 // If the source and destination are pointers, and this cast is equivalent to
6632 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6633 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006634 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6635 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6636 const Type *DstElTy = DstPTy->getElementType();
6637 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006638
Reid Spencerc635f472006-12-31 05:48:39 +00006639 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006640 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006641 while (SrcElTy != DstElTy &&
6642 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6643 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6644 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006645 ++NumZeros;
6646 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006647
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006648 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006649 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006650 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6651 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006652 }
6653 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006654 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006655
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006656 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6657 if (SVI->hasOneUse()) {
6658 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6659 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006660 if (isa<VectorType>(DestTy) &&
6661 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006662 SVI->getType()->getNumElements()) {
6663 CastInst *Tmp;
6664 // If either of the operands is a cast from CI.getType(), then
6665 // evaluating the shuffle in the casted destination's type will allow
6666 // us to eliminate at least one cast.
6667 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6668 Tmp->getOperand(0)->getType() == DestTy) ||
6669 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6670 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006671 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6672 SVI->getOperand(0), DestTy, &CI);
6673 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6674 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006675 // Return a new shuffle vector. Use the same element ID's, as we
6676 // know the vector types match #elts.
6677 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006678 }
6679 }
6680 }
6681 }
Chris Lattner260ab202002-04-18 17:39:14 +00006682 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006683}
6684
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006685/// GetSelectFoldableOperands - We want to turn code that looks like this:
6686/// %C = or %A, %B
6687/// %D = select %cond, %C, %A
6688/// into:
6689/// %C = select %cond, %B, 0
6690/// %D = or %A, %C
6691///
6692/// Assuming that the specified instruction is an operand to the select, return
6693/// a bitmask indicating which operands of this instruction are foldable if they
6694/// equal the other incoming value of the select.
6695///
6696static unsigned GetSelectFoldableOperands(Instruction *I) {
6697 switch (I->getOpcode()) {
6698 case Instruction::Add:
6699 case Instruction::Mul:
6700 case Instruction::And:
6701 case Instruction::Or:
6702 case Instruction::Xor:
6703 return 3; // Can fold through either operand.
6704 case Instruction::Sub: // Can only fold on the amount subtracted.
6705 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006706 case Instruction::LShr:
6707 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006708 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006709 default:
6710 return 0; // Cannot fold
6711 }
6712}
6713
6714/// GetSelectFoldableConstant - For the same transformation as the previous
6715/// function, return the identity constant that goes into the select.
6716static Constant *GetSelectFoldableConstant(Instruction *I) {
6717 switch (I->getOpcode()) {
6718 default: assert(0 && "This cannot happen!"); abort();
6719 case Instruction::Add:
6720 case Instruction::Sub:
6721 case Instruction::Or:
6722 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006723 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006724 case Instruction::LShr:
6725 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006726 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006727 case Instruction::And:
6728 return ConstantInt::getAllOnesValue(I->getType());
6729 case Instruction::Mul:
6730 return ConstantInt::get(I->getType(), 1);
6731 }
6732}
6733
Chris Lattner411336f2005-01-19 21:50:18 +00006734/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6735/// have the same opcode and only one use each. Try to simplify this.
6736Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6737 Instruction *FI) {
6738 if (TI->getNumOperands() == 1) {
6739 // If this is a non-volatile load or a cast from the same type,
6740 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006741 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006742 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6743 return 0;
6744 } else {
6745 return 0; // unknown unary op.
6746 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006747
Chris Lattner411336f2005-01-19 21:50:18 +00006748 // Fold this by inserting a select from the input values.
6749 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6750 FI->getOperand(0), SI.getName()+".v");
6751 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006752 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6753 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006754 }
6755
Reid Spencer2341c222007-02-02 02:16:23 +00006756 // Only handle binary operators here.
6757 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006758 return 0;
6759
6760 // Figure out if the operations have any operands in common.
6761 Value *MatchOp, *OtherOpT, *OtherOpF;
6762 bool MatchIsOpZero;
6763 if (TI->getOperand(0) == FI->getOperand(0)) {
6764 MatchOp = TI->getOperand(0);
6765 OtherOpT = TI->getOperand(1);
6766 OtherOpF = FI->getOperand(1);
6767 MatchIsOpZero = true;
6768 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6769 MatchOp = TI->getOperand(1);
6770 OtherOpT = TI->getOperand(0);
6771 OtherOpF = FI->getOperand(0);
6772 MatchIsOpZero = false;
6773 } else if (!TI->isCommutative()) {
6774 return 0;
6775 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6776 MatchOp = TI->getOperand(0);
6777 OtherOpT = TI->getOperand(1);
6778 OtherOpF = FI->getOperand(0);
6779 MatchIsOpZero = true;
6780 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6781 MatchOp = TI->getOperand(1);
6782 OtherOpT = TI->getOperand(0);
6783 OtherOpF = FI->getOperand(1);
6784 MatchIsOpZero = true;
6785 } else {
6786 return 0;
6787 }
6788
6789 // If we reach here, they do have operations in common.
6790 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6791 OtherOpF, SI.getName()+".v");
6792 InsertNewInstBefore(NewSI, SI);
6793
6794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6795 if (MatchIsOpZero)
6796 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6797 else
6798 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006799 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006800 assert(0 && "Shouldn't get here");
6801 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006802}
6803
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006804Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006805 Value *CondVal = SI.getCondition();
6806 Value *TrueVal = SI.getTrueValue();
6807 Value *FalseVal = SI.getFalseValue();
6808
6809 // select true, X, Y -> X
6810 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006811 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006812 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006813
6814 // select C, X, X -> X
6815 if (TrueVal == FalseVal)
6816 return ReplaceInstUsesWith(SI, TrueVal);
6817
Chris Lattner81a7a232004-10-16 18:11:37 +00006818 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6819 return ReplaceInstUsesWith(SI, FalseVal);
6820 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6821 return ReplaceInstUsesWith(SI, TrueVal);
6822 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6823 if (isa<Constant>(TrueVal))
6824 return ReplaceInstUsesWith(SI, TrueVal);
6825 else
6826 return ReplaceInstUsesWith(SI, FalseVal);
6827 }
6828
Reid Spencer542964f2007-01-11 18:21:29 +00006829 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006830 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006831 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006832 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006833 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006834 } else {
6835 // Change: A = select B, false, C --> A = and !B, C
6836 Value *NotCond =
6837 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6838 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006839 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006840 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006841 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006842 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006843 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006844 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006845 } else {
6846 // Change: A = select B, C, true --> A = or !B, C
6847 Value *NotCond =
6848 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6849 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006850 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006851 }
6852 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006853 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006854
Chris Lattner183b3362004-04-09 19:05:30 +00006855 // Selecting between two integer constants?
6856 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6857 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6858 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006859 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006860 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006861 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006862 // select C, 0, 1 -> cast !C to int
6863 Value *NotCond =
6864 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006865 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006866 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006867 }
Chris Lattner35167c32004-06-09 07:59:58 +00006868
Reid Spencer266e42b2006-12-23 06:05:41 +00006869 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006870
Reid Spencer266e42b2006-12-23 06:05:41 +00006871 // (x <s 0) ? -1 : 0 -> ashr x, 31
6872 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006873 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006874 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6875 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006876 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006877 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006878 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006879 else {
6880 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006881 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006882 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006883 }
6884
6885 if (CanXForm) {
6886 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006887 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006888 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006889 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006890 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6891 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6892 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006893 InsertNewInstBefore(SRA, SI);
6894
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006895 // Finally, convert to the type of the select RHS. We figure out
6896 // if this requires a SExt, Trunc or BitCast based on the sizes.
6897 Instruction::CastOps opc = Instruction::BitCast;
6898 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6899 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6900 if (SRASize < SISize)
6901 opc = Instruction::SExt;
6902 else if (SRASize > SISize)
6903 opc = Instruction::Trunc;
6904 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006905 }
6906 }
6907
6908
6909 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006910 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006911 // non-constant value, eliminate this whole mess. This corresponds to
6912 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006913 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006914 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006915 cast<Constant>(IC->getOperand(1))->isNullValue())
6916 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6917 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006918 isa<ConstantInt>(ICA->getOperand(1)) &&
6919 (ICA->getOperand(1) == TrueValC ||
6920 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006921 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6922 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006923 // know whether we have a icmp_ne or icmp_eq and whether the
6924 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006925 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006926 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006927 Value *V = ICA;
6928 if (ShouldNotVal)
6929 V = InsertNewInstBefore(BinaryOperator::create(
6930 Instruction::Xor, V, ICA->getOperand(1)), SI);
6931 return ReplaceInstUsesWith(SI, V);
6932 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006933 }
Chris Lattner533bc492004-03-30 19:37:13 +00006934 }
Chris Lattner623fba12004-04-10 22:21:27 +00006935
6936 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006937 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6938 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006939 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006940 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006941 return ReplaceInstUsesWith(SI, FalseVal);
6942 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006943 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006944 return ReplaceInstUsesWith(SI, TrueVal);
6945 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6946
Reid Spencer266e42b2006-12-23 06:05:41 +00006947 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006948 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006949 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006950 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006951 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006952 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6953 return ReplaceInstUsesWith(SI, TrueVal);
6954 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6955 }
6956 }
6957
6958 // See if we are selecting two values based on a comparison of the two values.
6959 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6960 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6961 // Transform (X == Y) ? X : Y -> Y
6962 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6963 return ReplaceInstUsesWith(SI, FalseVal);
6964 // Transform (X != Y) ? X : Y -> X
6965 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6966 return ReplaceInstUsesWith(SI, TrueVal);
6967 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6968
6969 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6970 // Transform (X == Y) ? Y : X -> X
6971 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6972 return ReplaceInstUsesWith(SI, FalseVal);
6973 // Transform (X != Y) ? Y : X -> Y
6974 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006975 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006976 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6977 }
6978 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006979
Chris Lattnera04c9042005-01-13 22:52:24 +00006980 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6981 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6982 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006983 Instruction *AddOp = 0, *SubOp = 0;
6984
Chris Lattner411336f2005-01-19 21:50:18 +00006985 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6986 if (TI->getOpcode() == FI->getOpcode())
6987 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6988 return IV;
6989
6990 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6991 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006992 if (TI->getOpcode() == Instruction::Sub &&
6993 FI->getOpcode() == Instruction::Add) {
6994 AddOp = FI; SubOp = TI;
6995 } else if (FI->getOpcode() == Instruction::Sub &&
6996 TI->getOpcode() == Instruction::Add) {
6997 AddOp = TI; SubOp = FI;
6998 }
6999
7000 if (AddOp) {
7001 Value *OtherAddOp = 0;
7002 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7003 OtherAddOp = AddOp->getOperand(1);
7004 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7005 OtherAddOp = AddOp->getOperand(0);
7006 }
7007
7008 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007009 // So at this point we know we have (Y -> OtherAddOp):
7010 // select C, (add X, Y), (sub X, Z)
7011 Value *NegVal; // Compute -Z
7012 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7013 NegVal = ConstantExpr::getNeg(C);
7014 } else {
7015 NegVal = InsertNewInstBefore(
7016 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007017 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007018
7019 Value *NewTrueOp = OtherAddOp;
7020 Value *NewFalseOp = NegVal;
7021 if (AddOp != TI)
7022 std::swap(NewTrueOp, NewFalseOp);
7023 Instruction *NewSel =
7024 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7025
7026 NewSel = InsertNewInstBefore(NewSel, SI);
7027 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007028 }
7029 }
7030 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007031
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007032 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007033 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007034 // See the comment above GetSelectFoldableOperands for a description of the
7035 // transformation we are doing here.
7036 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7037 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7038 !isa<Constant>(FalseVal))
7039 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7040 unsigned OpToFold = 0;
7041 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7042 OpToFold = 1;
7043 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7044 OpToFold = 2;
7045 }
7046
7047 if (OpToFold) {
7048 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007049 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007050 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007051 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007052 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007053 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7054 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007055 else {
7056 assert(0 && "Unknown instruction!!");
7057 }
7058 }
7059 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007060
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007061 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7062 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7063 !isa<Constant>(TrueVal))
7064 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7065 unsigned OpToFold = 0;
7066 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7067 OpToFold = 1;
7068 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7069 OpToFold = 2;
7070 }
7071
7072 if (OpToFold) {
7073 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007074 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007075 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007076 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007077 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7079 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007080 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007081 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007082 }
7083 }
7084 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007085
7086 if (BinaryOperator::isNot(CondVal)) {
7087 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7088 SI.setOperand(1, FalseVal);
7089 SI.setOperand(2, TrueVal);
7090 return &SI;
7091 }
7092
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007093 return 0;
7094}
7095
Chris Lattner82f2ef22006-03-06 20:18:44 +00007096/// GetKnownAlignment - If the specified pointer has an alignment that we can
7097/// determine, return it, otherwise return 0.
7098static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7099 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7100 unsigned Align = GV->getAlignment();
7101 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007102 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007103 return Align;
7104 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7105 unsigned Align = AI->getAlignment();
7106 if (Align == 0 && TD) {
7107 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007108 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007109 else if (isa<MallocInst>(AI)) {
7110 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007111 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007112 Align =
7113 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007114 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007115 Align =
7116 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007117 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007118 }
7119 }
7120 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007121 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007122 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007123 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007124 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007125 if (isa<PointerType>(CI->getOperand(0)->getType()))
7126 return GetKnownAlignment(CI->getOperand(0), TD);
7127 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007128 } else if (isa<GetElementPtrInst>(V) ||
7129 (isa<ConstantExpr>(V) &&
7130 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7131 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007132 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7133 if (BaseAlignment == 0) return 0;
7134
7135 // If all indexes are zero, it is just the alignment of the base pointer.
7136 bool AllZeroOperands = true;
7137 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7138 if (!isa<Constant>(GEPI->getOperand(i)) ||
7139 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7140 AllZeroOperands = false;
7141 break;
7142 }
7143 if (AllZeroOperands)
7144 return BaseAlignment;
7145
7146 // Otherwise, if the base alignment is >= the alignment we expect for the
7147 // base pointer type, then we know that the resultant pointer is aligned at
7148 // least as much as its type requires.
7149 if (!TD) return 0;
7150
7151 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007152 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007153 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007154 <= BaseAlignment) {
7155 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007156 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007157 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007158 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007159 return 0;
7160 }
7161 return 0;
7162}
7163
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007164
Chris Lattnerc66b2232006-01-13 20:11:04 +00007165/// visitCallInst - CallInst simplification. This mostly only handles folding
7166/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7167/// the heavy lifting.
7168///
Chris Lattner970c33a2003-06-19 17:00:31 +00007169Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007170 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7171 if (!II) return visitCallSite(&CI);
7172
Chris Lattner51ea1272004-02-28 05:22:00 +00007173 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7174 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007175 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007176 bool Changed = false;
7177
7178 // memmove/cpy/set of zero bytes is a noop.
7179 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7180 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7181
Chris Lattner00648e12004-10-12 04:52:52 +00007182 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007183 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007184 // Replace the instruction with just byte operations. We would
7185 // transform other cases to loads/stores, but we don't know if
7186 // alignment is sufficient.
7187 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007188 }
7189
Chris Lattner00648e12004-10-12 04:52:52 +00007190 // If we have a memmove and the source operation is a constant global,
7191 // then the source and dest pointers can't alias, so we can change this
7192 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007193 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007194 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7195 if (GVSrc->isConstant()) {
7196 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007197 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007198 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007199 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007200 Name = "llvm.memcpy.i32";
7201 else
7202 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007203 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007204 CI.getCalledFunction()->getFunctionType());
7205 CI.setOperand(0, MemCpy);
7206 Changed = true;
7207 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007208 }
Chris Lattner00648e12004-10-12 04:52:52 +00007209
Chris Lattner82f2ef22006-03-06 20:18:44 +00007210 // If we can determine a pointer alignment that is bigger than currently
7211 // set, update the alignment.
7212 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7213 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7214 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7215 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007216 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007217 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007218 Changed = true;
7219 }
7220 } else if (isa<MemSetInst>(MI)) {
7221 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007222 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007223 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007224 Changed = true;
7225 }
7226 }
7227
Chris Lattnerc66b2232006-01-13 20:11:04 +00007228 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007229 } else {
7230 switch (II->getIntrinsicID()) {
7231 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007232 case Intrinsic::ppc_altivec_lvx:
7233 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007234 case Intrinsic::x86_sse_loadu_ps:
7235 case Intrinsic::x86_sse2_loadu_pd:
7236 case Intrinsic::x86_sse2_loadu_dq:
7237 // Turn PPC lvx -> load if the pointer is known aligned.
7238 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007239 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007240 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007241 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007242 return new LoadInst(Ptr);
7243 }
7244 break;
7245 case Intrinsic::ppc_altivec_stvx:
7246 case Intrinsic::ppc_altivec_stvxl:
7247 // Turn stvx -> store if the pointer is known aligned.
7248 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007249 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007250 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7251 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007252 return new StoreInst(II->getOperand(1), Ptr);
7253 }
7254 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007255 case Intrinsic::x86_sse_storeu_ps:
7256 case Intrinsic::x86_sse2_storeu_pd:
7257 case Intrinsic::x86_sse2_storeu_dq:
7258 case Intrinsic::x86_sse2_storel_dq:
7259 // Turn X86 storeu -> store if the pointer is known aligned.
7260 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7261 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007262 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7263 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007264 return new StoreInst(II->getOperand(2), Ptr);
7265 }
7266 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007267
7268 case Intrinsic::x86_sse_cvttss2si: {
7269 // These intrinsics only demands the 0th element of its input vector. If
7270 // we can simplify the input based on that, do so now.
7271 uint64_t UndefElts;
7272 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7273 UndefElts)) {
7274 II->setOperand(1, V);
7275 return II;
7276 }
7277 break;
7278 }
7279
Chris Lattnere79d2492006-04-06 19:19:17 +00007280 case Intrinsic::ppc_altivec_vperm:
7281 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007282 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007283 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7284
7285 // Check that all of the elements are integer constants or undefs.
7286 bool AllEltsOk = true;
7287 for (unsigned i = 0; i != 16; ++i) {
7288 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7289 !isa<UndefValue>(Mask->getOperand(i))) {
7290 AllEltsOk = false;
7291 break;
7292 }
7293 }
7294
7295 if (AllEltsOk) {
7296 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007297 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7298 II->getOperand(1), Mask->getType(), CI);
7299 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7300 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007301 Value *Result = UndefValue::get(Op0->getType());
7302
7303 // Only extract each element once.
7304 Value *ExtractedElts[32];
7305 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7306
7307 for (unsigned i = 0; i != 16; ++i) {
7308 if (isa<UndefValue>(Mask->getOperand(i)))
7309 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007310 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007311 Idx &= 31; // Match the hardware behavior.
7312
7313 if (ExtractedElts[Idx] == 0) {
7314 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007315 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007316 InsertNewInstBefore(Elt, CI);
7317 ExtractedElts[Idx] = Elt;
7318 }
7319
7320 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007321 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007322 InsertNewInstBefore(cast<Instruction>(Result), CI);
7323 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007324 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007325 }
7326 }
7327 break;
7328
Chris Lattner503221f2006-01-13 21:28:09 +00007329 case Intrinsic::stackrestore: {
7330 // If the save is right next to the restore, remove the restore. This can
7331 // happen when variable allocas are DCE'd.
7332 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7333 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7334 BasicBlock::iterator BI = SS;
7335 if (&*++BI == II)
7336 return EraseInstFromFunction(CI);
7337 }
7338 }
7339
7340 // If the stack restore is in a return/unwind block and if there are no
7341 // allocas or calls between the restore and the return, nuke the restore.
7342 TerminatorInst *TI = II->getParent()->getTerminator();
7343 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7344 BasicBlock::iterator BI = II;
7345 bool CannotRemove = false;
7346 for (++BI; &*BI != TI; ++BI) {
7347 if (isa<AllocaInst>(BI) ||
7348 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7349 CannotRemove = true;
7350 break;
7351 }
7352 }
7353 if (!CannotRemove)
7354 return EraseInstFromFunction(CI);
7355 }
7356 break;
7357 }
7358 }
Chris Lattner00648e12004-10-12 04:52:52 +00007359 }
7360
Chris Lattnerc66b2232006-01-13 20:11:04 +00007361 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007362}
7363
7364// InvokeInst simplification
7365//
7366Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007367 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007368}
7369
Chris Lattneraec3d942003-10-07 22:32:43 +00007370// visitCallSite - Improvements for call and invoke instructions.
7371//
7372Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007373 bool Changed = false;
7374
7375 // If the callee is a constexpr cast of a function, attempt to move the cast
7376 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007377 if (transformConstExprCastCall(CS)) return 0;
7378
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007379 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007380
Chris Lattner61d9d812005-05-13 07:09:09 +00007381 if (Function *CalleeF = dyn_cast<Function>(Callee))
7382 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7383 Instruction *OldCall = CS.getInstruction();
7384 // If the call and callee calling conventions don't match, this call must
7385 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007386 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007387 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007388 if (!OldCall->use_empty())
7389 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7390 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7391 return EraseInstFromFunction(*OldCall);
7392 return 0;
7393 }
7394
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007395 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7396 // This instruction is not reachable, just remove it. We insert a store to
7397 // undef so that we know that this code is not reachable, despite the fact
7398 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007399 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007400 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007401 CS.getInstruction());
7402
7403 if (!CS.getInstruction()->use_empty())
7404 CS.getInstruction()->
7405 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7406
7407 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7408 // Don't break the CFG, insert a dummy cond branch.
7409 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007410 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007411 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007412 return EraseInstFromFunction(*CS.getInstruction());
7413 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007414
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007415 const PointerType *PTy = cast<PointerType>(Callee->getType());
7416 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7417 if (FTy->isVarArg()) {
7418 // See if we can optimize any arguments passed through the varargs area of
7419 // the call.
7420 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7421 E = CS.arg_end(); I != E; ++I)
7422 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7423 // If this cast does not effect the value passed through the varargs
7424 // area, we can eliminate the use of the cast.
7425 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007426 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007427 *I = Op;
7428 Changed = true;
7429 }
7430 }
7431 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007432
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007433 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007434}
7435
Chris Lattner970c33a2003-06-19 17:00:31 +00007436// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7437// attempt to move the cast to the arguments of the call/invoke.
7438//
7439bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7440 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7441 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007442 if (CE->getOpcode() != Instruction::BitCast ||
7443 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007444 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007445 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007446 Instruction *Caller = CS.getInstruction();
7447
7448 // Okay, this is a cast from a function to a different type. Unless doing so
7449 // would cause a type conversion of one of our arguments, change this call to
7450 // be a direct call with arguments casted to the appropriate types.
7451 //
7452 const FunctionType *FT = Callee->getFunctionType();
7453 const Type *OldRetTy = Caller->getType();
7454
Chris Lattner1f7942f2004-01-14 06:06:08 +00007455 // Check to see if we are changing the return type...
7456 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007457 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007458 // Conversion is ok if changing from pointer to int of same size.
7459 !(isa<PointerType>(FT->getReturnType()) &&
7460 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007461 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007462
7463 // If the callsite is an invoke instruction, and the return value is used by
7464 // a PHI node in a successor, we cannot change the return type of the call
7465 // because there is no place to put the cast instruction (without breaking
7466 // the critical edge). Bail out in this case.
7467 if (!Caller->use_empty())
7468 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7469 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7470 UI != E; ++UI)
7471 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7472 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007473 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007474 return false;
7475 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007476
7477 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7478 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007479
Chris Lattner970c33a2003-06-19 17:00:31 +00007480 CallSite::arg_iterator AI = CS.arg_begin();
7481 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7482 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007483 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007484 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007485 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007486 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007487 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007488 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007489 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7490 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007491 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007492 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007493 }
7494
7495 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007496 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007497 return false; // Do not delete arguments unless we have a function body...
7498
7499 // Okay, we decided that this is a safe thing to do: go ahead and start
7500 // inserting cast instructions as necessary...
7501 std::vector<Value*> Args;
7502 Args.reserve(NumActualArgs);
7503
7504 AI = CS.arg_begin();
7505 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7506 const Type *ParamTy = FT->getParamType(i);
7507 if ((*AI)->getType() == ParamTy) {
7508 Args.push_back(*AI);
7509 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007510 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007511 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007512 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007513 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007514 }
7515 }
7516
7517 // If the function takes more arguments than the call was taking, add them
7518 // now...
7519 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7520 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7521
7522 // If we are removing arguments to the function, emit an obnoxious warning...
7523 if (FT->getNumParams() < NumActualArgs)
7524 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007525 cerr << "WARNING: While resolving call to function '"
7526 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007527 } else {
7528 // Add all of the arguments in their promoted form to the arg list...
7529 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7530 const Type *PTy = getPromotedType((*AI)->getType());
7531 if (PTy != (*AI)->getType()) {
7532 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007533 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7534 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007535 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007536 InsertNewInstBefore(Cast, *Caller);
7537 Args.push_back(Cast);
7538 } else {
7539 Args.push_back(*AI);
7540 }
7541 }
7542 }
7543
7544 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007545 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007546
7547 Instruction *NC;
7548 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007549 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007550 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007551 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007552 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007553 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007554 if (cast<CallInst>(Caller)->isTailCall())
7555 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007556 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007557 }
7558
Chris Lattner6e0123b2007-02-11 01:23:03 +00007559 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007560 Value *NV = NC;
7561 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7562 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007563 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007564 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7565 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007566 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007567
7568 // If this is an invoke instruction, we should insert it after the first
7569 // non-phi, instruction in the normal successor block.
7570 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7571 BasicBlock::iterator I = II->getNormalDest()->begin();
7572 while (isa<PHINode>(I)) ++I;
7573 InsertNewInstBefore(NC, *I);
7574 } else {
7575 // Otherwise, it's a call, just insert cast right after the call instr
7576 InsertNewInstBefore(NC, *Caller);
7577 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007578 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007579 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007580 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007581 }
7582 }
7583
7584 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7585 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007586 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007587 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007588 return true;
7589}
7590
Chris Lattnercadac0c2006-11-01 04:51:18 +00007591/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7592/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7593/// and a single binop.
7594Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7595 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007596 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7597 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007598 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007599 Value *LHSVal = FirstInst->getOperand(0);
7600 Value *RHSVal = FirstInst->getOperand(1);
7601
7602 const Type *LHSType = LHSVal->getType();
7603 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007604
7605 // Scan to see if all operands are the same opcode, all have one use, and all
7606 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007607 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007608 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007609 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007610 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007611 // types or GEP's with different index types.
7612 I->getOperand(0)->getType() != LHSType ||
7613 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007614 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007615
7616 // If they are CmpInst instructions, check their predicates
7617 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7618 if (cast<CmpInst>(I)->getPredicate() !=
7619 cast<CmpInst>(FirstInst)->getPredicate())
7620 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007621
7622 // Keep track of which operand needs a phi node.
7623 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7624 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007625 }
7626
Chris Lattner4f218d52006-11-08 19:42:28 +00007627 // Otherwise, this is safe to transform, determine if it is profitable.
7628
7629 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7630 // Indexes are often folded into load/store instructions, so we don't want to
7631 // hide them behind a phi.
7632 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7633 return 0;
7634
Chris Lattnercadac0c2006-11-01 04:51:18 +00007635 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007636 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007637 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007638 if (LHSVal == 0) {
7639 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7640 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7641 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007642 InsertNewInstBefore(NewLHS, PN);
7643 LHSVal = NewLHS;
7644 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007645
7646 if (RHSVal == 0) {
7647 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7648 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7649 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007650 InsertNewInstBefore(NewRHS, PN);
7651 RHSVal = NewRHS;
7652 }
7653
Chris Lattnercd62f112006-11-08 19:29:23 +00007654 // Add all operands to the new PHIs.
7655 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7656 if (NewLHS) {
7657 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7658 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7659 }
7660 if (NewRHS) {
7661 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7662 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7663 }
7664 }
7665
Chris Lattnercadac0c2006-11-01 04:51:18 +00007666 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007667 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007668 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7669 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7670 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007671 else {
7672 assert(isa<GetElementPtrInst>(FirstInst));
7673 return new GetElementPtrInst(LHSVal, RHSVal);
7674 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007675}
7676
Chris Lattner14f82c72006-11-01 07:13:54 +00007677/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7678/// of the block that defines it. This means that it must be obvious the value
7679/// of the load is not changed from the point of the load to the end of the
7680/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007681///
7682/// Finally, it is safe, but not profitable, to sink a load targetting a
7683/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7684/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007685static bool isSafeToSinkLoad(LoadInst *L) {
7686 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7687
7688 for (++BBI; BBI != E; ++BBI)
7689 if (BBI->mayWriteToMemory())
7690 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007691
7692 // Check for non-address taken alloca. If not address-taken already, it isn't
7693 // profitable to do this xform.
7694 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7695 bool isAddressTaken = false;
7696 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7697 UI != E; ++UI) {
7698 if (isa<LoadInst>(UI)) continue;
7699 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7700 // If storing TO the alloca, then the address isn't taken.
7701 if (SI->getOperand(1) == AI) continue;
7702 }
7703 isAddressTaken = true;
7704 break;
7705 }
7706
7707 if (!isAddressTaken)
7708 return false;
7709 }
7710
Chris Lattner14f82c72006-11-01 07:13:54 +00007711 return true;
7712}
7713
Chris Lattner970c33a2003-06-19 17:00:31 +00007714
Chris Lattner7515cab2004-11-14 19:13:23 +00007715// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7716// operator and they all are only used by the PHI, PHI together their
7717// inputs, and do the operation once, to the result of the PHI.
7718Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7719 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7720
7721 // Scan the instruction, looking for input operations that can be folded away.
7722 // If all input operands to the phi are the same instruction (e.g. a cast from
7723 // the same type or "+42") we can pull the operation through the PHI, reducing
7724 // code size and simplifying code.
7725 Constant *ConstantOp = 0;
7726 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007727 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007728 if (isa<CastInst>(FirstInst)) {
7729 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007730 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007731 // Can fold binop, compare or shift here if the RHS is a constant,
7732 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007733 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007734 if (ConstantOp == 0)
7735 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007736 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7737 isVolatile = LI->isVolatile();
7738 // We can't sink the load if the loaded value could be modified between the
7739 // load and the PHI.
7740 if (LI->getParent() != PN.getIncomingBlock(0) ||
7741 !isSafeToSinkLoad(LI))
7742 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007743 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007744 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007745 return FoldPHIArgBinOpIntoPHI(PN);
7746 // Can't handle general GEPs yet.
7747 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007748 } else {
7749 return 0; // Cannot fold this operation.
7750 }
7751
7752 // Check to see if all arguments are the same operation.
7753 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7754 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7755 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007756 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007757 return 0;
7758 if (CastSrcTy) {
7759 if (I->getOperand(0)->getType() != CastSrcTy)
7760 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007761 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007762 // We can't sink the load if the loaded value could be modified between
7763 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007764 if (LI->isVolatile() != isVolatile ||
7765 LI->getParent() != PN.getIncomingBlock(i) ||
7766 !isSafeToSinkLoad(LI))
7767 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007768 } else if (I->getOperand(1) != ConstantOp) {
7769 return 0;
7770 }
7771 }
7772
7773 // Okay, they are all the same operation. Create a new PHI node of the
7774 // correct type, and PHI together all of the LHS's of the instructions.
7775 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7776 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007777 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007778
7779 Value *InVal = FirstInst->getOperand(0);
7780 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007781
7782 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007783 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7784 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7785 if (NewInVal != InVal)
7786 InVal = 0;
7787 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7788 }
7789
7790 Value *PhiVal;
7791 if (InVal) {
7792 // The new PHI unions all of the same values together. This is really
7793 // common, so we handle it intelligently here for compile-time speed.
7794 PhiVal = InVal;
7795 delete NewPN;
7796 } else {
7797 InsertNewInstBefore(NewPN, PN);
7798 PhiVal = NewPN;
7799 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007800
Chris Lattner7515cab2004-11-14 19:13:23 +00007801 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007802 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7803 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007804 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007805 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007806 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007807 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007808 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7809 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7810 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007811 else
Reid Spencer2341c222007-02-02 02:16:23 +00007812 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007813 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007814}
Chris Lattner48a44f72002-05-02 17:06:02 +00007815
Chris Lattner71536432005-01-17 05:10:15 +00007816/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7817/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007818static bool DeadPHICycle(PHINode *PN,
7819 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00007820 if (PN->use_empty()) return true;
7821 if (!PN->hasOneUse()) return false;
7822
7823 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007824 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00007825 return true;
7826
7827 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7828 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007829
Chris Lattner71536432005-01-17 05:10:15 +00007830 return false;
7831}
7832
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007833// PHINode simplification
7834//
Chris Lattner113f4f42002-06-25 16:13:24 +00007835Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007836 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007837 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007838
Owen Andersonae8aa642006-07-10 22:03:18 +00007839 if (Value *V = PN.hasConstantValue())
7840 return ReplaceInstUsesWith(PN, V);
7841
Owen Andersonae8aa642006-07-10 22:03:18 +00007842 // If all PHI operands are the same operation, pull them through the PHI,
7843 // reducing code size.
7844 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7845 PN.getIncomingValue(0)->hasOneUse())
7846 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7847 return Result;
7848
7849 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7850 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7851 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007852 if (PN.hasOneUse()) {
7853 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7854 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00007855 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00007856 PotentiallyDeadPHIs.insert(&PN);
7857 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7858 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7859 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007860
7861 // If this phi has a single use, and if that use just computes a value for
7862 // the next iteration of a loop, delete the phi. This occurs with unused
7863 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7864 // common case here is good because the only other things that catch this
7865 // are induction variable analysis (sometimes) and ADCE, which is only run
7866 // late.
7867 if (PHIUser->hasOneUse() &&
7868 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7869 PHIUser->use_back() == &PN) {
7870 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7871 }
7872 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007873
Chris Lattner91daeb52003-12-19 05:58:40 +00007874 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007875}
7876
Reid Spencer13bc5d72006-12-12 09:18:51 +00007877static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7878 Instruction *InsertPoint,
7879 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007880 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7881 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007882 // We must cast correctly to the pointer type. Ensure that we
7883 // sign extend the integer value if it is smaller as this is
7884 // used for address computation.
7885 Instruction::CastOps opcode =
7886 (VTySize < PtrSize ? Instruction::SExt :
7887 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7888 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007889}
7890
Chris Lattner48a44f72002-05-02 17:06:02 +00007891
Chris Lattner113f4f42002-06-25 16:13:24 +00007892Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007893 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007894 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007895 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007896 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007897 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007898
Chris Lattner81a7a232004-10-16 18:11:37 +00007899 if (isa<UndefValue>(GEP.getOperand(0)))
7900 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7901
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007902 bool HasZeroPointerIndex = false;
7903 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7904 HasZeroPointerIndex = C->isNullValue();
7905
7906 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007907 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007908
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007909 // Keep track of whether all indices are zero constants integers.
7910 bool AllZeroIndices = true;
7911
Chris Lattner69193f92004-04-05 01:30:19 +00007912 // Eliminate unneeded casts for indices.
7913 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007914
Chris Lattner2b2412d2004-04-07 18:38:20 +00007915 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007916 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7917 // Track whether this GEP has all zero indices, if so, it doesn't move the
7918 // input pointer, it just changes its type.
7919 if (AllZeroIndices) {
7920 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7921 AllZeroIndices = CI->isNullValue();
7922 else
7923 AllZeroIndices = false;
7924 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007925 if (isa<SequentialType>(*GTI)) {
7926 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007927 if (CI->getOpcode() == Instruction::ZExt ||
7928 CI->getOpcode() == Instruction::SExt) {
7929 const Type *SrcTy = CI->getOperand(0)->getType();
7930 // We can eliminate a cast from i32 to i64 iff the target
7931 // is a 32-bit pointer target.
7932 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7933 MadeChange = true;
7934 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007935 }
7936 }
7937 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007938 // If we are using a wider index than needed for this platform, shrink it
7939 // to what we need. If the incoming value needs a cast instruction,
7940 // insert it. This explicit cast can make subsequent optimizations more
7941 // obvious.
7942 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007943 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007944 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007945 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007946 MadeChange = true;
7947 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007948 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7949 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007950 GEP.setOperand(i, Op);
7951 MadeChange = true;
7952 }
Chris Lattner69193f92004-04-05 01:30:19 +00007953 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007954 }
Chris Lattner69193f92004-04-05 01:30:19 +00007955 if (MadeChange) return &GEP;
7956
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007957 // If this GEP instruction doesn't move the pointer, and if the input operand
7958 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7959 // real input to the dest type.
7960 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7961 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7962 GEP.getType());
7963
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007964 // Combine Indices - If the source pointer to this getelementptr instruction
7965 // is a getelementptr instruction, combine the indices of the two
7966 // getelementptr instructions into a single instruction.
7967 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007968 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007969 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007970 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007971
7972 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007973 // Note that if our source is a gep chain itself that we wait for that
7974 // chain to be resolved before we perform this transformation. This
7975 // avoids us creating a TON of code in some cases.
7976 //
7977 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7978 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7979 return 0; // Wait until our source is folded to completion.
7980
Chris Lattneraf6094f2007-02-15 22:48:32 +00007981 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007982
7983 // Find out whether the last index in the source GEP is a sequential idx.
7984 bool EndsWithSequential = false;
7985 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7986 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007987 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007988
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007989 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007990 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007991 // Replace: gep (gep %P, long B), long A, ...
7992 // With: T = long A+B; gep %P, T, ...
7993 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007994 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007995 if (SO1 == Constant::getNullValue(SO1->getType())) {
7996 Sum = GO1;
7997 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7998 Sum = SO1;
7999 } else {
8000 // If they aren't the same type, convert both to an integer of the
8001 // target's pointer size.
8002 if (SO1->getType() != GO1->getType()) {
8003 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008004 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008005 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008006 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008007 } else {
8008 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008009 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008010 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008011 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008012
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008013 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008014 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008015 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008016 } else {
8017 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008018 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8019 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008020 }
8021 }
8022 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008023 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8024 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8025 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008026 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8027 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008028 }
Chris Lattner69193f92004-04-05 01:30:19 +00008029 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008030
8031 // Recycle the GEP we already have if possible.
8032 if (SrcGEPOperands.size() == 2) {
8033 GEP.setOperand(0, SrcGEPOperands[0]);
8034 GEP.setOperand(1, Sum);
8035 return &GEP;
8036 } else {
8037 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8038 SrcGEPOperands.end()-1);
8039 Indices.push_back(Sum);
8040 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8041 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008042 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008043 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008044 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008045 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008046 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8047 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008048 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8049 }
8050
8051 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008052 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8053 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008054
Chris Lattner5f667a62004-05-07 22:09:22 +00008055 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008056 // GEP of global variable. If all of the indices for this GEP are
8057 // constants, we can promote this to a constexpr instead of an instruction.
8058
8059 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008060 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008061 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8062 for (; I != E && isa<Constant>(*I); ++I)
8063 Indices.push_back(cast<Constant>(*I));
8064
8065 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008066 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8067 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008068
8069 // Replace all uses of the GEP with the new constexpr...
8070 return ReplaceInstUsesWith(GEP, CE);
8071 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008072 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008073 if (!isa<PointerType>(X->getType())) {
8074 // Not interesting. Source pointer must be a cast from pointer.
8075 } else if (HasZeroPointerIndex) {
8076 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8077 // into : GEP [10 x ubyte]* X, long 0, ...
8078 //
8079 // This occurs when the program declares an array extern like "int X[];"
8080 //
8081 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8082 const PointerType *XTy = cast<PointerType>(X->getType());
8083 if (const ArrayType *XATy =
8084 dyn_cast<ArrayType>(XTy->getElementType()))
8085 if (const ArrayType *CATy =
8086 dyn_cast<ArrayType>(CPTy->getElementType()))
8087 if (CATy->getElementType() == XATy->getElementType()) {
8088 // At this point, we know that the cast source type is a pointer
8089 // to an array of the same type as the destination pointer
8090 // array. Because the array type is never stepped over (there
8091 // is a leading zero) we can fold the cast into this GEP.
8092 GEP.setOperand(0, X);
8093 return &GEP;
8094 }
8095 } else if (GEP.getNumOperands() == 2) {
8096 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008097 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8098 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008099 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8100 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8101 if (isa<ArrayType>(SrcElTy) &&
8102 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8103 TD->getTypeSize(ResElTy)) {
8104 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008105 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008106 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008107 // V and GEP are both pointer types --> BitCast
8108 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008109 }
Chris Lattner2a893292005-09-13 18:36:04 +00008110
8111 // Transform things like:
8112 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8113 // (where tmp = 8*tmp2) into:
8114 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8115
8116 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008117 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008118 uint64_t ArrayEltSize =
8119 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8120
8121 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8122 // allow either a mul, shift, or constant here.
8123 Value *NewIdx = 0;
8124 ConstantInt *Scale = 0;
8125 if (ArrayEltSize == 1) {
8126 NewIdx = GEP.getOperand(1);
8127 Scale = ConstantInt::get(NewIdx->getType(), 1);
8128 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008129 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008130 Scale = CI;
8131 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8132 if (Inst->getOpcode() == Instruction::Shl &&
8133 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008134 unsigned ShAmt =
8135 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008136 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008137 NewIdx = Inst->getOperand(0);
8138 } else if (Inst->getOpcode() == Instruction::Mul &&
8139 isa<ConstantInt>(Inst->getOperand(1))) {
8140 Scale = cast<ConstantInt>(Inst->getOperand(1));
8141 NewIdx = Inst->getOperand(0);
8142 }
8143 }
8144
8145 // If the index will be to exactly the right offset with the scale taken
8146 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008147 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008148 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008149 Scale = ConstantInt::get(Scale->getType(),
8150 Scale->getZExtValue() / ArrayEltSize);
8151 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008152 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8153 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008154 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8155 NewIdx = InsertNewInstBefore(Sc, GEP);
8156 }
8157
8158 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008159 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008160 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008161 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008162 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8163 // The NewGEP must be pointer typed, so must the old one -> BitCast
8164 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008165 }
8166 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008167 }
Chris Lattnerca081252001-12-14 16:52:21 +00008168 }
8169
Chris Lattnerca081252001-12-14 16:52:21 +00008170 return 0;
8171}
8172
Chris Lattner1085bdf2002-11-04 16:18:53 +00008173Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8174 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8175 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008176 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8177 const Type *NewTy =
8178 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008179 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008180
8181 // Create and insert the replacement instruction...
8182 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008183 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008184 else {
8185 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008186 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008187 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008188
8189 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008190
Chris Lattner1085bdf2002-11-04 16:18:53 +00008191 // Scan to the end of the allocation instructions, to skip over a block of
8192 // allocas if possible...
8193 //
8194 BasicBlock::iterator It = New;
8195 while (isa<AllocationInst>(*It)) ++It;
8196
8197 // Now that I is pointing to the first non-allocation-inst in the block,
8198 // insert our getelementptr instruction...
8199 //
Reid Spencerc635f472006-12-31 05:48:39 +00008200 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008201 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8202 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008203
8204 // Now make everything use the getelementptr instead of the original
8205 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008206 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008207 } else if (isa<UndefValue>(AI.getArraySize())) {
8208 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008209 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008210
8211 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8212 // Note that we only do this for alloca's, because malloc should allocate and
8213 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008214 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008215 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008216 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8217
Chris Lattner1085bdf2002-11-04 16:18:53 +00008218 return 0;
8219}
8220
Chris Lattner8427bff2003-12-07 01:24:23 +00008221Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8222 Value *Op = FI.getOperand(0);
8223
8224 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8225 if (CastInst *CI = dyn_cast<CastInst>(Op))
8226 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8227 FI.setOperand(0, CI->getOperand(0));
8228 return &FI;
8229 }
8230
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008231 // free undef -> unreachable.
8232 if (isa<UndefValue>(Op)) {
8233 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008234 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008235 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008236 return EraseInstFromFunction(FI);
8237 }
8238
Chris Lattnerf3a36602004-02-28 04:57:37 +00008239 // If we have 'free null' delete the instruction. This can happen in stl code
8240 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008241 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008242 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008243
Chris Lattner8427bff2003-12-07 01:24:23 +00008244 return 0;
8245}
8246
8247
Chris Lattner72684fe2005-01-31 05:51:45 +00008248/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008249static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8250 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008251 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008252
8253 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008254 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008255 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008256
Reid Spencer31a4ef42007-01-22 05:51:25 +00008257 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008258 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008259 // If the source is an array, the code below will not succeed. Check to
8260 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8261 // constants.
8262 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8263 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8264 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008265 Value *Idxs[2];
8266 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8267 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008268 SrcTy = cast<PointerType>(CastOp->getType());
8269 SrcPTy = SrcTy->getElementType();
8270 }
8271
Reid Spencer31a4ef42007-01-22 05:51:25 +00008272 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008273 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008274 // Do not allow turning this into a load of an integer, which is then
8275 // casted to a pointer, this pessimizes pointer analysis a lot.
8276 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008277 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8278 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008279
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008280 // Okay, we are casting from one integer or pointer type to another of
8281 // the same size. Instead of casting the pointer before the load, cast
8282 // the result of the loaded value.
8283 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8284 CI->getName(),
8285 LI.isVolatile()),LI);
8286 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008287 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008288 }
Chris Lattner35e24772004-07-13 01:49:43 +00008289 }
8290 }
8291 return 0;
8292}
8293
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008294/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008295/// from this value cannot trap. If it is not obviously safe to load from the
8296/// specified pointer, we do a quick local scan of the basic block containing
8297/// ScanFrom, to determine if the address is already accessed.
8298static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8299 // If it is an alloca or global variable, it is always safe to load from.
8300 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8301
8302 // Otherwise, be a little bit agressive by scanning the local block where we
8303 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008304 // from/to. If so, the previous load or store would have already trapped,
8305 // so there is no harm doing an extra load (also, CSE will later eliminate
8306 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008307 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8308
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008309 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008310 --BBI;
8311
8312 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8313 if (LI->getOperand(0) == V) return true;
8314 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8315 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008316
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008317 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008318 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008319}
8320
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008321Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8322 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008323
Chris Lattnera9d84e32005-05-01 04:24:53 +00008324 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008325 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008326 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8327 return Res;
8328
8329 // None of the following transforms are legal for volatile loads.
8330 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008331
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008332 if (&LI.getParent()->front() != &LI) {
8333 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008334 // If the instruction immediately before this is a store to the same
8335 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008336 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8337 if (SI->getOperand(1) == LI.getOperand(0))
8338 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008339 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8340 if (LIB->getOperand(0) == LI.getOperand(0))
8341 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008342 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008343
8344 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8345 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8346 isa<UndefValue>(GEPI->getOperand(0))) {
8347 // Insert a new store to null instruction before the load to indicate
8348 // that this code is not reachable. We do this instead of inserting
8349 // an unreachable instruction directly because we cannot modify the
8350 // CFG.
8351 new StoreInst(UndefValue::get(LI.getType()),
8352 Constant::getNullValue(Op->getType()), &LI);
8353 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8354 }
8355
Chris Lattner81a7a232004-10-16 18:11:37 +00008356 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008357 // load null/undef -> undef
8358 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008359 // Insert a new store to null instruction before the load to indicate that
8360 // this code is not reachable. We do this instead of inserting an
8361 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008362 new StoreInst(UndefValue::get(LI.getType()),
8363 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008364 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008365 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008366
Chris Lattner81a7a232004-10-16 18:11:37 +00008367 // Instcombine load (constant global) into the value loaded.
8368 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008369 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008370 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008371
Chris Lattner81a7a232004-10-16 18:11:37 +00008372 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8374 if (CE->getOpcode() == Instruction::GetElementPtr) {
8375 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008376 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008377 if (Constant *V =
8378 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008379 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008380 if (CE->getOperand(0)->isNullValue()) {
8381 // Insert a new store to null instruction before the load to indicate
8382 // that this code is not reachable. We do this instead of inserting
8383 // an unreachable instruction directly because we cannot modify the
8384 // CFG.
8385 new StoreInst(UndefValue::get(LI.getType()),
8386 Constant::getNullValue(Op->getType()), &LI);
8387 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8388 }
8389
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008390 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008391 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8392 return Res;
8393 }
8394 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008395
Chris Lattnera9d84e32005-05-01 04:24:53 +00008396 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008397 // Change select and PHI nodes to select values instead of addresses: this
8398 // helps alias analysis out a lot, allows many others simplifications, and
8399 // exposes redundancy in the code.
8400 //
8401 // Note that we cannot do the transformation unless we know that the
8402 // introduced loads cannot trap! Something like this is valid as long as
8403 // the condition is always false: load (select bool %C, int* null, int* %G),
8404 // but it would not be valid if we transformed it to load from null
8405 // unconditionally.
8406 //
8407 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8408 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008409 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8410 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008411 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008412 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008413 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008414 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008415 return new SelectInst(SI->getCondition(), V1, V2);
8416 }
8417
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008418 // load (select (cond, null, P)) -> load P
8419 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8420 if (C->isNullValue()) {
8421 LI.setOperand(0, SI->getOperand(2));
8422 return &LI;
8423 }
8424
8425 // load (select (cond, P, null)) -> load P
8426 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8427 if (C->isNullValue()) {
8428 LI.setOperand(0, SI->getOperand(1));
8429 return &LI;
8430 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008431 }
8432 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008433 return 0;
8434}
8435
Reid Spencere928a152007-01-19 21:20:31 +00008436/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008437/// when possible.
8438static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8439 User *CI = cast<User>(SI.getOperand(1));
8440 Value *CastOp = CI->getOperand(0);
8441
8442 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8443 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8444 const Type *SrcPTy = SrcTy->getElementType();
8445
Reid Spencer31a4ef42007-01-22 05:51:25 +00008446 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008447 // If the source is an array, the code below will not succeed. Check to
8448 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8449 // constants.
8450 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8451 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8452 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008453 Value* Idxs[2];
8454 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8455 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008456 SrcTy = cast<PointerType>(CastOp->getType());
8457 SrcPTy = SrcTy->getElementType();
8458 }
8459
Reid Spencer9a4bed02007-01-20 23:35:48 +00008460 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8461 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8462 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008463
8464 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008465 // the same size. Instead of casting the pointer before
8466 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008467 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008468 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008469 Instruction::CastOps opcode = Instruction::BitCast;
8470 const Type* CastSrcTy = SIOp0->getType();
8471 const Type* CastDstTy = SrcPTy;
8472 if (isa<PointerType>(CastDstTy)) {
8473 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008474 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008475 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008476 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008477 opcode = Instruction::PtrToInt;
8478 }
8479 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008480 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008481 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008482 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008483 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8484 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008485 return new StoreInst(NewCast, CastOp);
8486 }
8487 }
8488 }
8489 return 0;
8490}
8491
Chris Lattner31f486c2005-01-31 05:36:43 +00008492Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8493 Value *Val = SI.getOperand(0);
8494 Value *Ptr = SI.getOperand(1);
8495
8496 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008497 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008498 ++NumCombined;
8499 return 0;
8500 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008501
8502 // If the RHS is an alloca with a single use, zapify the store, making the
8503 // alloca dead.
8504 if (Ptr->hasOneUse()) {
8505 if (isa<AllocaInst>(Ptr)) {
8506 EraseInstFromFunction(SI);
8507 ++NumCombined;
8508 return 0;
8509 }
8510
8511 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8512 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8513 GEP->getOperand(0)->hasOneUse()) {
8514 EraseInstFromFunction(SI);
8515 ++NumCombined;
8516 return 0;
8517 }
8518 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008519
Chris Lattner5997cf92006-02-08 03:25:32 +00008520 // Do really simple DSE, to catch cases where there are several consequtive
8521 // stores to the same location, separated by a few arithmetic operations. This
8522 // situation often occurs with bitfield accesses.
8523 BasicBlock::iterator BBI = &SI;
8524 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8525 --ScanInsts) {
8526 --BBI;
8527
8528 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8529 // Prev store isn't volatile, and stores to the same location?
8530 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8531 ++NumDeadStore;
8532 ++BBI;
8533 EraseInstFromFunction(*PrevSI);
8534 continue;
8535 }
8536 break;
8537 }
8538
Chris Lattnerdab43b22006-05-26 19:19:20 +00008539 // If this is a load, we have to stop. However, if the loaded value is from
8540 // the pointer we're loading and is producing the pointer we're storing,
8541 // then *this* store is dead (X = load P; store X -> P).
8542 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8543 if (LI == Val && LI->getOperand(0) == Ptr) {
8544 EraseInstFromFunction(SI);
8545 ++NumCombined;
8546 return 0;
8547 }
8548 // Otherwise, this is a load from some other location. Stores before it
8549 // may not be dead.
8550 break;
8551 }
8552
Chris Lattner5997cf92006-02-08 03:25:32 +00008553 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008554 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008555 break;
8556 }
8557
8558
8559 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008560
8561 // store X, null -> turns into 'unreachable' in SimplifyCFG
8562 if (isa<ConstantPointerNull>(Ptr)) {
8563 if (!isa<UndefValue>(Val)) {
8564 SI.setOperand(0, UndefValue::get(Val->getType()));
8565 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008566 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008567 ++NumCombined;
8568 }
8569 return 0; // Do not modify these!
8570 }
8571
8572 // store undef, Ptr -> noop
8573 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008574 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008575 ++NumCombined;
8576 return 0;
8577 }
8578
Chris Lattner72684fe2005-01-31 05:51:45 +00008579 // If the pointer destination is a cast, see if we can fold the cast into the
8580 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008581 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008582 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8583 return Res;
8584 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008585 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008586 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8587 return Res;
8588
Chris Lattner219175c2005-09-12 23:23:25 +00008589
8590 // If this store is the last instruction in the basic block, and if the block
8591 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008592 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008593 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8594 if (BI->isUnconditional()) {
8595 // Check to see if the successor block has exactly two incoming edges. If
8596 // so, see if the other predecessor contains a store to the same location.
8597 // if so, insert a PHI node (if needed) and move the stores down.
8598 BasicBlock *Dest = BI->getSuccessor(0);
8599
8600 pred_iterator PI = pred_begin(Dest);
8601 BasicBlock *Other = 0;
8602 if (*PI != BI->getParent())
8603 Other = *PI;
8604 ++PI;
8605 if (PI != pred_end(Dest)) {
8606 if (*PI != BI->getParent())
8607 if (Other)
8608 Other = 0;
8609 else
8610 Other = *PI;
8611 if (++PI != pred_end(Dest))
8612 Other = 0;
8613 }
8614 if (Other) { // If only one other pred...
8615 BBI = Other->getTerminator();
8616 // Make sure this other block ends in an unconditional branch and that
8617 // there is an instruction before the branch.
8618 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8619 BBI != Other->begin()) {
8620 --BBI;
8621 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8622
8623 // If this instruction is a store to the same location.
8624 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8625 // Okay, we know we can perform this transformation. Insert a PHI
8626 // node now if we need it.
8627 Value *MergedVal = OtherStore->getOperand(0);
8628 if (MergedVal != SI.getOperand(0)) {
8629 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8630 PN->reserveOperandSpace(2);
8631 PN->addIncoming(SI.getOperand(0), SI.getParent());
8632 PN->addIncoming(OtherStore->getOperand(0), Other);
8633 MergedVal = InsertNewInstBefore(PN, Dest->front());
8634 }
8635
8636 // Advance to a place where it is safe to insert the new store and
8637 // insert it.
8638 BBI = Dest->begin();
8639 while (isa<PHINode>(BBI)) ++BBI;
8640 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8641 OtherStore->isVolatile()), *BBI);
8642
8643 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008644 EraseInstFromFunction(SI);
8645 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008646 ++NumCombined;
8647 return 0;
8648 }
8649 }
8650 }
8651 }
8652
Chris Lattner31f486c2005-01-31 05:36:43 +00008653 return 0;
8654}
8655
8656
Chris Lattner9eef8a72003-06-04 04:46:00 +00008657Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8658 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008659 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008660 BasicBlock *TrueDest;
8661 BasicBlock *FalseDest;
8662 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8663 !isa<Constant>(X)) {
8664 // Swap Destinations and condition...
8665 BI.setCondition(X);
8666 BI.setSuccessor(0, FalseDest);
8667 BI.setSuccessor(1, TrueDest);
8668 return &BI;
8669 }
8670
Reid Spencer266e42b2006-12-23 06:05:41 +00008671 // Cannonicalize fcmp_one -> fcmp_oeq
8672 FCmpInst::Predicate FPred; Value *Y;
8673 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8674 TrueDest, FalseDest)))
8675 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8676 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8677 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008678 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008679 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8680 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008681 // Swap Destinations and condition...
8682 BI.setCondition(NewSCC);
8683 BI.setSuccessor(0, FalseDest);
8684 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008685 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008686 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008687 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008688 return &BI;
8689 }
8690
8691 // Cannonicalize icmp_ne -> icmp_eq
8692 ICmpInst::Predicate IPred;
8693 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8694 TrueDest, FalseDest)))
8695 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8696 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8697 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8698 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008699 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008700 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8701 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008702 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008703 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008704 BI.setSuccessor(0, FalseDest);
8705 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008706 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008707 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008708 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008709 return &BI;
8710 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008711
Chris Lattner9eef8a72003-06-04 04:46:00 +00008712 return 0;
8713}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008714
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008715Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8716 Value *Cond = SI.getCondition();
8717 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8718 if (I->getOpcode() == Instruction::Add)
8719 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8720 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8721 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008722 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008723 AddRHS));
8724 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008725 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008726 return &SI;
8727 }
8728 }
8729 return 0;
8730}
8731
Chris Lattner6bc98652006-03-05 00:22:33 +00008732/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8733/// is to leave as a vector operation.
8734static bool CheapToScalarize(Value *V, bool isConstant) {
8735 if (isa<ConstantAggregateZero>(V))
8736 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008737 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008738 if (isConstant) return true;
8739 // If all elts are the same, we can extract.
8740 Constant *Op0 = C->getOperand(0);
8741 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8742 if (C->getOperand(i) != Op0)
8743 return false;
8744 return true;
8745 }
8746 Instruction *I = dyn_cast<Instruction>(V);
8747 if (!I) return false;
8748
8749 // Insert element gets simplified to the inserted element or is deleted if
8750 // this is constant idx extract element and its a constant idx insertelt.
8751 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8752 isa<ConstantInt>(I->getOperand(2)))
8753 return true;
8754 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8755 return true;
8756 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8757 if (BO->hasOneUse() &&
8758 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8759 CheapToScalarize(BO->getOperand(1), isConstant)))
8760 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008761 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8762 if (CI->hasOneUse() &&
8763 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8764 CheapToScalarize(CI->getOperand(1), isConstant)))
8765 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008766
8767 return false;
8768}
8769
Chris Lattner945e4372007-02-14 05:52:17 +00008770/// Read and decode a shufflevector mask.
8771///
8772/// It turns undef elements into values that are larger than the number of
8773/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008774static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8775 unsigned NElts = SVI->getType()->getNumElements();
8776 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8777 return std::vector<unsigned>(NElts, 0);
8778 if (isa<UndefValue>(SVI->getOperand(2)))
8779 return std::vector<unsigned>(NElts, 2*NElts);
8780
8781 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008782 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008783 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8784 if (isa<UndefValue>(CP->getOperand(i)))
8785 Result.push_back(NElts*2); // undef -> 8
8786 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008787 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008788 return Result;
8789}
8790
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008791/// FindScalarElement - Given a vector and an element number, see if the scalar
8792/// value is already around as a register, for example if it were inserted then
8793/// extracted from the vector.
8794static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008795 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8796 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008797 unsigned Width = PTy->getNumElements();
8798 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008799 return UndefValue::get(PTy->getElementType());
8800
8801 if (isa<UndefValue>(V))
8802 return UndefValue::get(PTy->getElementType());
8803 else if (isa<ConstantAggregateZero>(V))
8804 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008805 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008806 return CP->getOperand(EltNo);
8807 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8808 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008809 if (!isa<ConstantInt>(III->getOperand(2)))
8810 return 0;
8811 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008812
8813 // If this is an insert to the element we are looking for, return the
8814 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008815 if (EltNo == IIElt)
8816 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008817
8818 // Otherwise, the insertelement doesn't modify the value, recurse on its
8819 // vector input.
8820 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008821 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008822 unsigned InEl = getShuffleMask(SVI)[EltNo];
8823 if (InEl < Width)
8824 return FindScalarElement(SVI->getOperand(0), InEl);
8825 else if (InEl < Width*2)
8826 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8827 else
8828 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008829 }
8830
8831 // Otherwise, we don't know.
8832 return 0;
8833}
8834
Robert Bocchinoa8352962006-01-13 22:48:06 +00008835Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008836
Chris Lattner92346c32006-03-31 18:25:14 +00008837 // If packed val is undef, replace extract with scalar undef.
8838 if (isa<UndefValue>(EI.getOperand(0)))
8839 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8840
8841 // If packed val is constant 0, replace extract with scalar 0.
8842 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8843 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8844
Reid Spencerd84d35b2007-02-15 02:26:10 +00008845 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008846 // If packed val is constant with uniform operands, replace EI
8847 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008848 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008849 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008850 if (C->getOperand(i) != op0) {
8851 op0 = 0;
8852 break;
8853 }
8854 if (op0)
8855 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008856 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008857
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008858 // If extracting a specified index from the vector, see if we can recursively
8859 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008860 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008861 // This instruction only demands the single element from the input vector.
8862 // If the input vector has a single use, simplify it based on this use
8863 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008864 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008865 if (EI.getOperand(0)->hasOneUse()) {
8866 uint64_t UndefElts;
8867 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008868 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008869 UndefElts)) {
8870 EI.setOperand(0, V);
8871 return &EI;
8872 }
8873 }
8874
Reid Spencere0fc4df2006-10-20 07:07:24 +00008875 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008876 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008877 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008878
Chris Lattner83f65782006-05-25 22:53:38 +00008879 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008880 if (I->hasOneUse()) {
8881 // Push extractelement into predecessor operation if legal and
8882 // profitable to do so
8883 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008884 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8885 if (CheapToScalarize(BO, isConstantElt)) {
8886 ExtractElementInst *newEI0 =
8887 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8888 EI.getName()+".lhs");
8889 ExtractElementInst *newEI1 =
8890 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8891 EI.getName()+".rhs");
8892 InsertNewInstBefore(newEI0, EI);
8893 InsertNewInstBefore(newEI1, EI);
8894 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8895 }
Reid Spencerde46e482006-11-02 20:25:50 +00008896 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008897 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008898 PointerType::get(EI.getType()), EI);
8899 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008900 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008901 InsertNewInstBefore(GEP, EI);
8902 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008903 }
8904 }
8905 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8906 // Extracting the inserted element?
8907 if (IE->getOperand(2) == EI.getOperand(1))
8908 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8909 // If the inserted and extracted elements are constants, they must not
8910 // be the same value, extract from the pre-inserted value instead.
8911 if (isa<Constant>(IE->getOperand(2)) &&
8912 isa<Constant>(EI.getOperand(1))) {
8913 AddUsesToWorkList(EI);
8914 EI.setOperand(0, IE->getOperand(0));
8915 return &EI;
8916 }
8917 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8918 // If this is extracting an element from a shufflevector, figure out where
8919 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008920 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8921 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008922 Value *Src;
8923 if (SrcIdx < SVI->getType()->getNumElements())
8924 Src = SVI->getOperand(0);
8925 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8926 SrcIdx -= SVI->getType()->getNumElements();
8927 Src = SVI->getOperand(1);
8928 } else {
8929 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008930 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008931 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008932 }
8933 }
Chris Lattner83f65782006-05-25 22:53:38 +00008934 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008935 return 0;
8936}
8937
Chris Lattner90951862006-04-16 00:51:47 +00008938/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8939/// elements from either LHS or RHS, return the shuffle mask and true.
8940/// Otherwise, return false.
8941static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8942 std::vector<Constant*> &Mask) {
8943 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8944 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008945 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008946
8947 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008948 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008949 return true;
8950 } else if (V == LHS) {
8951 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008952 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008953 return true;
8954 } else if (V == RHS) {
8955 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008956 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008957 return true;
8958 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8959 // If this is an insert of an extract from some other vector, include it.
8960 Value *VecOp = IEI->getOperand(0);
8961 Value *ScalarOp = IEI->getOperand(1);
8962 Value *IdxOp = IEI->getOperand(2);
8963
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008964 if (!isa<ConstantInt>(IdxOp))
8965 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008966 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008967
8968 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8969 // Okay, we can handle this if the vector we are insertinting into is
8970 // transitively ok.
8971 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8972 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008973 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008974 return true;
8975 }
8976 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8977 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008978 EI->getOperand(0)->getType() == V->getType()) {
8979 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008980 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008981
8982 // This must be extracting from either LHS or RHS.
8983 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8984 // Okay, we can handle this if the vector we are insertinting into is
8985 // transitively ok.
8986 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8987 // If so, update the mask to reflect the inserted value.
8988 if (EI->getOperand(0) == LHS) {
8989 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008990 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008991 } else {
8992 assert(EI->getOperand(0) == RHS);
8993 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008994 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008995
8996 }
8997 return true;
8998 }
8999 }
9000 }
9001 }
9002 }
9003 // TODO: Handle shufflevector here!
9004
9005 return false;
9006}
9007
9008/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9009/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9010/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009011static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009012 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009013 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009014 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009015 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009016 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009017
9018 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009019 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009020 return V;
9021 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009022 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009023 return V;
9024 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9025 // If this is an insert of an extract from some other vector, include it.
9026 Value *VecOp = IEI->getOperand(0);
9027 Value *ScalarOp = IEI->getOperand(1);
9028 Value *IdxOp = IEI->getOperand(2);
9029
9030 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9031 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9032 EI->getOperand(0)->getType() == V->getType()) {
9033 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009034 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9035 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009036
9037 // Either the extracted from or inserted into vector must be RHSVec,
9038 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009039 if (EI->getOperand(0) == RHS || RHS == 0) {
9040 RHS = EI->getOperand(0);
9041 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009042 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009043 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009044 return V;
9045 }
9046
Chris Lattner90951862006-04-16 00:51:47 +00009047 if (VecOp == RHS) {
9048 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009049 // Everything but the extracted element is replaced with the RHS.
9050 for (unsigned i = 0; i != NumElts; ++i) {
9051 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009052 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009053 }
9054 return V;
9055 }
Chris Lattner90951862006-04-16 00:51:47 +00009056
9057 // If this insertelement is a chain that comes from exactly these two
9058 // vectors, return the vector and the effective shuffle.
9059 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9060 return EI->getOperand(0);
9061
Chris Lattner39fac442006-04-15 01:39:45 +00009062 }
9063 }
9064 }
Chris Lattner90951862006-04-16 00:51:47 +00009065 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009066
9067 // Otherwise, can't do anything fancy. Return an identity vector.
9068 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009069 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009070 return V;
9071}
9072
9073Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9074 Value *VecOp = IE.getOperand(0);
9075 Value *ScalarOp = IE.getOperand(1);
9076 Value *IdxOp = IE.getOperand(2);
9077
9078 // If the inserted element was extracted from some other vector, and if the
9079 // indexes are constant, try to turn this into a shufflevector operation.
9080 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9081 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9082 EI->getOperand(0)->getType() == IE.getType()) {
9083 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009084 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9085 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009086
9087 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9088 return ReplaceInstUsesWith(IE, VecOp);
9089
9090 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9091 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9092
9093 // If we are extracting a value from a vector, then inserting it right
9094 // back into the same place, just use the input vector.
9095 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9096 return ReplaceInstUsesWith(IE, VecOp);
9097
9098 // We could theoretically do this for ANY input. However, doing so could
9099 // turn chains of insertelement instructions into a chain of shufflevector
9100 // instructions, and right now we do not merge shufflevectors. As such,
9101 // only do this in a situation where it is clear that there is benefit.
9102 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9103 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9104 // the values of VecOp, except then one read from EIOp0.
9105 // Build a new shuffle mask.
9106 std::vector<Constant*> Mask;
9107 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009108 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009109 else {
9110 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009111 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009112 NumVectorElts));
9113 }
Reid Spencerc635f472006-12-31 05:48:39 +00009114 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009115 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009116 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009117 }
9118
9119 // If this insertelement isn't used by some other insertelement, turn it
9120 // (and any insertelements it points to), into one big shuffle.
9121 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9122 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009123 Value *RHS = 0;
9124 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9125 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9126 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009127 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009128 }
9129 }
9130 }
9131
9132 return 0;
9133}
9134
9135
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009136Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9137 Value *LHS = SVI.getOperand(0);
9138 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009139 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009140
9141 bool MadeChange = false;
9142
Chris Lattner2deeaea2006-10-05 06:55:50 +00009143 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009144 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009145 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9146
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009147 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009148 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009149 if (isa<UndefValue>(SVI.getOperand(1))) {
9150 // Scan to see if there are any references to the RHS. If so, replace them
9151 // with undef element refs and set MadeChange to true.
9152 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9153 if (Mask[i] >= e && Mask[i] != 2*e) {
9154 Mask[i] = 2*e;
9155 MadeChange = true;
9156 }
9157 }
9158
9159 if (MadeChange) {
9160 // Remap any references to RHS to use LHS.
9161 std::vector<Constant*> Elts;
9162 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9163 if (Mask[i] == 2*e)
9164 Elts.push_back(UndefValue::get(Type::Int32Ty));
9165 else
9166 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9167 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009168 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009169 }
9170 }
Chris Lattner39fac442006-04-15 01:39:45 +00009171
Chris Lattner12249be2006-05-25 23:48:38 +00009172 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9173 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9174 if (LHS == RHS || isa<UndefValue>(LHS)) {
9175 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009176 // shuffle(undef,undef,mask) -> undef.
9177 return ReplaceInstUsesWith(SVI, LHS);
9178 }
9179
Chris Lattner12249be2006-05-25 23:48:38 +00009180 // Remap any references to RHS to use LHS.
9181 std::vector<Constant*> Elts;
9182 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009183 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009184 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009185 else {
9186 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9187 (Mask[i] < e && isa<UndefValue>(LHS)))
9188 Mask[i] = 2*e; // Turn into undef.
9189 else
9190 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009191 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009192 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009193 }
Chris Lattner12249be2006-05-25 23:48:38 +00009194 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009195 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009196 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009197 LHS = SVI.getOperand(0);
9198 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009199 MadeChange = true;
9200 }
9201
Chris Lattner0e477162006-05-26 00:29:06 +00009202 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009203 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009204
Chris Lattner12249be2006-05-25 23:48:38 +00009205 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9206 if (Mask[i] >= e*2) continue; // Ignore undef values.
9207 // Is this an identity shuffle of the LHS value?
9208 isLHSID &= (Mask[i] == i);
9209
9210 // Is this an identity shuffle of the RHS value?
9211 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009212 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009213
Chris Lattner12249be2006-05-25 23:48:38 +00009214 // Eliminate identity shuffles.
9215 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9216 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009217
Chris Lattner0e477162006-05-26 00:29:06 +00009218 // If the LHS is a shufflevector itself, see if we can combine it with this
9219 // one without producing an unusual shuffle. Here we are really conservative:
9220 // we are absolutely afraid of producing a shuffle mask not in the input
9221 // program, because the code gen may not be smart enough to turn a merged
9222 // shuffle into two specific shuffles: it may produce worse code. As such,
9223 // we only merge two shuffles if the result is one of the two input shuffle
9224 // masks. In this case, merging the shuffles just removes one instruction,
9225 // which we know is safe. This is good for things like turning:
9226 // (splat(splat)) -> splat.
9227 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9228 if (isa<UndefValue>(RHS)) {
9229 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9230
9231 std::vector<unsigned> NewMask;
9232 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9233 if (Mask[i] >= 2*e)
9234 NewMask.push_back(2*e);
9235 else
9236 NewMask.push_back(LHSMask[Mask[i]]);
9237
9238 // If the result mask is equal to the src shuffle or this shuffle mask, do
9239 // the replacement.
9240 if (NewMask == LHSMask || NewMask == Mask) {
9241 std::vector<Constant*> Elts;
9242 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9243 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009244 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009245 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009246 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009247 }
9248 }
9249 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9250 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009251 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009252 }
9253 }
9254 }
Chris Lattner4284f642007-01-30 22:32:46 +00009255
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009256 return MadeChange ? &SVI : 0;
9257}
9258
9259
Robert Bocchinoa8352962006-01-13 22:48:06 +00009260
Chris Lattner39c98bb2004-12-08 23:43:58 +00009261
9262/// TryToSinkInstruction - Try to move the specified instruction from its
9263/// current block into the beginning of DestBlock, which can only happen if it's
9264/// safe to move the instruction past all of the instructions between it and the
9265/// end of its block.
9266static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9267 assert(I->hasOneUse() && "Invariants didn't hold!");
9268
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009269 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9270 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009271
Chris Lattner39c98bb2004-12-08 23:43:58 +00009272 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009273 if (isa<AllocaInst>(I) && I->getParent() ==
9274 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009275 return false;
9276
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009277 // We can only sink load instructions if there is nothing between the load and
9278 // the end of block that could change the value.
9279 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009280 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9281 Scan != E; ++Scan)
9282 if (Scan->mayWriteToMemory())
9283 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009284 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009285
9286 BasicBlock::iterator InsertPos = DestBlock->begin();
9287 while (isa<PHINode>(InsertPos)) ++InsertPos;
9288
Chris Lattner9f269e42005-08-08 19:11:57 +00009289 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009290 ++NumSunkInst;
9291 return true;
9292}
9293
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009294
9295/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9296/// all reachable code to the worklist.
9297///
9298/// This has a couple of tricks to make the code faster and more powerful. In
9299/// particular, we constant fold and DCE instructions as we go, to avoid adding
9300/// them to the worklist (this significantly speeds up instcombine on code where
9301/// many instructions are dead or constant). Additionally, if we find a branch
9302/// whose condition is a known constant, we only visit the reachable successors.
9303///
9304static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009305 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009306 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009307 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009308 std::vector<BasicBlock*> Worklist;
9309 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009310
Chris Lattner12b89cc2007-03-23 19:17:18 +00009311 while (!Worklist.empty()) {
9312 BB = Worklist.back();
9313 Worklist.pop_back();
9314
9315 // We have now visited this block! If we've already been here, ignore it.
9316 if (!Visited.insert(BB)) continue;
9317
9318 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9319 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009320
Chris Lattner12b89cc2007-03-23 19:17:18 +00009321 // DCE instruction if trivially dead.
9322 if (isInstructionTriviallyDead(Inst)) {
9323 ++NumDeadInst;
9324 DOUT << "IC: DCE: " << *Inst;
9325 Inst->eraseFromParent();
9326 continue;
9327 }
9328
9329 // ConstantProp instruction if trivially constant.
9330 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9331 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9332 Inst->replaceAllUsesWith(C);
9333 ++NumConstProp;
9334 Inst->eraseFromParent();
9335 continue;
9336 }
9337
9338 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009339 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009340
9341 // Recursively visit successors. If this is a branch or switch on a
9342 // constant, only visit the reachable successor.
9343 TerminatorInst *TI = BB->getTerminator();
9344 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9345 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9346 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9347 Worklist.push_back(BI->getSuccessor(!CondVal));
9348 continue;
9349 }
9350 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9351 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9352 // See if this is an explicit destination.
9353 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9354 if (SI->getCaseValue(i) == Cond) {
9355 Worklist.push_back(SI->getSuccessor(i));
9356 continue;
9357 }
9358
9359 // Otherwise it is the default destination.
9360 Worklist.push_back(SI->getSuccessor(0));
9361 continue;
9362 }
9363 }
9364
9365 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9366 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009367 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009368}
9369
Chris Lattner960a5432007-03-03 02:04:50 +00009370bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009371 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009372 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009373
9374 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9375 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009376
Chris Lattner4ed40f72005-07-07 20:40:38 +00009377 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009378 // Do a depth-first traversal of the function, populate the worklist with
9379 // the reachable instructions. Ignore blocks that are not reachable. Keep
9380 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009381 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009382 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009383
Chris Lattner4ed40f72005-07-07 20:40:38 +00009384 // Do a quick scan over the function. If we find any blocks that are
9385 // unreachable, remove any instructions inside of them. This prevents
9386 // the instcombine code from having to deal with some bad special cases.
9387 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9388 if (!Visited.count(BB)) {
9389 Instruction *Term = BB->getTerminator();
9390 while (Term != BB->begin()) { // Remove instrs bottom-up
9391 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009392
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009393 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009394 ++NumDeadInst;
9395
9396 if (!I->use_empty())
9397 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9398 I->eraseFromParent();
9399 }
9400 }
9401 }
Chris Lattnerca081252001-12-14 16:52:21 +00009402
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009403 while (!Worklist.empty()) {
9404 Instruction *I = RemoveOneFromWorkList();
9405 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009406
Chris Lattner1443bc52006-05-11 17:11:52 +00009407 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009408 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009409 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009410 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009411 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009412 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009413
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009414 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009415
9416 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009417 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009418 continue;
9419 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009420
Chris Lattner1443bc52006-05-11 17:11:52 +00009421 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009422 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009423 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009424
Chris Lattner1443bc52006-05-11 17:11:52 +00009425 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009426 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009427 ReplaceInstUsesWith(*I, C);
9428
Chris Lattner99f48c62002-09-02 04:59:56 +00009429 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009430 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009431 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009432 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009433 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009434
Chris Lattner39c98bb2004-12-08 23:43:58 +00009435 // See if we can trivially sink this instruction to a successor basic block.
9436 if (I->hasOneUse()) {
9437 BasicBlock *BB = I->getParent();
9438 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9439 if (UserParent != BB) {
9440 bool UserIsSuccessor = false;
9441 // See if the user is one of our successors.
9442 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9443 if (*SI == UserParent) {
9444 UserIsSuccessor = true;
9445 break;
9446 }
9447
9448 // If the user is one of our immediate successors, and if that successor
9449 // only has us as a predecessors (we'd have to split the critical edge
9450 // otherwise), we can keep going.
9451 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9452 next(pred_begin(UserParent)) == pred_end(UserParent))
9453 // Okay, the CFG is simple enough, try to sink this instruction.
9454 Changed |= TryToSinkInstruction(I, UserParent);
9455 }
9456 }
9457
Chris Lattnerca081252001-12-14 16:52:21 +00009458 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009459#ifndef NDEBUG
9460 std::string OrigI;
9461#endif
9462 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009463 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009464 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009465 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009466 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009467 DOUT << "IC: Old = " << *I
9468 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009469
Chris Lattner396dbfe2004-06-09 05:08:07 +00009470 // Everything uses the new instruction now.
9471 I->replaceAllUsesWith(Result);
9472
9473 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009474 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009475 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009476
Chris Lattner6e0123b2007-02-11 01:23:03 +00009477 // Move the name to the new instruction first.
9478 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009479
9480 // Insert the new instruction into the basic block...
9481 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009482 BasicBlock::iterator InsertPos = I;
9483
9484 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9485 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9486 ++InsertPos;
9487
9488 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009489
Chris Lattner63d75af2004-05-01 23:27:23 +00009490 // Make sure that we reprocess all operands now that we reduced their
9491 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009492 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009493
Chris Lattner396dbfe2004-06-09 05:08:07 +00009494 // Instructions can end up on the worklist more than once. Make sure
9495 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009496 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009497
9498 // Erase the old instruction.
9499 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009500 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009501#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009502 DOUT << "IC: Mod = " << OrigI
9503 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009504#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009505
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009506 // If the instruction was modified, it's possible that it is now dead.
9507 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009508 if (isInstructionTriviallyDead(I)) {
9509 // Make sure we process all operands now that we are reducing their
9510 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009511 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009512
Chris Lattner63d75af2004-05-01 23:27:23 +00009513 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009514 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009515 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009516 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009517 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009518 AddToWorkList(I);
9519 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009520 }
Chris Lattner053c0932002-05-14 15:24:07 +00009521 }
Chris Lattner260ab202002-04-18 17:39:14 +00009522 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009523 }
9524 }
9525
Chris Lattner960a5432007-03-03 02:04:50 +00009526 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009527 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009528}
9529
Chris Lattner960a5432007-03-03 02:04:50 +00009530
9531bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009532 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9533
Chris Lattner960a5432007-03-03 02:04:50 +00009534 bool EverMadeChange = false;
9535
9536 // Iterate while there is work to do.
9537 unsigned Iteration = 0;
9538 while (DoOneIteration(F, Iteration++))
9539 EverMadeChange = true;
9540 return EverMadeChange;
9541}
9542
Brian Gaeke38b79e82004-07-27 17:43:21 +00009543FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009544 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009545}
Brian Gaeke960707c2003-11-11 22:41:34 +00009546