blob: abb279f7740e592e5db9ce12857382248470d228 [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 Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %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 Spencer3f4e6e82007-02-04 00:40:42 +000059#include <set>
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
Chris Lattner0157e7f2006-02-11 09:31:47 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000325
Chris Lattner2deeaea2006-10-05 06:55:50 +0000326 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327 uint64_t &UndefElts, unsigned Depth = 0);
328
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000329 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330 // PHI node as operand #0, see if we can fold the instruction into the PHI
331 // (which is only possible if all operands to the PHI are constants).
332 Instruction *FoldOpIntoPhi(Instruction &I);
333
Chris Lattner7515cab2004-11-14 19:13:23 +0000334 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335 // operator and they all are only used by the PHI, PHI together their
336 // inputs, and do the operation once, to the result of the PHI.
337 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000338 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339
340
Zhou Sheng75b871f2007-01-11 12:24:14 +0000341 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000343
Zhou Sheng75b871f2007-01-11 12:24:14 +0000344 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000345 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000346 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000347 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000348 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000349 Instruction *MatchBSwap(BinaryOperator &I);
350
Reid Spencer74a528b2006-12-13 18:21:21 +0000351 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000352 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000353
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000354 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000355}
356
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000357// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000358// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359static unsigned getComplexity(Value *V) {
360 if (isa<Instruction>(V)) {
361 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000362 return 3;
363 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000365 if (isa<Argument>(V)) return 3;
366 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000367}
Chris Lattner260ab202002-04-18 17:39:14 +0000368
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369// isOnlyUse - Return true if this instruction will be deleted if we stop using
370// it.
371static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000372 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373}
374
Chris Lattnere79e8542004-02-23 06:38:22 +0000375// getPromotedType - Return the specified type promoted as it would be to pass
376// though a va_arg area...
377static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000378 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379 if (ITy->getBitWidth() < 32)
380 return Type::Int32Ty;
381 } else if (Ty == Type::FloatTy)
382 return Type::DoubleTy;
383 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000384}
385
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000386/// getBitCastOperand - If the specified operand is a CastInst or a constant
387/// expression bitcast, return the operand value, otherwise return null.
388static Value *getBitCastOperand(Value *V) {
389 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000390 return I->getOperand(0);
391 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000393 return CE->getOperand(0);
394 return 0;
395}
396
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397/// This function is a wrapper around CastInst::isEliminableCastPair. It
398/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399static Instruction::CastOps
400isEliminableCastPair(
401 const CastInst *CI, ///< The first cast instruction
402 unsigned opcode, ///< The opcode of the second cast instruction
403 const Type *DstTy, ///< The target type for the second cast instruction
404 TargetData *TD ///< The target data for pointer size
405) {
406
407 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
408 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000410 // Get the opcodes of the two Cast instructions
411 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000414 return Instruction::CastOps(
415 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000417}
418
419/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420/// in any code being generated. It does not require codegen if V is simple
421/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000422static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
423 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000424 if (V->getType() == Ty || isa<Constant>(V)) return false;
425
Chris Lattner99155be2006-05-25 23:24:33 +0000426 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000427 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000428 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 return false;
430 return true;
431}
432
433/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434/// InsertBefore instruction. This is specialized a bit to avoid inserting
435/// casts that are known to not do anything...
436///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000437Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000439 Instruction *InsertBefore) {
440 if (V->getType() == DestTy) return V;
441 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000442 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445}
446
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000447// SimplifyCommutative - This performs a few simplifications for commutative
448// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000449//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000450// 1. Order operands such that they are listed from right (least complex) to
451// left (most complex). This puts constants before unary operators before
452// binary operators.
453//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000454// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000457bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 bool Changed = false;
459 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462 if (!I.isAssociative()) return Changed;
463 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000467 Constant *Folded = ConstantExpr::get(I.getOpcode(),
468 cast<Constant>(I.getOperand(1)),
469 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000470 I.setOperand(0, Op->getOperand(0));
471 I.setOperand(1, Folded);
472 return true;
473 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475 isOnlyUse(Op) && isOnlyUse(Op1)) {
476 Constant *C1 = cast<Constant>(Op->getOperand(1));
477 Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000480 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000481 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482 Op1->getOperand(0),
483 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000484 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000485 I.setOperand(0, New);
486 I.setOperand(1, Folded);
487 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000488 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000489 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000490 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000491}
Chris Lattnerca081252001-12-14 16:52:21 +0000492
Reid Spencer266e42b2006-12-23 06:05:41 +0000493/// SimplifyCompare - For a CmpInst this function just orders the operands
494/// so that theyare listed from right (least complex) to left (most complex).
495/// This puts constants before unary operators before binary operators.
496bool InstCombiner::SimplifyCompare(CmpInst &I) {
497 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498 return false;
499 I.swapOperands();
500 // Compare instructions are not associative so there's nothing else we can do.
501 return true;
502}
503
Chris Lattnerbb74e222003-03-10 23:06:50 +0000504// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000506//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000507static inline Value *dyn_castNegVal(Value *V) {
508 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000509 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000510
Chris Lattner9ad0d552004-12-14 20:08:06 +0000511 // Constants can be considered to be negated values if they can be folded.
512 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000515}
516
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517static inline Value *dyn_castNotVal(Value *V) {
518 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000519 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000520
521 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000523 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524 return 0;
525}
526
Chris Lattner7fb29e12003-03-11 00:12:48 +0000527// dyn_castFoldableMul - If this value is a multiply that can be folded into
528// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000529// non-constant operand of the multiply, and set CST to point to the multiplier.
530// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000532static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000533 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000535 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000536 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000539 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 // The multiplier is really 1 << CST.
541 Constant *One = ConstantInt::get(V->getType(), 1);
542 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543 return I->getOperand(0);
544 }
545 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000547}
Chris Lattner31ae8632002-08-14 17:51:49 +0000548
Chris Lattner0798af32005-01-13 20:14:25 +0000549/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550/// expression, return it.
551static User *dyn_castGetElementPtr(Value *V) {
552 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554 if (CE->getOpcode() == Instruction::GetElementPtr)
555 return cast<User>(V);
556 return false;
557}
558
Chris Lattner623826c2004-09-28 21:48:02 +0000559// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000560static ConstantInt *AddOne(ConstantInt *C) {
561 return cast<ConstantInt>(ConstantExpr::getAdd(C,
562 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000563}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *SubOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getSub(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
568
Chris Lattner4534dd592006-02-09 07:38:58 +0000569/// ComputeMaskedBits - Determine which of the bits specified in Mask are
570/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000571/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
572/// processing.
573/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
574/// we cannot optimize based on the assumption that it is zero without changing
575/// it to be an explicit zero. If we don't change it to zero, other code could
576/// optimized based on the contradictory assumption that it is non-zero.
577/// Because instcombine aggressively folds operations with undef args anyway,
578/// this won't lose us code quality.
579static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
580 APInt& KnownOne, unsigned Depth = 0) {
581 uint32_t BitWidth = Mask.getBitWidth();
582 assert(KnownZero.getBitWidth() == BitWidth &&
583 KnownOne.getBitWidth() == BitWidth &&
584 "Mask, KnownOne and KnownZero should have same BitWidth");
585 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
586 // We know all of the bits for a constant!
587 APInt Tmp(CI->getValue());
588 Tmp.zextOrTrunc(BitWidth);
589 KnownOne = Tmp & Mask;
590 KnownZero = ~KnownOne & Mask;
591 return;
592 }
593
594 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
595 if (Depth == 6 || Mask == 0)
596 return; // Limit search depth.
597
598 Instruction *I = dyn_cast<Instruction>(V);
599 if (!I) return;
600
601 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
602 Mask &= APInt::getAllOnesValue(
603 cast<IntegerType>(V->getType())->getBitWidth()).zextOrTrunc(BitWidth);
604
605 switch (I->getOpcode()) {
606 case Instruction::And:
607 // If either the LHS or the RHS are Zero, the result is zero.
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
609 Mask &= ~KnownZero;
610 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613
614 // Output known-1 bits are only known if set in both the LHS & RHS.
615 KnownOne &= KnownOne2;
616 // Output known-0 are known to be clear if zero in either the LHS | RHS.
617 KnownZero |= KnownZero2;
618 return;
619 case Instruction::Or:
620 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621 Mask &= ~KnownOne;
622 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
623 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
624 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
625
626 // Output known-0 bits are only known if clear in both the LHS & RHS.
627 KnownZero &= KnownZero2;
628 // Output known-1 are known to be set if set in either the LHS | RHS.
629 KnownOne |= KnownOne2;
630 return;
631 case Instruction::Xor: {
632 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
633 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
634 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
635 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
636
637 // Output known-0 bits are known if clear or set in both the LHS & RHS.
638 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
639 // Output known-1 are known to be set if set in only one of the LHS, RHS.
640 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
641 KnownZero = KnownZeroOut;
642 return;
643 }
644 case Instruction::Select:
645 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
649
650 // Only known if known in both the LHS and RHS.
651 KnownOne &= KnownOne2;
652 KnownZero &= KnownZero2;
653 return;
654 case Instruction::FPTrunc:
655 case Instruction::FPExt:
656 case Instruction::FPToUI:
657 case Instruction::FPToSI:
658 case Instruction::SIToFP:
659 case Instruction::PtrToInt:
660 case Instruction::UIToFP:
661 case Instruction::IntToPtr:
662 return; // Can't work with floating point or pointers
663 case Instruction::Trunc:
664 // All these have integer operands
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 return;
667 case Instruction::BitCast: {
668 const Type *SrcTy = I->getOperand(0)->getType();
669 if (SrcTy->isInteger()) {
670 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
671 return;
672 }
673 break;
674 }
675 case Instruction::ZExt: {
676 // Compute the bits in the result that are not present in the input.
677 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000678 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000679
Zhou Shengd1eb3d52007-03-08 15:15:18 +0000680 Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
683 // The top bits are known to be zero.
684 KnownZero |= NewBits;
685 return;
686 }
687 case Instruction::SExt: {
688 // Compute the bits in the result that are not present in the input.
689 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000690 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000691
Zhou Shengd1eb3d52007-03-08 15:15:18 +0000692 Mask &= SrcTy->getMask().zextOrTrunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000693 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695
696 // If the sign bit of the input is known set or clear, then we know the
697 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000698 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000699 InSignBit.zextOrTrunc(BitWidth);
700 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
701 KnownZero |= NewBits;
702 KnownOne &= ~NewBits;
703 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
704 KnownOne |= NewBits;
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
709 }
710 return;
711 }
712 case Instruction::Shl:
713 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
714 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
715 uint64_t ShiftAmt = SA->getZExtValue();
716 Mask = APIntOps::lshr(Mask, ShiftAmt);
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000719 KnownZero <<= ShiftAmt;
720 KnownOne <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000721 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
722 return;
723 }
724 break;
725 case Instruction::LShr:
726 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
727 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
728 // Compute the new bits that are at the top now.
729 uint64_t ShiftAmt = SA->getZExtValue();
730 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
731
732 // Unsigned shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000733 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
735 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
736 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
737 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
738 KnownZero |= HighBits; // high bits known zero.
739 return;
740 }
741 break;
742 case Instruction::AShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748
749 // Signed shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000750 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755
756 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000757 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000758
759 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
760 KnownZero |= HighBits;
761 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
762 KnownOne |= HighBits;
763 }
764 return;
765 }
766 break;
767 }
768}
769
770/// ComputeMaskedBits - Determine which of the bits specified in Mask are
771/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner4534dd592006-02-09 07:38:58 +0000772/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
773/// processing.
Reid Spenceraa696402007-03-08 01:46:38 +0000774static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner4534dd592006-02-09 07:38:58 +0000775 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000776 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
777 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000778 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000779 // optimized based on the contradictory assumption that it is non-zero.
780 // Because instcombine aggressively folds operations with undef args anyway,
781 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000782 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000783 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000784 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000785 KnownZero = ~KnownOne & Mask;
786 return;
787 }
788
789 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000790 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000791 return; // Limit search depth.
792
793 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000794 Instruction *I = dyn_cast<Instruction>(V);
795 if (!I) return;
796
Reid Spencera94d3942007-01-19 21:13:56 +0000797 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000798
Chris Lattner0157e7f2006-02-11 09:31:47 +0000799 switch (I->getOpcode()) {
800 case Instruction::And:
801 // If either the LHS or the RHS are Zero, the result is zero.
802 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
803 Mask &= ~KnownZero;
804 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Output known-1 bits are only known if set in both the LHS & RHS.
809 KnownOne &= KnownOne2;
810 // Output known-0 are known to be clear if zero in either the LHS | RHS.
811 KnownZero |= KnownZero2;
812 return;
813 case Instruction::Or:
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
815 Mask &= ~KnownOne;
816 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
817 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
818 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
819
820 // Output known-0 bits are only known if clear in both the LHS & RHS.
821 KnownZero &= KnownZero2;
822 // Output known-1 are known to be set if set in either the LHS | RHS.
823 KnownOne |= KnownOne2;
824 return;
825 case Instruction::Xor: {
826 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
827 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
828 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
829 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
830
831 // Output known-0 bits are known if clear or set in both the LHS & RHS.
832 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
833 // Output known-1 are known to be set if set in only one of the LHS, RHS.
834 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
835 KnownZero = KnownZeroOut;
836 return;
837 }
838 case Instruction::Select:
839 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
840 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
841 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
842 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
843
844 // Only known if known in both the LHS and RHS.
845 KnownOne &= KnownOne2;
846 KnownZero &= KnownZero2;
847 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000848 case Instruction::FPTrunc:
849 case Instruction::FPExt:
850 case Instruction::FPToUI:
851 case Instruction::FPToSI:
852 case Instruction::SIToFP:
853 case Instruction::PtrToInt:
854 case Instruction::UIToFP:
855 case Instruction::IntToPtr:
856 return; // Can't work with floating point or pointers
857 case Instruction::Trunc:
858 // All these have integer operands
859 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
860 return;
861 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000862 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000863 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000864 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000865 return;
866 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000867 break;
868 }
869 case Instruction::ZExt: {
870 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000871 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
872 uint64_t NotIn = ~SrcTy->getBitMask();
873 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000874
Reid Spencera94d3942007-01-19 21:13:56 +0000875 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
878 // The top bits are known to be zero.
879 KnownZero |= NewBits;
880 return;
881 }
882 case Instruction::SExt: {
883 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000884 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
885 uint64_t NotIn = ~SrcTy->getBitMask();
886 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000887
Reid Spencera94d3942007-01-19 21:13:56 +0000888 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000889 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000891
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000892 // If the sign bit of the input is known set or clear, then we know the
893 // top bits of the result.
894 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
895 if (KnownZero & InSignBit) { // Input sign bit known zero
896 KnownZero |= NewBits;
897 KnownOne &= ~NewBits;
898 } else if (KnownOne & InSignBit) { // Input sign bit known set
899 KnownOne |= NewBits;
900 KnownZero &= ~NewBits;
901 } else { // Input sign bit unknown
902 KnownZero &= ~NewBits;
903 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 }
905 return;
906 }
907 case Instruction::Shl:
908 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000909 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
910 uint64_t ShiftAmt = SA->getZExtValue();
911 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
913 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000914 KnownZero <<= ShiftAmt;
915 KnownOne <<= ShiftAmt;
916 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000917 return;
918 }
919 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000920 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000921 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000922 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000923 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000924 uint64_t ShiftAmt = SA->getZExtValue();
925 uint64_t HighBits = (1ULL << ShiftAmt)-1;
926 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000927
Reid Spencerfdff9382006-11-08 06:47:33 +0000928 // Unsigned shift right.
929 Mask <<= ShiftAmt;
930 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
931 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
932 KnownZero >>= ShiftAmt;
933 KnownOne >>= ShiftAmt;
934 KnownZero |= HighBits; // high bits known zero.
935 return;
936 }
937 break;
938 case Instruction::AShr:
939 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
940 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
941 // Compute the new bits that are at the top now.
942 uint64_t ShiftAmt = SA->getZExtValue();
943 uint64_t HighBits = (1ULL << ShiftAmt)-1;
944 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
945
946 // Signed shift right.
947 Mask <<= ShiftAmt;
948 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
949 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
950 KnownZero >>= ShiftAmt;
951 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000952
Reid Spencerfdff9382006-11-08 06:47:33 +0000953 // Handle the sign bits.
954 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
955 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000956
Reid Spencerfdff9382006-11-08 06:47:33 +0000957 if (KnownZero & SignBit) { // New bits are known zero.
958 KnownZero |= HighBits;
959 } else if (KnownOne & SignBit) { // New bits are known one.
960 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000961 }
962 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000963 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000964 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000965 }
Chris Lattner92a68652006-02-07 08:05:22 +0000966}
967
968/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
969/// this predicate to simplify operations downstream. Mask is known to be zero
970/// for bits that V cannot have.
971static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000972 uint64_t KnownZero, KnownOne;
973 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
975 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000976}
977
Reid Spencerbb5741f2007-03-08 01:52:58 +0000978/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
979/// this predicate to simplify operations downstream. Mask is known to be zero
980/// for bits that V cannot have.
981static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
982 APInt KnownZero(Mask), KnownOne(Mask);
983 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 return (KnownZero & Mask) == Mask;
986}
987
Chris Lattner0157e7f2006-02-11 09:31:47 +0000988/// ShrinkDemandedConstant - Check to see if the specified operand of the
989/// specified instruction is a constant integer. If so, check to see if there
990/// are any bits set in the constant that are not demanded. If so, shrink the
991/// constant and return true.
992static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
993 uint64_t Demanded) {
994 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
995 if (!OpC) return false;
996
997 // If there are no bits set that aren't demanded, nothing to do.
998 if ((~Demanded & OpC->getZExtValue()) == 0)
999 return false;
1000
1001 // This is producing any bits that are not needed, shrink the RHS.
1002 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001003 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004 return true;
1005}
1006
Chris Lattneree0f2802006-02-12 02:07:56 +00001007// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1008// set of known zero and one bits, compute the maximum and minimum values that
1009// could have the specified known zero and known one bits, returning them in
1010// min/max.
1011static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1012 uint64_t KnownZero,
1013 uint64_t KnownOne,
1014 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001015 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001016 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1017
1018 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1019
1020 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1021 // bit if it is unknown.
1022 Min = KnownOne;
1023 Max = KnownOne|UnknownBits;
1024
1025 if (SignBit & UnknownBits) { // Sign bit is unknown
1026 Min |= SignBit;
1027 Max &= ~SignBit;
1028 }
1029
1030 // Sign extend the min/max values.
1031 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1032 Min = (Min << ShAmt) >> ShAmt;
1033 Max = (Max << ShAmt) >> ShAmt;
1034}
1035
1036// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1037// a set of known zero and one bits, compute the maximum and minimum values that
1038// could have the specified known zero and known one bits, returning them in
1039// min/max.
1040static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1041 uint64_t KnownZero,
1042 uint64_t KnownOne,
1043 uint64_t &Min,
1044 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001045 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001046 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1047
1048 // The minimum value is when the unknown bits are all zeros.
1049 Min = KnownOne;
1050 // The maximum value is when the unknown bits are all ones.
1051 Max = KnownOne|UnknownBits;
1052}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053
1054
1055/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1056/// DemandedMask bits of the result of V are ever used downstream. If we can
1057/// use this information to simplify V, do so and return true. Otherwise,
1058/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1059/// the expression (used to simplify the caller). The KnownZero/One bits may
1060/// only be accurate for those bits in the DemandedMask.
1061bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1062 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +00001063 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001064 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +00001065 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066 // We know all of the bits for a constant!
1067 KnownOne = CI->getZExtValue() & DemandedMask;
1068 KnownZero = ~KnownOne & DemandedMask;
1069 return false;
1070 }
1071
1072 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001073 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001074 if (Depth != 0) { // Not at the root.
1075 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1076 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +00001077 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001078 }
Chris Lattner2590e512006-02-07 06:56:34 +00001079 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001080 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001081 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001082 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001083 if (V != UndefValue::get(VTy))
1084 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +00001085 return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001086 } else if (Depth == 6) { // Limit search depth.
1087 return false;
1088 }
1089
1090 Instruction *I = dyn_cast<Instruction>(V);
1091 if (!I) return false; // Only analyze instructions.
1092
Chris Lattnerab2f9132007-03-04 23:16:36 +00001093 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +00001094
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001095 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001096 switch (I->getOpcode()) {
1097 default: break;
1098 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001099 // If either the LHS or the RHS are Zero, the result is zero.
1100 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1101 KnownZero, KnownOne, Depth+1))
1102 return true;
1103 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1104
1105 // If something is known zero on the RHS, the bits aren't demanded on the
1106 // LHS.
1107 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1108 KnownZero2, KnownOne2, Depth+1))
1109 return true;
1110 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1111
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001112 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001113 // These bits cannot contribute to the result of the 'and'.
1114 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1115 return UpdateValueUsesWith(I, I->getOperand(0));
1116 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1117 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001118
1119 // If all of the demanded bits in the inputs are known zeros, return zero.
1120 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001121 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001122
Chris Lattner0157e7f2006-02-11 09:31:47 +00001123 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001124 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001125 return UpdateValueUsesWith(I, I);
1126
1127 // Output known-1 bits are only known if set in both the LHS & RHS.
1128 KnownOne &= KnownOne2;
1129 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1130 KnownZero |= KnownZero2;
1131 break;
1132 case Instruction::Or:
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1134 KnownZero, KnownOne, Depth+1))
1135 return true;
1136 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1137 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1138 KnownZero2, KnownOne2, Depth+1))
1139 return true;
1140 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1141
1142 // If all of the demanded bits are known zero on one side, return the other.
1143 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +00001144 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001145 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +00001146 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001147 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001148
1149 // If all of the potentially set bits on one side are known to be set on
1150 // the other side, just use the 'other' side.
1151 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1152 (DemandedMask & (~KnownZero)))
1153 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +00001154 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1155 (DemandedMask & (~KnownZero2)))
1156 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001157
1158 // If the RHS is a constant, see if we can simplify it.
1159 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1160 return UpdateValueUsesWith(I, I);
1161
1162 // Output known-0 bits are only known if clear in both the LHS & RHS.
1163 KnownZero &= KnownZero2;
1164 // Output known-1 are known to be set if set in either the LHS | RHS.
1165 KnownOne |= KnownOne2;
1166 break;
1167 case Instruction::Xor: {
1168 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1169 KnownZero, KnownOne, Depth+1))
1170 return true;
1171 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1172 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1173 KnownZero2, KnownOne2, Depth+1))
1174 return true;
1175 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1176
1177 // If all of the demanded bits are known zero on one side, return the other.
1178 // These bits cannot contribute to the result of the 'xor'.
1179 if ((DemandedMask & KnownZero) == DemandedMask)
1180 return UpdateValueUsesWith(I, I->getOperand(0));
1181 if ((DemandedMask & KnownZero2) == DemandedMask)
1182 return UpdateValueUsesWith(I, I->getOperand(1));
1183
1184 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1185 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1186 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1187 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1188
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001189 // If all of the demanded bits are known to be zero on one side or the
1190 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001191 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001192 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1193 Instruction *Or =
1194 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1195 I->getName());
1196 InsertNewInstBefore(Or, *I);
1197 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001198 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001199
Chris Lattner5b2edb12006-02-12 08:02:11 +00001200 // If all of the demanded bits on one side are known, and all of the set
1201 // bits on that side are also known to be set on the other side, turn this
1202 // into an AND, as we know the bits will be cleared.
1203 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1204 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1205 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001206 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +00001207 Instruction *And =
1208 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1209 InsertNewInstBefore(And, *I);
1210 return UpdateValueUsesWith(I, And);
1211 }
1212 }
1213
Chris Lattner0157e7f2006-02-11 09:31:47 +00001214 // If the RHS is a constant, see if we can simplify it.
1215 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1216 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1217 return UpdateValueUsesWith(I, I);
1218
1219 KnownZero = KnownZeroOut;
1220 KnownOne = KnownOneOut;
1221 break;
1222 }
1223 case Instruction::Select:
1224 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1225 KnownZero, KnownOne, Depth+1))
1226 return true;
1227 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1228 KnownZero2, KnownOne2, Depth+1))
1229 return true;
1230 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1231 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1232
1233 // If the operands are constants, see if we can simplify them.
1234 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1235 return UpdateValueUsesWith(I, I);
1236 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1237 return UpdateValueUsesWith(I, I);
1238
1239 // Only known if known in both the LHS and RHS.
1240 KnownOne &= KnownOne2;
1241 KnownZero &= KnownZero2;
1242 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001243 case Instruction::Trunc:
1244 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1245 KnownZero, KnownOne, Depth+1))
1246 return true;
1247 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1248 break;
1249 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001250 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001251 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001252
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001253 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254 KnownZero, KnownOne, Depth+1))
1255 return true;
1256 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1257 break;
1258 case Instruction::ZExt: {
1259 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001260 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1261 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001262 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001263
Reid Spencera94d3942007-01-19 21:13:56 +00001264 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001265 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1266 KnownZero, KnownOne, Depth+1))
1267 return true;
1268 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1269 // The top bits are known to be zero.
1270 KnownZero |= NewBits;
1271 break;
1272 }
1273 case Instruction::SExt: {
1274 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001275 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1276 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001277 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001278
1279 // Get the sign bit for the source type
1280 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001281 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001282
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001283 // If any of the sign extended bits are demanded, we know that the sign
1284 // bit is demanded.
1285 if (NewBits & DemandedMask)
1286 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001287
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001288 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1289 KnownZero, KnownOne, Depth+1))
1290 return true;
1291 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001292
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001293 // If the sign bit of the input is known set or clear, then we know the
1294 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001295
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001296 // If the input sign bit is known zero, or if the NewBits are not demanded
1297 // convert this into a zero extension.
1298 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1299 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001300 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001301 return UpdateValueUsesWith(I, NewCast);
1302 } else if (KnownOne & InSignBit) { // Input sign bit known set
1303 KnownOne |= NewBits;
1304 KnownZero &= ~NewBits;
1305 } else { // Input sign bit unknown
1306 KnownZero &= ~NewBits;
1307 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001308 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001309 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001310 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001311 case Instruction::Add:
1312 // If there is a constant on the RHS, there are a variety of xformations
1313 // we can do.
1314 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315 // If null, this should be simplified elsewhere. Some of the xforms here
1316 // won't work if the RHS is zero.
1317 if (RHS->isNullValue())
1318 break;
1319
1320 // Figure out what the input bits are. If the top bits of the and result
1321 // are not demanded, then the add doesn't demand them from its input
1322 // either.
1323
1324 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001325 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001326 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1327
1328 // If the top bit of the output is demanded, demand everything from the
1329 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001330 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001331
1332 // Find information about known zero/one bits in the input.
1333 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1334 KnownZero2, KnownOne2, Depth+1))
1335 return true;
1336
1337 // If the RHS of the add has bits set that can't affect the input, reduce
1338 // the constant.
1339 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1340 return UpdateValueUsesWith(I, I);
1341
1342 // Avoid excess work.
1343 if (KnownZero2 == 0 && KnownOne2 == 0)
1344 break;
1345
1346 // Turn it into OR if input bits are zero.
1347 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1348 Instruction *Or =
1349 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1350 I->getName());
1351 InsertNewInstBefore(Or, *I);
1352 return UpdateValueUsesWith(I, Or);
1353 }
1354
1355 // We can say something about the output known-zero and known-one bits,
1356 // depending on potential carries from the input constant and the
1357 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1358 // bits set and the RHS constant is 0x01001, then we know we have a known
1359 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1360
1361 // To compute this, we first compute the potential carry bits. These are
1362 // the bits which may be modified. I'm not aware of a better way to do
1363 // this scan.
1364 uint64_t RHSVal = RHS->getZExtValue();
1365
1366 bool CarryIn = false;
1367 uint64_t CarryBits = 0;
1368 uint64_t CurBit = 1;
1369 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1370 // Record the current carry in.
1371 if (CarryIn) CarryBits |= CurBit;
1372
1373 bool CarryOut;
1374
1375 // This bit has a carry out unless it is "zero + zero" or
1376 // "zero + anything" with no carry in.
1377 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1378 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1379 } else if (!CarryIn &&
1380 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1381 CarryOut = false; // 0 + anything has no carry out if no carry in.
1382 } else {
1383 // Otherwise, we have to assume we have a carry out.
1384 CarryOut = true;
1385 }
1386
1387 // This stage's carry out becomes the next stage's carry-in.
1388 CarryIn = CarryOut;
1389 }
1390
1391 // Now that we know which bits have carries, compute the known-1/0 sets.
1392
1393 // Bits are known one if they are known zero in one operand and one in the
1394 // other, and there is no input carry.
1395 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1396
1397 // Bits are known zero if they are known zero in both operands and there
1398 // is no input carry.
1399 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner5fdded12007-03-05 00:02:29 +00001400 } else {
1401 // If the high-bits of this ADD are not demanded, then it does not demand
1402 // the high bits of its LHS or RHS.
1403 if ((DemandedMask & VTy->getSignBit()) == 0) {
1404 // Right fill the mask of bits for this ADD to demand the most
1405 // significant bit and all those below it.
1406 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1407 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1408 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409 KnownZero2, KnownOne2, Depth+1))
1410 return true;
1411 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412 KnownZero2, KnownOne2, Depth+1))
1413 return true;
1414 }
1415 }
1416 break;
1417 case Instruction::Sub:
1418 // If the high-bits of this SUB are not demanded, then it does not demand
1419 // the high bits of its LHS or RHS.
1420 if ((DemandedMask & VTy->getSignBit()) == 0) {
1421 // Right fill the mask of bits for this SUB to demand the most
1422 // significant bit and all those below it.
1423 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1424 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1425 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1426 KnownZero2, KnownOne2, Depth+1))
1427 return true;
1428 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1429 KnownZero2, KnownOne2, Depth+1))
1430 return true;
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001431 }
1432 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001433 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001434 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435 uint64_t ShiftAmt = SA->getZExtValue();
1436 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001437 KnownZero, KnownOne, Depth+1))
1438 return true;
1439 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001440 KnownZero <<= ShiftAmt;
1441 KnownOne <<= ShiftAmt;
1442 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001443 }
Chris Lattner2590e512006-02-07 06:56:34 +00001444 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001445 case Instruction::LShr:
1446 // For a logical shift right
1447 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1448 unsigned ShiftAmt = SA->getZExtValue();
1449
1450 // Compute the new bits that are at the top now.
1451 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001452 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1453 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001454 // Unsigned shift right.
1455 if (SimplifyDemandedBits(I->getOperand(0),
1456 (DemandedMask << ShiftAmt) & TypeMask,
1457 KnownZero, KnownOne, Depth+1))
1458 return true;
1459 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1460 KnownZero &= TypeMask;
1461 KnownOne &= TypeMask;
1462 KnownZero >>= ShiftAmt;
1463 KnownOne >>= ShiftAmt;
1464 KnownZero |= HighBits; // high bits known zero.
1465 }
1466 break;
1467 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001468 // If this is an arithmetic shift right and only the low-bit is set, we can
1469 // always convert this into a logical shr, even if the shift amount is
1470 // variable. The low bit of the shift cannot be an input sign bit unless
1471 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001472 if (DemandedMask == 1) {
1473 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001474 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001475 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001476 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001477 return UpdateValueUsesWith(I, NewVal);
1478 }
1479
Reid Spencere0fc4df2006-10-20 07:07:24 +00001480 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1481 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001482
1483 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001484 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001485 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1486 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001487 // Signed shift right.
1488 if (SimplifyDemandedBits(I->getOperand(0),
1489 (DemandedMask << ShiftAmt) & TypeMask,
1490 KnownZero, KnownOne, Depth+1))
1491 return true;
1492 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1493 KnownZero &= TypeMask;
1494 KnownOne &= TypeMask;
1495 KnownZero >>= ShiftAmt;
1496 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001497
Reid Spencerfdff9382006-11-08 06:47:33 +00001498 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001499 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001500 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001501
Reid Spencerfdff9382006-11-08 06:47:33 +00001502 // If the input sign bit is known to be zero, or if none of the top bits
1503 // are demanded, turn this into an unsigned shift right.
1504 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1505 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001506 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001507 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001508 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1509 return UpdateValueUsesWith(I, NewVal);
1510 } else if (KnownOne & SignBit) { // New bits are known one.
1511 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001512 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001513 }
Chris Lattner2590e512006-02-07 06:56:34 +00001514 break;
1515 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001516
1517 // If the client is only demanding bits that we know, return the known
1518 // constant.
1519 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001520 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001521 return false;
1522}
1523
Chris Lattner2deeaea2006-10-05 06:55:50 +00001524
1525/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1526/// 64 or fewer elements. DemandedElts contains the set of elements that are
1527/// actually used by the caller. This method analyzes which elements of the
1528/// operand are undef and returns that information in UndefElts.
1529///
1530/// If the information about demanded elements can be used to simplify the
1531/// operation, the operation is simplified, then the resultant value is
1532/// returned. This returns null if no change was made.
1533Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1534 uint64_t &UndefElts,
1535 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001536 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001537 assert(VWidth <= 64 && "Vector too wide to analyze!");
1538 uint64_t EltMask = ~0ULL >> (64-VWidth);
1539 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1540 "Invalid DemandedElts!");
1541
1542 if (isa<UndefValue>(V)) {
1543 // If the entire vector is undefined, just return this info.
1544 UndefElts = EltMask;
1545 return 0;
1546 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1547 UndefElts = EltMask;
1548 return UndefValue::get(V->getType());
1549 }
1550
1551 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001552 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1553 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001554 Constant *Undef = UndefValue::get(EltTy);
1555
1556 std::vector<Constant*> Elts;
1557 for (unsigned i = 0; i != VWidth; ++i)
1558 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1559 Elts.push_back(Undef);
1560 UndefElts |= (1ULL << i);
1561 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1562 Elts.push_back(Undef);
1563 UndefElts |= (1ULL << i);
1564 } else { // Otherwise, defined.
1565 Elts.push_back(CP->getOperand(i));
1566 }
1567
1568 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001569 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001570 return NewCP != CP ? NewCP : 0;
1571 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001572 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001573 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001574 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001575 Constant *Zero = Constant::getNullValue(EltTy);
1576 Constant *Undef = UndefValue::get(EltTy);
1577 std::vector<Constant*> Elts;
1578 for (unsigned i = 0; i != VWidth; ++i)
1579 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1580 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001581 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001582 }
1583
1584 if (!V->hasOneUse()) { // Other users may use these bits.
1585 if (Depth != 0) { // Not at the root.
1586 // TODO: Just compute the UndefElts information recursively.
1587 return false;
1588 }
1589 return false;
1590 } else if (Depth == 10) { // Limit search depth.
1591 return false;
1592 }
1593
1594 Instruction *I = dyn_cast<Instruction>(V);
1595 if (!I) return false; // Only analyze instructions.
1596
1597 bool MadeChange = false;
1598 uint64_t UndefElts2;
1599 Value *TmpV;
1600 switch (I->getOpcode()) {
1601 default: break;
1602
1603 case Instruction::InsertElement: {
1604 // If this is a variable index, we don't know which element it overwrites.
1605 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001606 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001607 if (Idx == 0) {
1608 // Note that we can't propagate undef elt info, because we don't know
1609 // which elt is getting updated.
1610 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1611 UndefElts2, Depth+1);
1612 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1613 break;
1614 }
1615
1616 // If this is inserting an element that isn't demanded, remove this
1617 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001618 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001619 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1620 return AddSoonDeadInstToWorklist(*I, 0);
1621
1622 // Otherwise, the element inserted overwrites whatever was there, so the
1623 // input demanded set is simpler than the output set.
1624 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1625 DemandedElts & ~(1ULL << IdxNo),
1626 UndefElts, Depth+1);
1627 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1628
1629 // The inserted element is defined.
1630 UndefElts |= 1ULL << IdxNo;
1631 break;
1632 }
1633
1634 case Instruction::And:
1635 case Instruction::Or:
1636 case Instruction::Xor:
1637 case Instruction::Add:
1638 case Instruction::Sub:
1639 case Instruction::Mul:
1640 // div/rem demand all inputs, because they don't want divide by zero.
1641 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1642 UndefElts, Depth+1);
1643 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1644 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1645 UndefElts2, Depth+1);
1646 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1647
1648 // Output elements are undefined if both are undefined. Consider things
1649 // like undef&0. The result is known zero, not undef.
1650 UndefElts &= UndefElts2;
1651 break;
1652
1653 case Instruction::Call: {
1654 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1655 if (!II) break;
1656 switch (II->getIntrinsicID()) {
1657 default: break;
1658
1659 // Binary vector operations that work column-wise. A dest element is a
1660 // function of the corresponding input elements from the two inputs.
1661 case Intrinsic::x86_sse_sub_ss:
1662 case Intrinsic::x86_sse_mul_ss:
1663 case Intrinsic::x86_sse_min_ss:
1664 case Intrinsic::x86_sse_max_ss:
1665 case Intrinsic::x86_sse2_sub_sd:
1666 case Intrinsic::x86_sse2_mul_sd:
1667 case Intrinsic::x86_sse2_min_sd:
1668 case Intrinsic::x86_sse2_max_sd:
1669 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1670 UndefElts, Depth+1);
1671 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1672 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1673 UndefElts2, Depth+1);
1674 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1675
1676 // If only the low elt is demanded and this is a scalarizable intrinsic,
1677 // scalarize it now.
1678 if (DemandedElts == 1) {
1679 switch (II->getIntrinsicID()) {
1680 default: break;
1681 case Intrinsic::x86_sse_sub_ss:
1682 case Intrinsic::x86_sse_mul_ss:
1683 case Intrinsic::x86_sse2_sub_sd:
1684 case Intrinsic::x86_sse2_mul_sd:
1685 // TODO: Lower MIN/MAX/ABS/etc
1686 Value *LHS = II->getOperand(1);
1687 Value *RHS = II->getOperand(2);
1688 // Extract the element as scalars.
1689 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1690 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1691
1692 switch (II->getIntrinsicID()) {
1693 default: assert(0 && "Case stmts out of sync!");
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse2_sub_sd:
1696 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1697 II->getName()), *II);
1698 break;
1699 case Intrinsic::x86_sse_mul_ss:
1700 case Intrinsic::x86_sse2_mul_sd:
1701 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1702 II->getName()), *II);
1703 break;
1704 }
1705
1706 Instruction *New =
1707 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1708 II->getName());
1709 InsertNewInstBefore(New, *II);
1710 AddSoonDeadInstToWorklist(*II, 0);
1711 return New;
1712 }
1713 }
1714
1715 // Output elements are undefined if both are undefined. Consider things
1716 // like undef&0. The result is known zero, not undef.
1717 UndefElts &= UndefElts2;
1718 break;
1719 }
1720 break;
1721 }
1722 }
1723 return MadeChange ? I : 0;
1724}
1725
Reid Spencer266e42b2006-12-23 06:05:41 +00001726/// @returns true if the specified compare instruction is
1727/// true when both operands are equal...
1728/// @brief Determine if the ICmpInst returns true if both operands are equal
1729static bool isTrueWhenEqual(ICmpInst &ICI) {
1730 ICmpInst::Predicate pred = ICI.getPredicate();
1731 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1732 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1733 pred == ICmpInst::ICMP_SLE;
1734}
1735
Chris Lattnerb8b97502003-08-13 19:01:45 +00001736/// AssociativeOpt - Perform an optimization on an associative operator. This
1737/// function is designed to check a chain of associative operators for a
1738/// potential to apply a certain optimization. Since the optimization may be
1739/// applicable if the expression was reassociated, this checks the chain, then
1740/// reassociates the expression as necessary to expose the optimization
1741/// opportunity. This makes use of a special Functor, which must define
1742/// 'shouldApply' and 'apply' methods.
1743///
1744template<typename Functor>
1745Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1746 unsigned Opcode = Root.getOpcode();
1747 Value *LHS = Root.getOperand(0);
1748
1749 // Quick check, see if the immediate LHS matches...
1750 if (F.shouldApply(LHS))
1751 return F.apply(Root);
1752
1753 // Otherwise, if the LHS is not of the same opcode as the root, return.
1754 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001755 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001756 // Should we apply this transform to the RHS?
1757 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1758
1759 // If not to the RHS, check to see if we should apply to the LHS...
1760 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1761 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1762 ShouldApply = true;
1763 }
1764
1765 // If the functor wants to apply the optimization to the RHS of LHSI,
1766 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1767 if (ShouldApply) {
1768 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001769
Chris Lattnerb8b97502003-08-13 19:01:45 +00001770 // Now all of the instructions are in the current basic block, go ahead
1771 // and perform the reassociation.
1772 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1773
1774 // First move the selected RHS to the LHS of the root...
1775 Root.setOperand(0, LHSI->getOperand(1));
1776
1777 // Make what used to be the LHS of the root be the user of the root...
1778 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001779 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001780 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1781 return 0;
1782 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001783 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001784 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001785 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1786 BasicBlock::iterator ARI = &Root; ++ARI;
1787 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1788 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001789
1790 // Now propagate the ExtraOperand down the chain of instructions until we
1791 // get to LHSI.
1792 while (TmpLHSI != LHSI) {
1793 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001794 // Move the instruction to immediately before the chain we are
1795 // constructing to avoid breaking dominance properties.
1796 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1797 BB->getInstList().insert(ARI, NextLHSI);
1798 ARI = NextLHSI;
1799
Chris Lattnerb8b97502003-08-13 19:01:45 +00001800 Value *NextOp = NextLHSI->getOperand(1);
1801 NextLHSI->setOperand(1, ExtraOperand);
1802 TmpLHSI = NextLHSI;
1803 ExtraOperand = NextOp;
1804 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001805
Chris Lattnerb8b97502003-08-13 19:01:45 +00001806 // Now that the instructions are reassociated, have the functor perform
1807 // the transformation...
1808 return F.apply(Root);
1809 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001810
Chris Lattnerb8b97502003-08-13 19:01:45 +00001811 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1812 }
1813 return 0;
1814}
1815
1816
1817// AddRHS - Implements: X + X --> X << 1
1818struct AddRHS {
1819 Value *RHS;
1820 AddRHS(Value *rhs) : RHS(rhs) {}
1821 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1822 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001823 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001824 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001825 }
1826};
1827
1828// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1829// iff C1&C2 == 0
1830struct AddMaskingAnd {
1831 Constant *C2;
1832 AddMaskingAnd(Constant *c) : C2(c) {}
1833 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001834 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001835 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001836 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001837 }
1838 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001839 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001840 }
1841};
1842
Chris Lattner86102b82005-01-01 16:22:27 +00001843static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001844 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001845 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001846 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001847 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001848
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001849 return IC->InsertNewInstBefore(CastInst::create(
1850 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001851 }
1852
Chris Lattner183b3362004-04-09 19:05:30 +00001853 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001854 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1855 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001856
Chris Lattner183b3362004-04-09 19:05:30 +00001857 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1858 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001859 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1860 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001861 }
1862
1863 Value *Op0 = SO, *Op1 = ConstOperand;
1864 if (!ConstIsRHS)
1865 std::swap(Op0, Op1);
1866 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001867 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1868 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001869 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1870 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1871 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001872 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001873 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001874 abort();
1875 }
Chris Lattner86102b82005-01-01 16:22:27 +00001876 return IC->InsertNewInstBefore(New, I);
1877}
1878
1879// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1880// constant as the other operand, try to fold the binary operator into the
1881// select arguments. This also works for Cast instructions, which obviously do
1882// not have a second operand.
1883static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1884 InstCombiner *IC) {
1885 // Don't modify shared select instructions
1886 if (!SI->hasOneUse()) return 0;
1887 Value *TV = SI->getOperand(1);
1888 Value *FV = SI->getOperand(2);
1889
1890 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001891 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001892 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001893
Chris Lattner86102b82005-01-01 16:22:27 +00001894 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1895 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1896
1897 return new SelectInst(SI->getCondition(), SelectTrueVal,
1898 SelectFalseVal);
1899 }
1900 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001901}
1902
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001903
1904/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1905/// node as operand #0, see if we can fold the instruction into the PHI (which
1906/// is only possible if all operands to the PHI are constants).
1907Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1908 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001909 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001910 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001911
Chris Lattner04689872006-09-09 22:02:56 +00001912 // Check to see if all of the operands of the PHI are constants. If there is
1913 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001914 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001915 BasicBlock *NonConstBB = 0;
1916 for (unsigned i = 0; i != NumPHIValues; ++i)
1917 if (!isa<Constant>(PN->getIncomingValue(i))) {
1918 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001919 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001920 NonConstBB = PN->getIncomingBlock(i);
1921
1922 // If the incoming non-constant value is in I's block, we have an infinite
1923 // loop.
1924 if (NonConstBB == I.getParent())
1925 return 0;
1926 }
1927
1928 // If there is exactly one non-constant value, we can insert a copy of the
1929 // operation in that block. However, if this is a critical edge, we would be
1930 // inserting the computation one some other paths (e.g. inside a loop). Only
1931 // do this if the pred block is unconditionally branching into the phi block.
1932 if (NonConstBB) {
1933 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1934 if (!BI || !BI->isUnconditional()) return 0;
1935 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001936
1937 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001938 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001939 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001940 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001941 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001942
1943 // Next, add all of the operands to the PHI.
1944 if (I.getNumOperands() == 2) {
1945 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001946 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001947 Value *InV;
1948 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001949 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1950 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1951 else
1952 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001953 } else {
1954 assert(PN->getIncomingBlock(i) == NonConstBB);
1955 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1956 InV = BinaryOperator::create(BO->getOpcode(),
1957 PN->getIncomingValue(i), C, "phitmp",
1958 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001959 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1960 InV = CmpInst::create(CI->getOpcode(),
1961 CI->getPredicate(),
1962 PN->getIncomingValue(i), C, "phitmp",
1963 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001964 else
1965 assert(0 && "Unknown binop!");
1966
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001967 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001968 }
1969 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001970 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001971 } else {
1972 CastInst *CI = cast<CastInst>(&I);
1973 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001974 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001975 Value *InV;
1976 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001977 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001978 } else {
1979 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001980 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1981 I.getType(), "phitmp",
1982 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001983 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001984 }
1985 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001986 }
1987 }
1988 return ReplaceInstUsesWith(I, NewPN);
1989}
1990
Chris Lattner113f4f42002-06-25 16:13:24 +00001991Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001992 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001993 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001994
Chris Lattnercf4a9962004-04-10 22:01:55 +00001995 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001996 // X + undef -> undef
1997 if (isa<UndefValue>(RHS))
1998 return ReplaceInstUsesWith(I, RHS);
1999
Chris Lattnercf4a9962004-04-10 22:01:55 +00002000 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002001 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002002 if (RHSC->isNullValue())
2003 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002004 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2005 if (CFP->isExactlyValue(-0.0))
2006 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002008
Chris Lattnercf4a9962004-04-10 22:01:55 +00002009 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002010 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00002011 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00002012 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002013 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002014
2015 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2016 // (X & 254)+1 -> (X&254)|1
2017 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002018 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00002019 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002020 KnownZero, KnownOne))
2021 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00002022 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002023
2024 if (isa<PHINode>(LHS))
2025 if (Instruction *NV = FoldOpIntoPhi(I))
2026 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002027
Chris Lattner330628a2006-01-06 17:59:59 +00002028 ConstantInt *XorRHS = 0;
2029 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002030 if (isa<ConstantInt>(RHSC) &&
2031 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002032 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2033 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2034 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2035
2036 uint64_t C0080Val = 1ULL << 31;
2037 int64_t CFF80Val = -C0080Val;
2038 unsigned Size = 32;
2039 do {
2040 if (TySizeBits > Size) {
2041 bool Found = false;
2042 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2043 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2044 if (RHSSExt == CFF80Val) {
2045 if (XorRHS->getZExtValue() == C0080Val)
2046 Found = true;
2047 } else if (RHSZExt == C0080Val) {
2048 if (XorRHS->getSExtValue() == CFF80Val)
2049 Found = true;
2050 }
2051 if (Found) {
2052 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002053 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002054 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00002055 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002056 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002057 Size = 0; // Not a sign ext, but can't be any others either.
2058 goto FoundSExt;
2059 }
2060 }
2061 Size >>= 1;
2062 C0080Val >>= Size;
2063 CFF80Val >>= Size;
2064 } while (Size >= 8);
2065
2066FoundSExt:
2067 const Type *MiddleType = 0;
2068 switch (Size) {
2069 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00002070 case 32: MiddleType = Type::Int32Ty; break;
2071 case 16: MiddleType = Type::Int16Ty; break;
2072 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002073 }
2074 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002075 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002076 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002077 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002078 }
2079 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002080 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002081
Chris Lattnerb8b97502003-08-13 19:01:45 +00002082 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002083 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002084 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002085
2086 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2087 if (RHSI->getOpcode() == Instruction::Sub)
2088 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2089 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2090 }
2091 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2092 if (LHSI->getOpcode() == Instruction::Sub)
2093 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2094 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2095 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002096 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002097
Chris Lattner147e9752002-05-08 22:46:53 +00002098 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002099 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002100 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002101
2102 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002103 if (!isa<Constant>(RHS))
2104 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002105 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002106
Misha Brukmanb1c93172005-04-21 23:48:37 +00002107
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002108 ConstantInt *C2;
2109 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2110 if (X == RHS) // X*C + X --> X * (C+1)
2111 return BinaryOperator::createMul(RHS, AddOne(C2));
2112
2113 // X*C1 + X*C2 --> X * (C1+C2)
2114 ConstantInt *C1;
2115 if (X == dyn_castFoldableMul(RHS, C1))
2116 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002117 }
2118
2119 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002120 if (dyn_castFoldableMul(RHS, C2) == LHS)
2121 return BinaryOperator::createMul(LHS, AddOne(C2));
2122
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002123 // X + ~X --> -1 since ~X = -X-1
2124 if (dyn_castNotVal(LHS) == RHS ||
2125 dyn_castNotVal(RHS) == LHS)
2126 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2127
Chris Lattner57c8d992003-02-18 19:57:07 +00002128
Chris Lattnerb8b97502003-08-13 19:01:45 +00002129 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002130 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002131 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2132 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002133
Chris Lattnerb9cde762003-10-02 15:11:26 +00002134 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002135 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002136 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2137 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2138 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00002139 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00002140
Chris Lattnerbff91d92004-10-08 05:07:56 +00002141 // (X & FF00) + xx00 -> (X+xx00) & FF00
2142 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2143 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2144 if (Anded == CRHS) {
2145 // See if all bits from the first bit set in the Add RHS up are included
2146 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002147 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002148
2149 // Form a mask of all bits from the lowest bit added through the top.
2150 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00002151 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002152
2153 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002154 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002155
Chris Lattnerbff91d92004-10-08 05:07:56 +00002156 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2157 // Okay, the xform is safe. Insert the new add pronto.
2158 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2159 LHS->getName()), I);
2160 return BinaryOperator::createAnd(NewAdd, C2);
2161 }
2162 }
2163 }
2164
Chris Lattnerd4252a72004-07-30 07:50:03 +00002165 // Try to fold constant add into select arguments.
2166 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002167 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002168 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002169 }
2170
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002171 // add (cast *A to intptrtype) B ->
2172 // cast (GEP (cast *A to sbyte*) B) ->
2173 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002174 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002175 CastInst *CI = dyn_cast<CastInst>(LHS);
2176 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002177 if (!CI) {
2178 CI = dyn_cast<CastInst>(RHS);
2179 Other = LHS;
2180 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002181 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002182 (CI->getType()->getPrimitiveSizeInBits() ==
2183 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002184 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002185 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002186 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002187 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002188 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002189 }
2190 }
2191
Chris Lattner113f4f42002-06-25 16:13:24 +00002192 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002193}
2194
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002195// isSignBit - Return true if the value represented by the constant only has the
2196// highest order bit set.
2197static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002198 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00002199 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002200}
2201
Chris Lattner113f4f42002-06-25 16:13:24 +00002202Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002204
Chris Lattnere6794492002-08-12 21:17:25 +00002205 if (Op0 == Op1) // sub X, X -> 0
2206 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002207
Chris Lattnere6794492002-08-12 21:17:25 +00002208 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002209 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002210 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002211
Chris Lattner81a7a232004-10-16 18:11:37 +00002212 if (isa<UndefValue>(Op0))
2213 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2214 if (isa<UndefValue>(Op1))
2215 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2216
Chris Lattner8f2f5982003-11-05 01:06:05 +00002217 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2218 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002219 if (C->isAllOnesValue())
2220 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002221
Chris Lattner8f2f5982003-11-05 01:06:05 +00002222 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002223 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002224 if (match(Op1, m_Not(m_Value(X))))
2225 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002226 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002227 // -(X >>u 31) -> (X >>s 31)
2228 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002229 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002230 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002231 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002232 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002233 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002234 if (CU->getZExtValue() ==
2235 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002236 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002237 return BinaryOperator::create(Instruction::AShr,
2238 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002239 }
2240 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002241 }
2242 else if (SI->getOpcode() == Instruction::AShr) {
2243 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2244 // Check to see if we are shifting out everything but the sign bit.
2245 if (CU->getZExtValue() ==
2246 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002247 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002248 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002249 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002250 }
2251 }
2252 }
Chris Lattner022167f2004-03-13 00:11:49 +00002253 }
Chris Lattner183b3362004-04-09 19:05:30 +00002254
2255 // Try to fold constant sub into select arguments.
2256 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002258 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002259
2260 if (isa<PHINode>(Op0))
2261 if (Instruction *NV = FoldOpIntoPhi(I))
2262 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002263 }
2264
Chris Lattnera9be4492005-04-07 16:15:25 +00002265 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2266 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002267 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002268 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002269 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002270 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002271 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002272 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2273 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2274 // C1-(X+C2) --> (C1-C2)-X
2275 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2276 Op1I->getOperand(0));
2277 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002278 }
2279
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002280 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002281 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2282 // is not used by anyone else...
2283 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002284 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002285 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002286 // Swap the two operands of the subexpr...
2287 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2288 Op1I->setOperand(0, IIOp1);
2289 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002290
Chris Lattner3082c5a2003-02-18 19:28:33 +00002291 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002292 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002293 }
2294
2295 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2296 //
2297 if (Op1I->getOpcode() == Instruction::And &&
2298 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2299 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2300
Chris Lattner396dbfe2004-06-09 05:08:07 +00002301 Value *NewNot =
2302 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002303 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002304 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002305
Reid Spencer3c514952006-10-16 23:08:08 +00002306 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002307 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002308 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002310 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002311 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002312 ConstantExpr::getNeg(DivRHS));
2313
Chris Lattner57c8d992003-02-18 19:57:07 +00002314 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002315 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002316 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002317 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002318 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002319 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002320 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002321 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002322 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002323
Chris Lattner7a002fe2006-12-02 00:13:08 +00002324 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002325 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2326 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002327 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2328 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2329 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2330 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002331 } else if (Op0I->getOpcode() == Instruction::Sub) {
2332 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2333 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002334 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002335
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002336 ConstantInt *C1;
2337 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2338 if (X == Op1) { // X*C - X --> X * (C-1)
2339 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2340 return BinaryOperator::createMul(Op1, CP1);
2341 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002342
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002343 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2344 if (X == dyn_castFoldableMul(Op1, C2))
2345 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2346 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002347 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002348}
2349
Reid Spencer266e42b2006-12-23 06:05:41 +00002350/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002351/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002352static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2353 switch (pred) {
2354 case ICmpInst::ICMP_SLT:
2355 // True if LHS s< RHS and RHS == 0
2356 return RHS->isNullValue();
2357 case ICmpInst::ICMP_SLE:
2358 // True if LHS s<= RHS and RHS == -1
2359 return RHS->isAllOnesValue();
2360 case ICmpInst::ICMP_UGE:
2361 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2362 return RHS->getZExtValue() == (1ULL <<
2363 (RHS->getType()->getPrimitiveSizeInBits()-1));
2364 case ICmpInst::ICMP_UGT:
2365 // True if LHS u> RHS and RHS == high-bit-mask - 1
2366 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002367 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002368 default:
2369 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002370 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002371}
2372
Chris Lattner113f4f42002-06-25 16:13:24 +00002373Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002374 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002375 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002376
Chris Lattner81a7a232004-10-16 18:11:37 +00002377 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2379
Chris Lattnere6794492002-08-12 21:17:25 +00002380 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002381 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002383
2384 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002385 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002386 if (SI->getOpcode() == Instruction::Shl)
2387 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002388 return BinaryOperator::createMul(SI->getOperand(0),
2389 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002390
Chris Lattnercce81be2003-09-11 22:24:54 +00002391 if (CI->isNullValue())
2392 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2393 if (CI->equalsInt(1)) // X * 1 == X
2394 return ReplaceInstUsesWith(I, Op0);
2395 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002396 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002397
Reid Spencere0fc4df2006-10-20 07:07:24 +00002398 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002399 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2400 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002401 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002402 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002403 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002404 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002405 if (Op1F->isNullValue())
2406 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002407
Chris Lattner3082c5a2003-02-18 19:28:33 +00002408 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2409 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2410 if (Op1F->getValue() == 1.0)
2411 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2412 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002413
2414 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2415 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2416 isa<ConstantInt>(Op0I->getOperand(1))) {
2417 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2418 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2419 Op1, "tmp");
2420 InsertNewInstBefore(Add, I);
2421 Value *C1C2 = ConstantExpr::getMul(Op1,
2422 cast<Constant>(Op0I->getOperand(1)));
2423 return BinaryOperator::createAdd(Add, C1C2);
2424
2425 }
Chris Lattner183b3362004-04-09 19:05:30 +00002426
2427 // Try to fold constant mul into select arguments.
2428 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002429 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002430 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002431
2432 if (isa<PHINode>(Op0))
2433 if (Instruction *NV = FoldOpIntoPhi(I))
2434 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002435 }
2436
Chris Lattner934a64cf2003-03-10 23:23:04 +00002437 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2438 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002439 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002440
Chris Lattner2635b522004-02-23 05:39:21 +00002441 // If one of the operands of the multiply is a cast from a boolean value, then
2442 // we know the bool is either zero or one, so this is a 'masking' multiply.
2443 // See if we can simplify things based on how the boolean was originally
2444 // formed.
2445 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002446 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002447 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002448 BoolCast = CI;
2449 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002450 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002451 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002452 BoolCast = CI;
2453 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002454 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002455 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2456 const Type *SCOpTy = SCIOp0->getType();
2457
Reid Spencer266e42b2006-12-23 06:05:41 +00002458 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002459 // multiply into a shift/and combination.
2460 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002461 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002462 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002463 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002464 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002465 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002466 InsertNewInstBefore(
2467 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002468 BoolCast->getOperand(0)->getName()+
2469 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002470
2471 // If the multiply type is not the same as the source type, sign extend
2472 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002473 if (I.getType() != V->getType()) {
2474 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2475 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2476 Instruction::CastOps opcode =
2477 (SrcBits == DstBits ? Instruction::BitCast :
2478 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2479 V = InsertCastBefore(opcode, V, I.getType(), I);
2480 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002481
Chris Lattner2635b522004-02-23 05:39:21 +00002482 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002483 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002484 }
2485 }
2486 }
2487
Chris Lattner113f4f42002-06-25 16:13:24 +00002488 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002489}
2490
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002491/// This function implements the transforms on div instructions that work
2492/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2493/// used by the visitors to those instructions.
2494/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002495Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002497
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002498 // undef / X -> 0
2499 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002501
2502 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002503 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002504 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002505
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002506 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002507 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2508 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002509 // same basic block, then we replace the select with Y, and the condition
2510 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002511 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002512 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002513 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2514 if (ST->isNullValue()) {
2515 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2516 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002517 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002518 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2519 I.setOperand(1, SI->getOperand(2));
2520 else
2521 UpdateValueUsesWith(SI, SI->getOperand(2));
2522 return &I;
2523 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002524
Chris Lattnerd79dc792006-09-09 20:26:32 +00002525 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2526 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2527 if (ST->isNullValue()) {
2528 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2529 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002530 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002531 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2532 I.setOperand(1, SI->getOperand(1));
2533 else
2534 UpdateValueUsesWith(SI, SI->getOperand(1));
2535 return &I;
2536 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002537 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002538
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002539 return 0;
2540}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002541
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002542/// This function implements the transforms common to both integer division
2543/// instructions (udiv and sdiv). It is called by the visitors to those integer
2544/// division instructions.
2545/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002546Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002547 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2548
2549 if (Instruction *Common = commonDivTransforms(I))
2550 return Common;
2551
2552 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2553 // div X, 1 == X
2554 if (RHS->equalsInt(1))
2555 return ReplaceInstUsesWith(I, Op0);
2556
2557 // (X / C1) / C2 -> X / (C1*C2)
2558 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2559 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2560 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2561 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2562 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002563 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002564
2565 if (!RHS->isNullValue()) { // avoid X udiv 0
2566 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2567 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2568 return R;
2569 if (isa<PHINode>(Op0))
2570 if (Instruction *NV = FoldOpIntoPhi(I))
2571 return NV;
2572 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002573 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002574
Chris Lattner3082c5a2003-02-18 19:28:33 +00002575 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002576 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002577 if (LHS->equalsInt(0))
2578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2579
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002580 return 0;
2581}
2582
2583Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2584 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2585
2586 // Handle the integer div common cases
2587 if (Instruction *Common = commonIDivTransforms(I))
2588 return Common;
2589
2590 // X udiv C^2 -> X >> C
2591 // Check to see if this is an unsigned division with an exact power of 2,
2592 // if so, convert to a right shift.
2593 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2594 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2595 if (isPowerOf2_64(Val)) {
2596 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002597 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002598 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002599 }
2600 }
2601
2602 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002603 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002604 if (RHSI->getOpcode() == Instruction::Shl &&
2605 isa<ConstantInt>(RHSI->getOperand(0))) {
2606 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2607 if (isPowerOf2_64(C1)) {
2608 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002609 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002610 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002611 Constant *C2V = ConstantInt::get(NTy, C2);
2612 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002613 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002614 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002615 }
2616 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002617 }
2618
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002619 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2620 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002621 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002622 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002623 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2624 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2625 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2626 // Compute the shift amounts
2627 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2628 // Construct the "on true" case of the select
2629 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2630 Instruction *TSI = BinaryOperator::createLShr(
2631 Op0, TC, SI->getName()+".t");
2632 TSI = InsertNewInstBefore(TSI, I);
2633
2634 // Construct the "on false" case of the select
2635 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2636 Instruction *FSI = BinaryOperator::createLShr(
2637 Op0, FC, SI->getName()+".f");
2638 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002639
Reid Spencer3939b1a2007-03-05 23:36:13 +00002640 // construct the select instruction and return it.
2641 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002642 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002643 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002644 return 0;
2645}
2646
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002647Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650 // Handle the integer div common cases
2651 if (Instruction *Common = commonIDivTransforms(I))
2652 return Common;
2653
2654 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2655 // sdiv X, -1 == -X
2656 if (RHS->isAllOnesValue())
2657 return BinaryOperator::createNeg(Op0);
2658
2659 // -X/C -> X/-C
2660 if (Value *LHSNeg = dyn_castNegVal(Op0))
2661 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2662 }
2663
2664 // If the sign bits of both operands are zero (i.e. we can prove they are
2665 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002666 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002667 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2668 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2669 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2670 }
2671 }
2672
2673 return 0;
2674}
2675
2676Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2677 return commonDivTransforms(I);
2678}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002679
Chris Lattner85dda9a2006-03-02 06:50:58 +00002680/// GetFactor - If we can prove that the specified value is at least a multiple
2681/// of some factor, return that factor.
2682static Constant *GetFactor(Value *V) {
2683 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2684 return CI;
2685
2686 // Unless we can be tricky, we know this is a multiple of 1.
2687 Constant *Result = ConstantInt::get(V->getType(), 1);
2688
2689 Instruction *I = dyn_cast<Instruction>(V);
2690 if (!I) return Result;
2691
2692 if (I->getOpcode() == Instruction::Mul) {
2693 // Handle multiplies by a constant, etc.
2694 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2695 GetFactor(I->getOperand(1)));
2696 } else if (I->getOpcode() == Instruction::Shl) {
2697 // (X<<C) -> X * (1 << C)
2698 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2699 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2700 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2701 }
2702 } else if (I->getOpcode() == Instruction::And) {
2703 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2704 // X & 0xFFF0 is known to be a multiple of 16.
2705 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2706 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2707 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002708 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002709 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002710 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002711 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002712 if (!CI->isIntegerCast())
2713 return Result;
2714 Value *Op = CI->getOperand(0);
2715 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002716 }
2717 return Result;
2718}
2719
Reid Spencer7eb55b32006-11-02 01:53:59 +00002720/// This function implements the transforms on rem instructions that work
2721/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2722/// is used by the visitors to those instructions.
2723/// @brief Transforms common to all three rem instructions
2724Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002726
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002727 // 0 % X == 0, we don't need to preserve faults!
2728 if (Constant *LHS = dyn_cast<Constant>(Op0))
2729 if (LHS->isNullValue())
2730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2731
2732 if (isa<UndefValue>(Op0)) // undef % X -> 0
2733 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2734 if (isa<UndefValue>(Op1))
2735 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002736
2737 // Handle cases involving: rem X, (select Cond, Y, Z)
2738 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2739 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2740 // the same basic block, then we replace the select with Y, and the
2741 // condition of the select with false (if the cond value is in the same
2742 // BB). If the select has uses other than the div, this allows them to be
2743 // simplified also.
2744 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2745 if (ST->isNullValue()) {
2746 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2747 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002748 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002749 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2750 I.setOperand(1, SI->getOperand(2));
2751 else
2752 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002753 return &I;
2754 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002755 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2756 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2757 if (ST->isNullValue()) {
2758 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2759 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002760 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002761 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2762 I.setOperand(1, SI->getOperand(1));
2763 else
2764 UpdateValueUsesWith(SI, SI->getOperand(1));
2765 return &I;
2766 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002767 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002768
Reid Spencer7eb55b32006-11-02 01:53:59 +00002769 return 0;
2770}
2771
2772/// This function implements the transforms common to both integer remainder
2773/// instructions (urem and srem). It is called by the visitors to those integer
2774/// remainder instructions.
2775/// @brief Common integer remainder transforms
2776Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2778
2779 if (Instruction *common = commonRemTransforms(I))
2780 return common;
2781
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002782 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002783 // X % 0 == undef, we don't need to preserve faults!
2784 if (RHS->equalsInt(0))
2785 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2786
Chris Lattner3082c5a2003-02-18 19:28:33 +00002787 if (RHS->equalsInt(1)) // X % 1 == 0
2788 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2789
Chris Lattnerb70f1412006-02-28 05:49:21 +00002790 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2791 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2792 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2793 return R;
2794 } else if (isa<PHINode>(Op0I)) {
2795 if (Instruction *NV = FoldOpIntoPhi(I))
2796 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002797 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002798 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2799 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002800 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002801 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002802 }
2803
Reid Spencer7eb55b32006-11-02 01:53:59 +00002804 return 0;
2805}
2806
2807Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2808 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2809
2810 if (Instruction *common = commonIRemTransforms(I))
2811 return common;
2812
2813 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2814 // X urem C^2 -> X and C
2815 // Check to see if this is an unsigned remainder with an exact power of 2,
2816 // if so, convert to a bitwise and.
2817 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2818 if (isPowerOf2_64(C->getZExtValue()))
2819 return BinaryOperator::createAnd(Op0, SubOne(C));
2820 }
2821
Chris Lattner2e90b732006-02-05 07:54:04 +00002822 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002823 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2824 if (RHSI->getOpcode() == Instruction::Shl &&
2825 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002826 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002827 if (isPowerOf2_64(C1)) {
2828 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2829 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2830 "tmp"), I);
2831 return BinaryOperator::createAnd(Op0, Add);
2832 }
2833 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002834 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002835
Reid Spencer7eb55b32006-11-02 01:53:59 +00002836 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2837 // where C1&C2 are powers of two.
2838 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2839 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2840 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2841 // STO == 0 and SFO == 0 handled above.
2842 if (isPowerOf2_64(STO->getZExtValue()) &&
2843 isPowerOf2_64(SFO->getZExtValue())) {
2844 Value *TrueAnd = InsertNewInstBefore(
2845 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2846 Value *FalseAnd = InsertNewInstBefore(
2847 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2848 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2849 }
2850 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002851 }
2852
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002853 return 0;
2854}
2855
Reid Spencer7eb55b32006-11-02 01:53:59 +00002856Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2857 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859 if (Instruction *common = commonIRemTransforms(I))
2860 return common;
2861
2862 if (Value *RHSNeg = dyn_castNegVal(Op1))
2863 if (!isa<ConstantInt>(RHSNeg) ||
2864 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2865 // X % -Y -> X % Y
2866 AddUsesToWorkList(I);
2867 I.setOperand(1, RHSNeg);
2868 return &I;
2869 }
2870
2871 // If the top bits of both operands are zero (i.e. we can prove they are
2872 // unsigned inputs), turn this into a urem.
2873 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2874 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2875 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2876 return BinaryOperator::createURem(Op0, Op1, I.getName());
2877 }
2878
2879 return 0;
2880}
2881
2882Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002883 return commonRemTransforms(I);
2884}
2885
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002886// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002887static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2888 if (isSigned) {
2889 // Calculate 0111111111..11111
2890 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2891 int64_t Val = INT64_MAX; // All ones
2892 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2893 return C->getSExtValue() == Val-1;
2894 }
Reid Spencera94d3942007-01-19 21:13:56 +00002895 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002896}
2897
2898// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002899static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2900 if (isSigned) {
2901 // Calculate 1111111111000000000000
2902 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2903 int64_t Val = -1; // All ones
2904 Val <<= TypeBits-1; // Shift over to the right spot
2905 return C->getSExtValue() == Val+1;
2906 }
2907 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002908}
2909
Chris Lattner35167c32004-06-09 07:59:58 +00002910// isOneBitSet - Return true if there is exactly one bit set in the specified
2911// constant.
2912static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002913 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002914 return V && (V & (V-1)) == 0;
2915}
2916
Chris Lattner8fc5af42004-09-23 21:46:38 +00002917#if 0 // Currently unused
2918// isLowOnes - Return true if the constant is of the form 0+1+.
2919static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002920 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002921
2922 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002923 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002924
2925 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2926 return U && V && (U & V) == 0;
2927}
2928#endif
2929
2930// isHighOnes - Return true if the constant is of the form 1+0+.
2931// This is the same as lowones(~X).
2932static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002933 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002934 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002935
2936 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002937 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002938
2939 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2940 return U && V && (U & V) == 0;
2941}
2942
Reid Spencer266e42b2006-12-23 06:05:41 +00002943/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002944/// are carefully arranged to allow folding of expressions such as:
2945///
2946/// (A < B) | (A > B) --> (A != B)
2947///
Reid Spencer266e42b2006-12-23 06:05:41 +00002948/// Note that this is only valid if the first and second predicates have the
2949/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002950///
Reid Spencer266e42b2006-12-23 06:05:41 +00002951/// Three bits are used to represent the condition, as follows:
2952/// 0 A > B
2953/// 1 A == B
2954/// 2 A < B
2955///
2956/// <=> Value Definition
2957/// 000 0 Always false
2958/// 001 1 A > B
2959/// 010 2 A == B
2960/// 011 3 A >= B
2961/// 100 4 A < B
2962/// 101 5 A != B
2963/// 110 6 A <= B
2964/// 111 7 Always true
2965///
2966static unsigned getICmpCode(const ICmpInst *ICI) {
2967 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002968 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002969 case ICmpInst::ICMP_UGT: return 1; // 001
2970 case ICmpInst::ICMP_SGT: return 1; // 001
2971 case ICmpInst::ICMP_EQ: return 2; // 010
2972 case ICmpInst::ICMP_UGE: return 3; // 011
2973 case ICmpInst::ICMP_SGE: return 3; // 011
2974 case ICmpInst::ICMP_ULT: return 4; // 100
2975 case ICmpInst::ICMP_SLT: return 4; // 100
2976 case ICmpInst::ICMP_NE: return 5; // 101
2977 case ICmpInst::ICMP_ULE: return 6; // 110
2978 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002979 // True -> 7
2980 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002981 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002982 return 0;
2983 }
2984}
2985
Reid Spencer266e42b2006-12-23 06:05:41 +00002986/// getICmpValue - This is the complement of getICmpCode, which turns an
2987/// opcode and two operands into either a constant true or false, or a brand
2988/// new /// ICmp instruction. The sign is passed in to determine which kind
2989/// of predicate to use in new icmp instructions.
2990static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2991 switch (code) {
2992 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002993 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002994 case 1:
2995 if (sign)
2996 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2997 else
2998 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2999 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3000 case 3:
3001 if (sign)
3002 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3003 else
3004 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3005 case 4:
3006 if (sign)
3007 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3008 else
3009 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3010 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3011 case 6:
3012 if (sign)
3013 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3014 else
3015 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003016 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003017 }
3018}
3019
Reid Spencer266e42b2006-12-23 06:05:41 +00003020static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3021 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3022 (ICmpInst::isSignedPredicate(p1) &&
3023 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3024 (ICmpInst::isSignedPredicate(p2) &&
3025 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3026}
3027
3028namespace {
3029// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3030struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003031 InstCombiner &IC;
3032 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003033 ICmpInst::Predicate pred;
3034 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3035 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3036 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003037 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003038 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3039 if (PredicatesFoldable(pred, ICI->getPredicate()))
3040 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3041 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003042 return false;
3043 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003044 Instruction *apply(Instruction &Log) const {
3045 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3046 if (ICI->getOperand(0) != LHS) {
3047 assert(ICI->getOperand(1) == LHS);
3048 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003049 }
3050
Reid Spencer266e42b2006-12-23 06:05:41 +00003051 unsigned LHSCode = getICmpCode(ICI);
3052 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003053 unsigned Code;
3054 switch (Log.getOpcode()) {
3055 case Instruction::And: Code = LHSCode & RHSCode; break;
3056 case Instruction::Or: Code = LHSCode | RHSCode; break;
3057 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003058 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003059 }
3060
Reid Spencer266e42b2006-12-23 06:05:41 +00003061 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003062 if (Instruction *I = dyn_cast<Instruction>(RV))
3063 return I;
3064 // Otherwise, it's a constant boolean value...
3065 return IC.ReplaceInstUsesWith(Log, RV);
3066 }
3067};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003068} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003069
Chris Lattnerba1cb382003-09-19 17:17:26 +00003070// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3071// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003072// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003073Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003074 ConstantInt *OpRHS,
3075 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003076 BinaryOperator &TheAnd) {
3077 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003078 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003079 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003080 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003081
Chris Lattnerba1cb382003-09-19 17:17:26 +00003082 switch (Op->getOpcode()) {
3083 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003084 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003085 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003086 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003087 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003088 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003089 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003090 }
3091 break;
3092 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003093 if (Together == AndRHS) // (X | C) & C --> C
3094 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003095
Chris Lattner86102b82005-01-01 16:22:27 +00003096 if (Op->hasOneUse() && Together != OpRHS) {
3097 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003098 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003099 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003100 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003101 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003102 }
3103 break;
3104 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003105 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003106 // Adding a one to a single bit bit-field should be turned into an XOR
3107 // of the bit. First thing to check is to see if this AND is with a
3108 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003109 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003110
3111 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00003112 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003113
3114 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003115 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003116 // Ok, at this point, we know that we are masking the result of the
3117 // ADD down to exactly one bit. If the constant we are adding has
3118 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003119 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003120
Chris Lattnerba1cb382003-09-19 17:17:26 +00003121 // Check to see if any bits below the one bit set in AndRHSV are set.
3122 if ((AddRHS & (AndRHSV-1)) == 0) {
3123 // If not, the only thing that can effect the output of the AND is
3124 // the bit specified by AndRHSV. If that bit is set, the effect of
3125 // the XOR is to toggle the bit. If it is clear, then the ADD has
3126 // no effect.
3127 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3128 TheAnd.setOperand(0, X);
3129 return &TheAnd;
3130 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003131 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003132 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003133 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003134 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003135 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003136 }
3137 }
3138 }
3139 }
3140 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003141
3142 case Instruction::Shl: {
3143 // We know that the AND will not produce any of the bits shifted in, so if
3144 // the anded constant includes them, clear them now!
3145 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003146 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00003147 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3148 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003149
Chris Lattner7e794272004-09-24 15:21:34 +00003150 if (CI == ShlMask) { // Masking out bits that the shift already masks
3151 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3152 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003153 TheAnd.setOperand(1, CI);
3154 return &TheAnd;
3155 }
3156 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003157 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003158 case Instruction::LShr:
3159 {
Chris Lattner2da29172003-09-19 19:05:02 +00003160 // We know that the AND will not produce any of the bits shifted in, so if
3161 // the anded constant includes them, clear them now! This only applies to
3162 // unsigned shifts, because a signed shr may bring in set bits!
3163 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003164 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003165 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3166 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003167
Reid Spencerfdff9382006-11-08 06:47:33 +00003168 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3169 return ReplaceInstUsesWith(TheAnd, Op);
3170 } else if (CI != AndRHS) {
3171 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3172 return &TheAnd;
3173 }
3174 break;
3175 }
3176 case Instruction::AShr:
3177 // Signed shr.
3178 // See if this is shifting in some sign extension, then masking it out
3179 // with an and.
3180 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003181 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003182 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003183 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3184 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003185 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003186 // Make the argument unsigned.
3187 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003188 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003189 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003190 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003191 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003192 }
Chris Lattner2da29172003-09-19 19:05:02 +00003193 }
3194 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003195 }
3196 return 0;
3197}
3198
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003199
Chris Lattner6862fbd2004-09-29 17:40:11 +00003200/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3201/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003202/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3203/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003204/// insert new instructions.
3205Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003206 bool isSigned, bool Inside,
3207 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003208 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003209 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003210 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003211
Chris Lattner6862fbd2004-09-29 17:40:11 +00003212 if (Inside) {
3213 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003214 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003215
Reid Spencer266e42b2006-12-23 06:05:41 +00003216 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003217 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003218 ICmpInst::Predicate pred = (isSigned ?
3219 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3220 return new ICmpInst(pred, V, Hi);
3221 }
3222
3223 // Emit V-Lo <u Hi-Lo
3224 Constant *NegLo = ConstantExpr::getNeg(Lo);
3225 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003226 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003227 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3228 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003229 }
3230
3231 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003232 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003233
Reid Spencer266e42b2006-12-23 06:05:41 +00003234 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003235 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003236 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003237 ICmpInst::Predicate pred = (isSigned ?
3238 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3239 return new ICmpInst(pred, V, Hi);
3240 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003241
Reid Spencer266e42b2006-12-23 06:05:41 +00003242 // Emit V-Lo > Hi-1-Lo
3243 Constant *NegLo = ConstantExpr::getNeg(Lo);
3244 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003245 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003246 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3247 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003248}
3249
Chris Lattnerb4b25302005-09-18 07:22:02 +00003250// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3251// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3252// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3253// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003254static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003255 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003256 if (!isShiftedMask_64(V)) return false;
3257
3258 // look for the first zero bit after the run of ones
3259 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3260 // look for the first non-zero bit
3261 ME = 64-CountLeadingZeros_64(V);
3262 return true;
3263}
3264
3265
3266
3267/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3268/// where isSub determines whether the operator is a sub. If we can fold one of
3269/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003270///
3271/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3272/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3273/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3274///
3275/// return (A +/- B).
3276///
3277Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003278 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003279 Instruction &I) {
3280 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3281 if (!LHSI || LHSI->getNumOperands() != 2 ||
3282 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3283
3284 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3285
3286 switch (LHSI->getOpcode()) {
3287 default: return 0;
3288 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003289 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3290 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003291 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003292 break;
3293
3294 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3295 // part, we don't need any explicit masks to take them out of A. If that
3296 // is all N is, ignore it.
3297 unsigned MB, ME;
3298 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003299 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003300 Mask >>= 64-MB+1;
3301 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003302 break;
3303 }
3304 }
Chris Lattneraf517572005-09-18 04:24:45 +00003305 return 0;
3306 case Instruction::Or:
3307 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003308 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003309 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003310 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003311 break;
3312 return 0;
3313 }
3314
3315 Instruction *New;
3316 if (isSub)
3317 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3318 else
3319 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3320 return InsertNewInstBefore(New, I);
3321}
3322
Chris Lattner113f4f42002-06-25 16:13:24 +00003323Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003324 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003325 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003326
Chris Lattner81a7a232004-10-16 18:11:37 +00003327 if (isa<UndefValue>(Op1)) // X & undef -> 0
3328 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3329
Chris Lattner86102b82005-01-01 16:22:27 +00003330 // and X, X = X
3331 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003332 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003333
Chris Lattner5b2edb12006-02-12 08:02:11 +00003334 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003335 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003336 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003337 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003338 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003339 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003340 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003341 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003342 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003343 if (CP->isAllOnesValue())
3344 return ReplaceInstUsesWith(I, I.getOperand(0));
3345 }
3346 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003347
Zhou Sheng75b871f2007-01-11 12:24:14 +00003348 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003349 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003350 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003351 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003352
Chris Lattnerba1cb382003-09-19 17:17:26 +00003353 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003354 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003355 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003356 Value *Op0LHS = Op0I->getOperand(0);
3357 Value *Op0RHS = Op0I->getOperand(1);
3358 switch (Op0I->getOpcode()) {
3359 case Instruction::Xor:
3360 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003361 // If the mask is only needed on one incoming arm, push it up.
3362 if (Op0I->hasOneUse()) {
3363 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3364 // Not masking anything out for the LHS, move to RHS.
3365 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3366 Op0RHS->getName()+".masked");
3367 InsertNewInstBefore(NewRHS, I);
3368 return BinaryOperator::create(
3369 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003370 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003371 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003372 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3373 // Not masking anything out for the RHS, move to LHS.
3374 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3375 Op0LHS->getName()+".masked");
3376 InsertNewInstBefore(NewLHS, I);
3377 return BinaryOperator::create(
3378 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3379 }
3380 }
3381
Chris Lattner86102b82005-01-01 16:22:27 +00003382 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003383 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003384 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3385 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3386 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3387 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3388 return BinaryOperator::createAnd(V, AndRHS);
3389 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3390 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003391 break;
3392
3393 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003394 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3395 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3396 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3397 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3398 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003399 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003400 }
3401
Chris Lattner16464b32003-07-23 19:25:52 +00003402 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003403 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003404 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003405 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003406 // If this is an integer truncation or change from signed-to-unsigned, and
3407 // if the source is an and/or with immediate, transform it. This
3408 // frequently occurs for bitfield accesses.
3409 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003410 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003411 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003412 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003413 if (CastOp->getOpcode() == Instruction::And) {
3414 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003415 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3416 // This will fold the two constants together, which may allow
3417 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003418 Instruction *NewCast = CastInst::createTruncOrBitCast(
3419 CastOp->getOperand(0), I.getType(),
3420 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003421 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003422 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003423 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003424 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003425 return BinaryOperator::createAnd(NewCast, C3);
3426 } else if (CastOp->getOpcode() == Instruction::Or) {
3427 // Change: and (cast (or X, C1) to T), C2
3428 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003429 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003430 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3431 return ReplaceInstUsesWith(I, AndRHS);
3432 }
3433 }
Chris Lattner33217db2003-07-23 19:36:21 +00003434 }
Chris Lattner183b3362004-04-09 19:05:30 +00003435
3436 // Try to fold constant and into select arguments.
3437 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003438 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003439 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003440 if (isa<PHINode>(Op0))
3441 if (Instruction *NV = FoldOpIntoPhi(I))
3442 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003443 }
3444
Chris Lattnerbb74e222003-03-10 23:06:50 +00003445 Value *Op0NotVal = dyn_castNotVal(Op0);
3446 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003447
Chris Lattner023a4832004-06-18 06:07:51 +00003448 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3450
Misha Brukman9c003d82004-07-30 12:50:08 +00003451 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003452 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003453 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3454 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003455 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003456 return BinaryOperator::createNot(Or);
3457 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003458
3459 {
3460 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003461 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3462 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3463 return ReplaceInstUsesWith(I, Op1);
3464 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3465 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3466 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003467
3468 if (Op0->hasOneUse() &&
3469 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3470 if (A == Op1) { // (A^B)&A -> A&(A^B)
3471 I.swapOperands(); // Simplify below
3472 std::swap(Op0, Op1);
3473 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3474 cast<BinaryOperator>(Op0)->swapOperands();
3475 I.swapOperands(); // Simplify below
3476 std::swap(Op0, Op1);
3477 }
3478 }
3479 if (Op1->hasOneUse() &&
3480 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3481 if (B == Op0) { // B&(A^B) -> B&(B^A)
3482 cast<BinaryOperator>(Op1)->swapOperands();
3483 std::swap(A, B);
3484 }
3485 if (A == Op0) { // A&(A^B) -> A & ~B
3486 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3487 InsertNewInstBefore(NotB, I);
3488 return BinaryOperator::createAnd(A, NotB);
3489 }
3490 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003491 }
3492
Reid Spencer266e42b2006-12-23 06:05:41 +00003493 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3494 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3495 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003496 return R;
3497
Chris Lattner623826c2004-09-28 21:48:02 +00003498 Value *LHSVal, *RHSVal;
3499 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003500 ICmpInst::Predicate LHSCC, RHSCC;
3501 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3502 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3503 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3504 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3505 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3506 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3507 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3508 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003509 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003510 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3511 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3512 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3513 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003514 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003515 std::swap(LHS, RHS);
3516 std::swap(LHSCst, RHSCst);
3517 std::swap(LHSCC, RHSCC);
3518 }
3519
Reid Spencer266e42b2006-12-23 06:05:41 +00003520 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003521 // comparing a value against two constants and and'ing the result
3522 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003523 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3524 // (from the FoldICmpLogical check above), that the two constants
3525 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003526 assert(LHSCst != RHSCst && "Compares not folded above?");
3527
3528 switch (LHSCC) {
3529 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003530 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003531 switch (RHSCC) {
3532 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003533 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3534 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3535 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003536 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003537 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3538 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3539 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003540 return ReplaceInstUsesWith(I, LHS);
3541 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003542 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003543 switch (RHSCC) {
3544 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003545 case ICmpInst::ICMP_ULT:
3546 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3547 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3548 break; // (X != 13 & X u< 15) -> no change
3549 case ICmpInst::ICMP_SLT:
3550 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3551 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3552 break; // (X != 13 & X s< 15) -> no change
3553 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3554 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3555 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003556 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003557 case ICmpInst::ICMP_NE:
3558 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003559 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3560 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3561 LHSVal->getName()+".off");
3562 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003563 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3564 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003565 }
3566 break; // (X != 13 & X != 15) -> no change
3567 }
3568 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003569 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003570 switch (RHSCC) {
3571 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003572 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3573 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003574 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003575 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3576 break;
3577 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3578 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003579 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003580 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3581 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003582 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003583 break;
3584 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003585 switch (RHSCC) {
3586 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003587 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3588 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003589 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003590 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3591 break;
3592 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3593 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003594 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003595 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3596 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003597 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003598 break;
3599 case ICmpInst::ICMP_UGT:
3600 switch (RHSCC) {
3601 default: assert(0 && "Unknown integer condition code!");
3602 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3603 return ReplaceInstUsesWith(I, LHS);
3604 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3605 return ReplaceInstUsesWith(I, RHS);
3606 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3607 break;
3608 case ICmpInst::ICMP_NE:
3609 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3610 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3611 break; // (X u> 13 & X != 15) -> no change
3612 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3613 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3614 true, I);
3615 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3616 break;
3617 }
3618 break;
3619 case ICmpInst::ICMP_SGT:
3620 switch (RHSCC) {
3621 default: assert(0 && "Unknown integer condition code!");
3622 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3623 return ReplaceInstUsesWith(I, LHS);
3624 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3625 return ReplaceInstUsesWith(I, RHS);
3626 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3627 break;
3628 case ICmpInst::ICMP_NE:
3629 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3630 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3631 break; // (X s> 13 & X != 15) -> no change
3632 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3633 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3634 true, I);
3635 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3636 break;
3637 }
3638 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003639 }
3640 }
3641 }
3642
Chris Lattner3af10532006-05-05 06:39:07 +00003643 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003644 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3645 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3646 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3647 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003648 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003649 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003650 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3651 I.getType(), TD) &&
3652 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3653 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003654 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3655 Op1C->getOperand(0),
3656 I.getName());
3657 InsertNewInstBefore(NewOp, I);
3658 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3659 }
Chris Lattner3af10532006-05-05 06:39:07 +00003660 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003661
3662 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003663 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3664 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3665 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003666 SI0->getOperand(1) == SI1->getOperand(1) &&
3667 (SI0->hasOneUse() || SI1->hasOneUse())) {
3668 Instruction *NewOp =
3669 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3670 SI1->getOperand(0),
3671 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003672 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3673 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003674 }
Chris Lattner3af10532006-05-05 06:39:07 +00003675 }
3676
Chris Lattner113f4f42002-06-25 16:13:24 +00003677 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003678}
3679
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003680/// CollectBSwapParts - Look to see if the specified value defines a single byte
3681/// in the result. If it does, and if the specified byte hasn't been filled in
3682/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003683static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003684 Instruction *I = dyn_cast<Instruction>(V);
3685 if (I == 0) return true;
3686
3687 // If this is an or instruction, it is an inner node of the bswap.
3688 if (I->getOpcode() == Instruction::Or)
3689 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3690 CollectBSwapParts(I->getOperand(1), ByteValues);
3691
3692 // If this is a shift by a constant int, and it is "24", then its operand
3693 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003694 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003695 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003696 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003697 8*(ByteValues.size()-1))
3698 return true;
3699
3700 unsigned DestNo;
3701 if (I->getOpcode() == Instruction::Shl) {
3702 // X << 24 defines the top byte with the lowest of the input bytes.
3703 DestNo = ByteValues.size()-1;
3704 } else {
3705 // X >>u 24 defines the low byte with the highest of the input bytes.
3706 DestNo = 0;
3707 }
3708
3709 // If the destination byte value is already defined, the values are or'd
3710 // together, which isn't a bswap (unless it's an or of the same bits).
3711 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3712 return true;
3713 ByteValues[DestNo] = I->getOperand(0);
3714 return false;
3715 }
3716
3717 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3718 // don't have this.
3719 Value *Shift = 0, *ShiftLHS = 0;
3720 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3721 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3722 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3723 return true;
3724 Instruction *SI = cast<Instruction>(Shift);
3725
3726 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003727 if (ShiftAmt->getZExtValue() & 7 ||
3728 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003729 return true;
3730
3731 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3732 unsigned DestByte;
3733 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003734 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003735 break;
3736 // Unknown mask for bswap.
3737 if (DestByte == ByteValues.size()) return true;
3738
Reid Spencere0fc4df2006-10-20 07:07:24 +00003739 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003740 unsigned SrcByte;
3741 if (SI->getOpcode() == Instruction::Shl)
3742 SrcByte = DestByte - ShiftBytes;
3743 else
3744 SrcByte = DestByte + ShiftBytes;
3745
3746 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3747 if (SrcByte != ByteValues.size()-DestByte-1)
3748 return true;
3749
3750 // If the destination byte value is already defined, the values are or'd
3751 // together, which isn't a bswap (unless it's an or of the same bits).
3752 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3753 return true;
3754 ByteValues[DestByte] = SI->getOperand(0);
3755 return false;
3756}
3757
3758/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3759/// If so, insert the new bswap intrinsic and return it.
3760Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003761 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003762 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003763 return 0;
3764
3765 /// ByteValues - For each byte of the result, we keep track of which value
3766 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003767 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003768 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003769
3770 // Try to find all the pieces corresponding to the bswap.
3771 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3772 CollectBSwapParts(I.getOperand(1), ByteValues))
3773 return 0;
3774
3775 // Check to see if all of the bytes come from the same value.
3776 Value *V = ByteValues[0];
3777 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3778
3779 // Check to make sure that all of the bytes come from the same value.
3780 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3781 if (ByteValues[i] != V)
3782 return 0;
3783
3784 // If they do then *success* we can turn this into a bswap. Figure out what
3785 // bswap to make it into.
3786 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003787 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003788 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003789 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003790 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003791 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003792 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003793 FnName = "llvm.bswap.i64";
3794 else
3795 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003796 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003797 return new CallInst(F, V);
3798}
3799
3800
Chris Lattner113f4f42002-06-25 16:13:24 +00003801Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003802 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003803 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003804
Chris Lattner81a7a232004-10-16 18:11:37 +00003805 if (isa<UndefValue>(Op1))
3806 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003807 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003808
Chris Lattner5b2edb12006-02-12 08:02:11 +00003809 // or X, X = X
3810 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003811 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003812
Chris Lattner5b2edb12006-02-12 08:02:11 +00003813 // See if we can simplify any instructions used by the instruction whose sole
3814 // purpose is to compute bits we don't care about.
3815 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003816 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003817 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003818 KnownZero, KnownOne))
3819 return &I;
3820
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003821 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003822 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003823 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003824 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3825 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003826 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003827 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003828 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003829 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3830 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003831
Chris Lattnerd4252a72004-07-30 07:50:03 +00003832 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3833 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003834 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003835 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003836 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003837 return BinaryOperator::createXor(Or,
3838 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003839 }
Chris Lattner183b3362004-04-09 19:05:30 +00003840
3841 // Try to fold constant and into select arguments.
3842 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003843 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003844 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003845 if (isa<PHINode>(Op0))
3846 if (Instruction *NV = FoldOpIntoPhi(I))
3847 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003848 }
3849
Chris Lattner330628a2006-01-06 17:59:59 +00003850 Value *A = 0, *B = 0;
3851 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003852
3853 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3854 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3855 return ReplaceInstUsesWith(I, Op1);
3856 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3857 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3858 return ReplaceInstUsesWith(I, Op0);
3859
Chris Lattnerb7845d62006-07-10 20:25:24 +00003860 // (A | B) | C and A | (B | C) -> bswap if possible.
3861 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003862 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003863 match(Op1, m_Or(m_Value(), m_Value())) ||
3864 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3865 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003866 if (Instruction *BSwap = MatchBSwap(I))
3867 return BSwap;
3868 }
3869
Chris Lattnerb62f5082005-05-09 04:58:36 +00003870 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3871 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003872 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003873 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3874 InsertNewInstBefore(NOr, I);
3875 NOr->takeName(Op0);
3876 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003877 }
3878
3879 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3880 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003881 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003882 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3883 InsertNewInstBefore(NOr, I);
3884 NOr->takeName(Op0);
3885 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003886 }
3887
Chris Lattner15212982005-09-18 03:42:07 +00003888 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003889 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003890 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3891
3892 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3893 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3894
3895
Chris Lattner01f56c62005-09-18 06:02:59 +00003896 // If we have: ((V + N) & C1) | (V & C2)
3897 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3898 // replace with V+N.
3899 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003900 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003901 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003902 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3903 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003904 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003905 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003906 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003907 return ReplaceInstUsesWith(I, A);
3908 }
3909 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003910 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003911 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3912 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003913 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003914 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003915 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003916 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003917 }
3918 }
3919 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003920
3921 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003922 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3923 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3924 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003925 SI0->getOperand(1) == SI1->getOperand(1) &&
3926 (SI0->hasOneUse() || SI1->hasOneUse())) {
3927 Instruction *NewOp =
3928 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3929 SI1->getOperand(0),
3930 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003931 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3932 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003933 }
3934 }
Chris Lattner812aab72003-08-12 19:11:07 +00003935
Chris Lattnerd4252a72004-07-30 07:50:03 +00003936 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3937 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003938 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003939 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003940 } else {
3941 A = 0;
3942 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003943 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003944 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3945 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003946 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003947 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003948
Misha Brukman9c003d82004-07-30 12:50:08 +00003949 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003950 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3951 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3952 I.getName()+".demorgan"), I);
3953 return BinaryOperator::createNot(And);
3954 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003955 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003956
Reid Spencer266e42b2006-12-23 06:05:41 +00003957 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3958 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3959 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003960 return R;
3961
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003962 Value *LHSVal, *RHSVal;
3963 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003964 ICmpInst::Predicate LHSCC, RHSCC;
3965 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3966 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3967 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3968 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3969 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3970 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3971 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3972 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003973 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003974 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3975 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3976 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3977 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003978 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003979 std::swap(LHS, RHS);
3980 std::swap(LHSCst, RHSCst);
3981 std::swap(LHSCC, RHSCC);
3982 }
3983
Reid Spencer266e42b2006-12-23 06:05:41 +00003984 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003985 // comparing a value against two constants and or'ing the result
3986 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003987 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3988 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003989 // equal.
3990 assert(LHSCst != RHSCst && "Compares not folded above?");
3991
3992 switch (LHSCC) {
3993 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003994 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003995 switch (RHSCC) {
3996 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003997 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003998 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3999 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4000 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4001 LHSVal->getName()+".off");
4002 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004003 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004004 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004005 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004006 break; // (X == 13 | X == 15) -> no change
4007 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4008 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004009 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004010 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4011 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4012 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004013 return ReplaceInstUsesWith(I, RHS);
4014 }
4015 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004017 switch (RHSCC) {
4018 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004019 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4020 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4021 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004022 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004023 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4024 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4025 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004026 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004027 }
4028 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004029 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004030 switch (RHSCC) {
4031 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004032 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004033 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4035 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4036 false, I);
4037 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4038 break;
4039 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4040 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004041 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004042 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4043 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004044 }
4045 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004047 switch (RHSCC) {
4048 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004049 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4050 break;
4051 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4052 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4053 false, I);
4054 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4055 break;
4056 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4057 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4058 return ReplaceInstUsesWith(I, RHS);
4059 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4060 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004061 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004062 break;
4063 case ICmpInst::ICMP_UGT:
4064 switch (RHSCC) {
4065 default: assert(0 && "Unknown integer condition code!");
4066 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4067 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4068 return ReplaceInstUsesWith(I, LHS);
4069 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4070 break;
4071 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4072 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004073 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004074 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4075 break;
4076 }
4077 break;
4078 case ICmpInst::ICMP_SGT:
4079 switch (RHSCC) {
4080 default: assert(0 && "Unknown integer condition code!");
4081 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4082 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4083 return ReplaceInstUsesWith(I, LHS);
4084 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4085 break;
4086 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4087 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004088 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004089 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4090 break;
4091 }
4092 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004093 }
4094 }
4095 }
Chris Lattner3af10532006-05-05 06:39:07 +00004096
4097 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004098 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004099 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004100 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4101 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004102 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004103 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004104 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4105 I.getType(), TD) &&
4106 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4107 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004108 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4109 Op1C->getOperand(0),
4110 I.getName());
4111 InsertNewInstBefore(NewOp, I);
4112 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4113 }
Chris Lattner3af10532006-05-05 06:39:07 +00004114 }
Chris Lattner3af10532006-05-05 06:39:07 +00004115
Chris Lattner15212982005-09-18 03:42:07 +00004116
Chris Lattner113f4f42002-06-25 16:13:24 +00004117 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004118}
4119
Chris Lattnerc2076352004-02-16 01:20:27 +00004120// XorSelf - Implements: X ^ X --> 0
4121struct XorSelf {
4122 Value *RHS;
4123 XorSelf(Value *rhs) : RHS(rhs) {}
4124 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4125 Instruction *apply(BinaryOperator &Xor) const {
4126 return &Xor;
4127 }
4128};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004129
4130
Chris Lattner113f4f42002-06-25 16:13:24 +00004131Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004132 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004134
Chris Lattner81a7a232004-10-16 18:11:37 +00004135 if (isa<UndefValue>(Op1))
4136 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4137
Chris Lattnerc2076352004-02-16 01:20:27 +00004138 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4139 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4140 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004142 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004143
4144 // See if we can simplify any instructions used by the instruction whose sole
4145 // purpose is to compute bits we don't care about.
4146 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004147 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004148 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004149 KnownZero, KnownOne))
4150 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004151
Zhou Sheng75b871f2007-01-11 12:24:14 +00004152 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004153 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4154 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004155 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004156 return new ICmpInst(ICI->getInversePredicate(),
4157 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004158
Reid Spencer266e42b2006-12-23 06:05:41 +00004159 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004160 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004161 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4162 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004163 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4164 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004165 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004166 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004167 }
Chris Lattner023a4832004-06-18 06:07:51 +00004168
4169 // ~(~X & Y) --> (X | ~Y)
4170 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4171 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4172 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4173 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004174 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004175 Op0I->getOperand(1)->getName()+".not");
4176 InsertNewInstBefore(NotY, I);
4177 return BinaryOperator::createOr(Op0NotVal, NotY);
4178 }
4179 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004180
Chris Lattner97638592003-07-23 21:37:07 +00004181 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004182 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004183 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004184 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004185 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4186 return BinaryOperator::createSub(
4187 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004188 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004189 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004190 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004191 } else if (Op0I->getOpcode() == Instruction::Or) {
4192 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4193 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4194 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4195 // Anything in both C1 and C2 is known to be zero, remove it from
4196 // NewRHS.
4197 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4198 NewRHS = ConstantExpr::getAnd(NewRHS,
4199 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004200 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004201 I.setOperand(0, Op0I->getOperand(0));
4202 I.setOperand(1, NewRHS);
4203 return &I;
4204 }
Chris Lattner97638592003-07-23 21:37:07 +00004205 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004206 }
Chris Lattner183b3362004-04-09 19:05:30 +00004207
4208 // Try to fold constant and into select arguments.
4209 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004210 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004211 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004212 if (isa<PHINode>(Op0))
4213 if (Instruction *NV = FoldOpIntoPhi(I))
4214 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004215 }
4216
Chris Lattnerbb74e222003-03-10 23:06:50 +00004217 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004218 if (X == Op1)
4219 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004220 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004221
Chris Lattnerbb74e222003-03-10 23:06:50 +00004222 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004223 if (X == Op0)
4224 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004225 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004226
Chris Lattnerdcd07922006-04-01 08:03:55 +00004227 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00004228 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004229 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004230 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004231 I.swapOperands();
4232 std::swap(Op0, Op1);
4233 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004234 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004235 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004236 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004237 } else if (Op1I->getOpcode() == Instruction::Xor) {
4238 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4239 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4240 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4241 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004242 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4243 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4244 Op1I->swapOperands();
4245 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4246 I.swapOperands(); // Simplified below.
4247 std::swap(Op0, Op1);
4248 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004249 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004250
Chris Lattnerdcd07922006-04-01 08:03:55 +00004251 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004252 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004253 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004254 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004255 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004256 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4257 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004258 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004259 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004260 } else if (Op0I->getOpcode() == Instruction::Xor) {
4261 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4262 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4263 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4264 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004265 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4266 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4267 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004268 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4269 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004270 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4271 InsertNewInstBefore(N, I);
4272 return BinaryOperator::createAnd(N, Op1);
4273 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004274 }
4275
Reid Spencer266e42b2006-12-23 06:05:41 +00004276 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4277 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4278 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004279 return R;
4280
Chris Lattner3af10532006-05-05 06:39:07 +00004281 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004282 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004283 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004284 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4285 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004286 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004287 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004288 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4289 I.getType(), TD) &&
4290 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4291 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004292 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4293 Op1C->getOperand(0),
4294 I.getName());
4295 InsertNewInstBefore(NewOp, I);
4296 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4297 }
Chris Lattner3af10532006-05-05 06:39:07 +00004298 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004299
4300 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004301 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4302 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4303 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004304 SI0->getOperand(1) == SI1->getOperand(1) &&
4305 (SI0->hasOneUse() || SI1->hasOneUse())) {
4306 Instruction *NewOp =
4307 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4308 SI1->getOperand(0),
4309 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004310 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4311 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004312 }
4313 }
Chris Lattner3af10532006-05-05 06:39:07 +00004314
Chris Lattner113f4f42002-06-25 16:13:24 +00004315 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004316}
4317
Chris Lattner6862fbd2004-09-29 17:40:11 +00004318static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004319 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004320}
4321
4322/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4323/// overflowed for this type.
4324static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4325 ConstantInt *In2) {
4326 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4327
Reid Spencerc635f472006-12-31 05:48:39 +00004328 return cast<ConstantInt>(Result)->getZExtValue() <
4329 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004330}
4331
Chris Lattner0798af32005-01-13 20:14:25 +00004332/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4333/// code necessary to compute the offset from the base pointer (without adding
4334/// in the base pointer). Return the result as a signed integer of intptr size.
4335static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4336 TargetData &TD = IC.getTargetData();
4337 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004338 const Type *IntPtrTy = TD.getIntPtrType();
4339 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004340
4341 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004342 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004343
Chris Lattner0798af32005-01-13 20:14:25 +00004344 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4345 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004346 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004347 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004348 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4349 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004350 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004351 Scale = ConstantExpr::getMul(OpC, Scale);
4352 if (Constant *RC = dyn_cast<Constant>(Result))
4353 Result = ConstantExpr::getAdd(RC, Scale);
4354 else {
4355 // Emit an add instruction.
4356 Result = IC.InsertNewInstBefore(
4357 BinaryOperator::createAdd(Result, Scale,
4358 GEP->getName()+".offs"), I);
4359 }
4360 }
4361 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004362 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004363 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004364 Op->getName()+".c"), I);
4365 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004366 // We'll let instcombine(mul) convert this to a shl if possible.
4367 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4368 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004369
4370 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004371 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004372 GEP->getName()+".offs"), I);
4373 }
4374 }
4375 return Result;
4376}
4377
Reid Spencer266e42b2006-12-23 06:05:41 +00004378/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004379/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004380Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4381 ICmpInst::Predicate Cond,
4382 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004383 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004384
4385 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4386 if (isa<PointerType>(CI->getOperand(0)->getType()))
4387 RHS = CI->getOperand(0);
4388
Chris Lattner0798af32005-01-13 20:14:25 +00004389 Value *PtrBase = GEPLHS->getOperand(0);
4390 if (PtrBase == RHS) {
4391 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004392 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4393 // each index is zero or not.
4394 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004395 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004396 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4397 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004398 bool EmitIt = true;
4399 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4400 if (isa<UndefValue>(C)) // undef index -> undef.
4401 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4402 if (C->isNullValue())
4403 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004404 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4405 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004406 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004407 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004408 ConstantInt::get(Type::Int1Ty,
4409 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004410 }
4411
4412 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004413 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004414 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004415 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4416 if (InVal == 0)
4417 InVal = Comp;
4418 else {
4419 InVal = InsertNewInstBefore(InVal, I);
4420 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004422 InVal = BinaryOperator::createOr(InVal, Comp);
4423 else // True if all are equal
4424 InVal = BinaryOperator::createAnd(InVal, Comp);
4425 }
4426 }
4427 }
4428
4429 if (InVal)
4430 return InVal;
4431 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004433 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4434 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004435 }
Chris Lattner0798af32005-01-13 20:14:25 +00004436
Reid Spencer266e42b2006-12-23 06:05:41 +00004437 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004438 // the result to fold to a constant!
4439 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4440 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4441 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004442 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4443 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004444 }
4445 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004446 // If the base pointers are different, but the indices are the same, just
4447 // compare the base pointer.
4448 if (PtrBase != GEPRHS->getOperand(0)) {
4449 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004450 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004451 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004452 if (IndicesTheSame)
4453 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4454 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4455 IndicesTheSame = false;
4456 break;
4457 }
4458
4459 // If all indices are the same, just compare the base pointers.
4460 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004461 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4462 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004463
4464 // Otherwise, the base pointers are different and the indices are
4465 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004466 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004467 }
Chris Lattner0798af32005-01-13 20:14:25 +00004468
Chris Lattner81e84172005-01-13 22:25:21 +00004469 // If one of the GEPs has all zero indices, recurse.
4470 bool AllZeros = true;
4471 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4472 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4473 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4474 AllZeros = false;
4475 break;
4476 }
4477 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004478 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4479 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004480
4481 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004482 AllZeros = true;
4483 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4484 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4485 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4486 AllZeros = false;
4487 break;
4488 }
4489 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004490 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004491
Chris Lattner4fa89822005-01-14 00:20:05 +00004492 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4493 // If the GEPs only differ by one index, compare it.
4494 unsigned NumDifferences = 0; // Keep track of # differences.
4495 unsigned DiffOperand = 0; // The operand that differs.
4496 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4497 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004498 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4499 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004500 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004501 NumDifferences = 2;
4502 break;
4503 } else {
4504 if (NumDifferences++) break;
4505 DiffOperand = i;
4506 }
4507 }
4508
4509 if (NumDifferences == 0) // SAME GEP?
4510 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004511 ConstantInt::get(Type::Int1Ty,
4512 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004513 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004514 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4515 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004516 // Make sure we do a signed comparison here.
4517 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004518 }
4519 }
4520
Reid Spencer266e42b2006-12-23 06:05:41 +00004521 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004522 // the result to fold to a constant!
4523 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4524 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4525 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4526 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4527 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004528 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004529 }
4530 }
4531 return 0;
4532}
4533
Reid Spencer266e42b2006-12-23 06:05:41 +00004534Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4535 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004537
Chris Lattner6ee923f2007-01-14 19:42:17 +00004538 // Fold trivial predicates.
4539 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4540 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4541 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4542 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4543
4544 // Simplify 'fcmp pred X, X'
4545 if (Op0 == Op1) {
4546 switch (I.getPredicate()) {
4547 default: assert(0 && "Unknown predicate!");
4548 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4549 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4550 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4551 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4552 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4553 case FCmpInst::FCMP_OLT: // True if ordered and less than
4554 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4556
4557 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4558 case FCmpInst::FCMP_ULT: // True if unordered or less than
4559 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4560 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4561 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4562 I.setPredicate(FCmpInst::FCMP_UNO);
4563 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4564 return &I;
4565
4566 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4567 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4568 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4569 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4570 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4571 I.setPredicate(FCmpInst::FCMP_ORD);
4572 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4573 return &I;
4574 }
4575 }
4576
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004578 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004579
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 // Handle fcmp with constant RHS
4581 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4582 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4583 switch (LHSI->getOpcode()) {
4584 case Instruction::PHI:
4585 if (Instruction *NV = FoldOpIntoPhi(I))
4586 return NV;
4587 break;
4588 case Instruction::Select:
4589 // If either operand of the select is a constant, we can fold the
4590 // comparison into the select arms, which will cause one to be
4591 // constant folded and the select turned into a bitwise or.
4592 Value *Op1 = 0, *Op2 = 0;
4593 if (LHSI->hasOneUse()) {
4594 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4595 // Fold the known value into the constant operand.
4596 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4597 // Insert a new FCmp of the other select operand.
4598 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4599 LHSI->getOperand(2), RHSC,
4600 I.getName()), I);
4601 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4602 // Fold the known value into the constant operand.
4603 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4604 // Insert a new FCmp of the other select operand.
4605 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4606 LHSI->getOperand(1), RHSC,
4607 I.getName()), I);
4608 }
4609 }
4610
4611 if (Op1)
4612 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4613 break;
4614 }
4615 }
4616
4617 return Changed ? &I : 0;
4618}
4619
4620Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4621 bool Changed = SimplifyCompare(I);
4622 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4623 const Type *Ty = Op0->getType();
4624
4625 // icmp X, X
4626 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004627 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4628 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004629
4630 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004631 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004632
4633 // icmp of GlobalValues can never equal each other as long as they aren't
4634 // external weak linkage type.
4635 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4636 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4637 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004638 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4639 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004640
4641 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004642 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004643 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4644 isa<ConstantPointerNull>(Op0)) &&
4645 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004646 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004647 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4648 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004649
Reid Spencer266e42b2006-12-23 06:05:41 +00004650 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004651 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004652 switch (I.getPredicate()) {
4653 default: assert(0 && "Invalid icmp instruction!");
4654 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004655 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004656 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004657 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004658 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004659 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004660 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004661
Reid Spencer266e42b2006-12-23 06:05:41 +00004662 case ICmpInst::ICMP_UGT:
4663 case ICmpInst::ICMP_SGT:
4664 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004665 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004666 case ICmpInst::ICMP_ULT:
4667 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004668 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4669 InsertNewInstBefore(Not, I);
4670 return BinaryOperator::createAnd(Not, Op1);
4671 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004672 case ICmpInst::ICMP_UGE:
4673 case ICmpInst::ICMP_SGE:
4674 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004675 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004676 case ICmpInst::ICMP_ULE:
4677 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004678 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4679 InsertNewInstBefore(Not, I);
4680 return BinaryOperator::createOr(Not, Op1);
4681 }
4682 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004683 }
4684
Chris Lattner2dd01742004-06-09 04:24:29 +00004685 // See if we are doing a comparison between a constant and an instruction that
4686 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004687 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004688 switch (I.getPredicate()) {
4689 default: break;
4690 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4691 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004692 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004693 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4694 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4695 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4696 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4697 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004698
Reid Spencer266e42b2006-12-23 06:05:41 +00004699 case ICmpInst::ICMP_SLT:
4700 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004702 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4703 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4704 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4705 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4706 break;
4707
4708 case ICmpInst::ICMP_UGT:
4709 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004710 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004711 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4712 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4713 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4714 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4715 break;
4716
4717 case ICmpInst::ICMP_SGT:
4718 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004719 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004720 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4721 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4722 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4723 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4724 break;
4725
4726 case ICmpInst::ICMP_ULE:
4727 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004728 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004729 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4730 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4731 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4732 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4733 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004734
Reid Spencer266e42b2006-12-23 06:05:41 +00004735 case ICmpInst::ICMP_SLE:
4736 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004737 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004738 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4739 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4740 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4741 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4742 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004743
Reid Spencer266e42b2006-12-23 06:05:41 +00004744 case ICmpInst::ICMP_UGE:
4745 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004746 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004747 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4748 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4749 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4750 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4751 break;
4752
4753 case ICmpInst::ICMP_SGE:
4754 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004755 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004756 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4757 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4758 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4759 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4760 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004761 }
4762
Reid Spencer266e42b2006-12-23 06:05:41 +00004763 // If we still have a icmp le or icmp ge instruction, turn it into the
4764 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004765 // already been handled above, this requires little checking.
4766 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004767 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4768 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4769 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4770 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4771 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4772 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4773 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4774 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004775
4776 // See if we can fold the comparison based on bits known to be zero or one
4777 // in the input.
4778 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004779 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004780 KnownZero, KnownOne, 0))
4781 return &I;
4782
4783 // Given the known and unknown bits, compute a range that the LHS could be
4784 // in.
4785 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004786 // Compute the Min, Max and RHS values based on the known bits. For the
4787 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004788 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4789 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004790 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4791 SRHSVal = CI->getSExtValue();
4792 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4793 SMax);
4794 } else {
4795 URHSVal = CI->getZExtValue();
4796 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4797 UMax);
4798 }
4799 switch (I.getPredicate()) { // LE/GE have been folded already.
4800 default: assert(0 && "Unknown icmp opcode!");
4801 case ICmpInst::ICMP_EQ:
4802 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004803 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004804 break;
4805 case ICmpInst::ICMP_NE:
4806 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004807 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004808 break;
4809 case ICmpInst::ICMP_ULT:
4810 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004814 break;
4815 case ICmpInst::ICMP_UGT:
4816 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004817 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004818 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004819 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004820 break;
4821 case ICmpInst::ICMP_SLT:
4822 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004823 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004824 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004825 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004826 break;
4827 case ICmpInst::ICMP_SGT:
4828 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004829 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004830 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004831 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004832 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004833 }
4834 }
4835
Reid Spencer266e42b2006-12-23 06:05:41 +00004836 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004837 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004838 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004839 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004840 switch (LHSI->getOpcode()) {
4841 case Instruction::And:
4842 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4843 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004844 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4845
Reid Spencer266e42b2006-12-23 06:05:41 +00004846 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004847 // and/compare to be the input width without changing the value
4848 // produced, eliminating a cast.
4849 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4850 // We can do this transformation if either the AND constant does not
4851 // have its sign bit set or if it is an equality comparison.
4852 // Extending a relational comparison when we're checking the sign
4853 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004854 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004855 (I.isEquality() ||
4856 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4857 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4858 ConstantInt *NewCST;
4859 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004860 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4861 AndCST->getZExtValue());
4862 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4863 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004864 Instruction *NewAnd =
4865 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4866 LHSI->getName());
4867 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004868 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004869 }
4870 }
4871
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004872 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4873 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4874 // happens a LOT in code produced by the C front-end, for bitfield
4875 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004876 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4877 if (Shift && !Shift->isShift())
4878 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004879
Reid Spencere0fc4df2006-10-20 07:07:24 +00004880 ConstantInt *ShAmt;
4881 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004882 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4883 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004884
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004885 // We can fold this as long as we can't shift unknown bits
4886 // into the mask. This can only happen with signed shift
4887 // rights, as they sign-extend.
4888 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004889 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004890 if (!CanFold) {
4891 // To test for the bad case of the signed shr, see if any
4892 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004893 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004894 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4895
Reid Spencer2341c222007-02-02 02:16:23 +00004896 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004897 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004898 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4899 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004900 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4901 CanFold = true;
4902 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004903
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004904 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004905 Constant *NewCst;
4906 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004907 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004908 else
4909 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004910
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004911 // Check to see if we are shifting out any of the bits being
4912 // compared.
4913 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4914 // If we shifted bits out, the fold is not going to work out.
4915 // As a special case, check to see if this means that the
4916 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004918 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004919 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004920 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004921 } else {
4922 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004923 Constant *NewAndCST;
4924 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004925 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004926 else
4927 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4928 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004929 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004930 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004931 AddUsesToWorkList(I);
4932 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004933 }
4934 }
Chris Lattner35167c32004-06-09 07:59:58 +00004935 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004936
4937 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4938 // preferable because it allows the C<<Y expression to be hoisted out
4939 // of a loop if Y is invariant and X is not.
4940 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004941 I.isEquality() && !Shift->isArithmeticShift() &&
4942 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004943 // Compute C << Y.
4944 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004945 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004946 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004947 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004948 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004949 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004950 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004951 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004952 }
4953 InsertNewInstBefore(cast<Instruction>(NS), I);
4954
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004955 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004956 Instruction *NewAnd = BinaryOperator::createAnd(
4957 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004958 InsertNewInstBefore(NewAnd, I);
4959
4960 I.setOperand(0, NewAnd);
4961 return &I;
4962 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004963 }
4964 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004965
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004967 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004968 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004969 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4970
4971 // Check that the shift amount is in range. If not, don't perform
4972 // undefined shifts. When the shift is visited it will be
4973 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004974 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004975 break;
4976
Chris Lattner272d5ca2004-09-28 18:22:15 +00004977 // If we are comparing against bits always shifted out, the
4978 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004979 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004980 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004981 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004982 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004983 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004984 return ReplaceInstUsesWith(I, Cst);
4985 }
4986
4987 if (LHSI->hasOneUse()) {
4988 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004989 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004990 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004991 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004992
Chris Lattner272d5ca2004-09-28 18:22:15 +00004993 Instruction *AndI =
4994 BinaryOperator::createAnd(LHSI->getOperand(0),
4995 Mask, LHSI->getName()+".mask");
4996 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004997 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004998 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004999 }
5000 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00005001 }
5002 break;
5003
Reid Spencer266e42b2006-12-23 06:05:41 +00005004 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00005005 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00005006 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005007 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005008 // Check that the shift amount is in range. If not, don't perform
5009 // undefined shifts. When the shift is visited it will be
5010 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00005011 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005012 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005013 break;
5014
Chris Lattner1023b872004-09-27 16:18:50 +00005015 // If we are comparing against bits always shifted out, the
5016 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00005017 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00005018 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00005019 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5020 ShAmt);
5021 else
5022 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5023 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005024
Chris Lattner1023b872004-09-27 16:18:50 +00005025 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005026 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005027 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00005028 return ReplaceInstUsesWith(I, Cst);
5029 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005030
Chris Lattner1023b872004-09-27 16:18:50 +00005031 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005032 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005033
Chris Lattner1023b872004-09-27 16:18:50 +00005034 // Otherwise strength reduce the shift into an and.
5035 uint64_t Val = ~0ULL; // All ones.
5036 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00005037 Val &= ~0ULL >> (64-TypeBits);
5038 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005039
Chris Lattner1023b872004-09-27 16:18:50 +00005040 Instruction *AndI =
5041 BinaryOperator::createAnd(LHSI->getOperand(0),
5042 Mask, LHSI->getName()+".mask");
5043 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005044 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00005045 ConstantExpr::getShl(CI, ShAmt));
5046 }
Chris Lattner1023b872004-09-27 16:18:50 +00005047 }
5048 }
5049 break;
Chris Lattner7e794272004-09-24 15:21:34 +00005050
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005051 case Instruction::SDiv:
5052 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00005053 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005054 // Fold this div into the comparison, producing a range check.
5055 // Determine, based on the divide type, what the range is being
5056 // checked. If there is an overflow on the low or high side, remember
5057 // it, otherwise compute the range [low, hi) bounding the new value.
5058 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005059 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005060 // FIXME: If the operand types don't match the type of the divide
5061 // then don't attempt this transform. The code below doesn't have the
5062 // logic to deal with a signed divide and an unsigned compare (and
5063 // vice versa). This is because (x /s C1) <s C2 produces different
5064 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5065 // (x /u C1) <u C2. Simply casting the operands and result won't
5066 // work. :( The if statement below tests that condition and bails
5067 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00005068 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5069 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005070 break;
5071
5072 // Initialize the variables that will indicate the nature of the
5073 // range check.
5074 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005075 ConstantInt *LoBound = 0, *HiBound = 0;
5076
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005077 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5078 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5079 // C2 (CI). By solving for X we can turn this into a range check
5080 // instead of computing a divide.
5081 ConstantInt *Prod =
5082 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005083
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005084 // Determine if the product overflows by seeing if the product is
5085 // not equal to the divide. Make sure we do the same kind of divide
5086 // as in the LHS instruction that we're folding.
5087 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005089 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5090
Reid Spencer266e42b2006-12-23 06:05:41 +00005091 // Get the ICmp opcode
5092 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00005093
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005094 if (DivRHS->isNullValue()) {
5095 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00005096 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00005097 LoBound = Prod;
5098 LoOverflow = ProdOV;
5099 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005100 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005101 if (CI->isNullValue()) { // (X / pos) op 0
5102 // Can't overflow.
5103 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5104 HiBound = DivRHS;
5105 } else if (isPositive(CI)) { // (X / pos) op pos
5106 LoBound = Prod;
5107 LoOverflow = ProdOV;
5108 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5109 } else { // (X / pos) op neg
5110 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5111 LoOverflow = AddWithOverflow(LoBound, Prod,
5112 cast<ConstantInt>(DivRHSH));
5113 HiBound = Prod;
5114 HiOverflow = ProdOV;
5115 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005116 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005117 if (CI->isNullValue()) { // (X / neg) op 0
5118 LoBound = AddOne(DivRHS);
5119 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005120 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005121 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00005122 } else if (isPositive(CI)) { // (X / neg) op pos
5123 HiOverflow = LoOverflow = ProdOV;
5124 if (!LoOverflow)
5125 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5126 HiBound = AddOne(Prod);
5127 } else { // (X / neg) op neg
5128 LoBound = Prod;
5129 LoOverflow = HiOverflow = ProdOV;
5130 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5131 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005132
Chris Lattnera92af962004-10-11 19:40:04 +00005133 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005134 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005135 }
5136
5137 if (LoBound) {
5138 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005139 switch (predicate) {
5140 default: assert(0 && "Unhandled icmp opcode!");
5141 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005142 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005143 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005144 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005145 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5146 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005147 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005148 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5149 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005150 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005151 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5152 true, I);
5153 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005154 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005155 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005156 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005157 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5158 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005159 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005160 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5161 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005162 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005163 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5164 false, I);
5165 case ICmpInst::ICMP_ULT:
5166 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005167 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005168 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005169 return new ICmpInst(predicate, X, LoBound);
5170 case ICmpInst::ICMP_UGT:
5171 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005172 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005173 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005174 if (predicate == ICmpInst::ICMP_UGT)
5175 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5176 else
5177 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005178 }
5179 }
5180 }
5181 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005182 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005183
Reid Spencer266e42b2006-12-23 06:05:41 +00005184 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005185 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005186 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005187
Reid Spencere0fc4df2006-10-20 07:07:24 +00005188 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5189 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5191 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005192 case Instruction::SRem:
5193 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5194 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5195 BO->hasOneUse()) {
5196 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5197 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005198 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5199 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005200 return new ICmpInst(I.getPredicate(), NewRem,
5201 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005202 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005203 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005204 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005205 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005206 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5207 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005208 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005209 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5210 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005211 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005212 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5213 // efficiently invertible, or if the add has just this one use.
5214 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005215
Chris Lattnerc992add2003-08-13 05:33:12 +00005216 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005217 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005218 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005219 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005220 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005221 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005222 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005223 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005224 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005225 }
5226 }
5227 break;
5228 case Instruction::Xor:
5229 // For the xor case, we can xor two constants together, eliminating
5230 // the explicit xor.
5231 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005232 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5233 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005234
5235 // FALLTHROUGH
5236 case Instruction::Sub:
5237 // Replace (([sub|xor] A, B) != 0) with (A != B)
5238 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005239 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5240 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005241 break;
5242
5243 case Instruction::Or:
5244 // If bits are being or'd in that are not present in the constant we
5245 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005246 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005247 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005248 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005249 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5250 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005251 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005252 break;
5253
5254 case Instruction::And:
5255 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005256 // If bits are being compared against that are and'd out, then the
5257 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005258 if (!ConstantExpr::getAnd(CI,
5259 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005260 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5261 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005262
Chris Lattner35167c32004-06-09 07:59:58 +00005263 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005264 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005265 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5266 ICmpInst::ICMP_NE, Op0,
5267 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005268
Reid Spencer266e42b2006-12-23 06:05:41 +00005269 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005270 if (isSignBit(BOC)) {
5271 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005272 Constant *Zero = Constant::getNullValue(X->getType());
5273 ICmpInst::Predicate pred = isICMP_NE ?
5274 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5275 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005276 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005277
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005278 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005279 if (CI->isNullValue() && isHighOnes(BOC)) {
5280 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005281 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005282 ICmpInst::Predicate pred = isICMP_NE ?
5283 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5284 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005285 }
5286
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005287 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005288 default: break;
5289 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005290 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5291 // Handle set{eq|ne} <intrinsic>, intcst.
5292 switch (II->getIntrinsicID()) {
5293 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005294 case Intrinsic::bswap_i16:
5295 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005296 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005297 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005298 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005299 ByteSwap_16(CI->getZExtValue())));
5300 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005301 case Intrinsic::bswap_i32:
5302 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005303 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005304 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005305 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005306 ByteSwap_32(CI->getZExtValue())));
5307 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005308 case Intrinsic::bswap_i64:
5309 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005310 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005311 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005312 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005313 ByteSwap_64(CI->getZExtValue())));
5314 return &I;
5315 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005316 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005317 } else { // Not a ICMP_EQ/ICMP_NE
5318 // If the LHS is a cast from an integral value of the same size, then
5319 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005320 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5321 Value *CastOp = Cast->getOperand(0);
5322 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005323 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005324 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005325 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005326 // If this is an unsigned comparison, try to make the comparison use
5327 // smaller constant values.
5328 switch (I.getPredicate()) {
5329 default: break;
5330 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5331 ConstantInt *CUI = cast<ConstantInt>(CI);
5332 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5333 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005334 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005335 break;
5336 }
5337 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5338 ConstantInt *CUI = cast<ConstantInt>(CI);
5339 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5340 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5341 Constant::getNullValue(SrcTy));
5342 break;
5343 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005344 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005345
Chris Lattner2b55ea32004-02-23 07:16:20 +00005346 }
5347 }
Chris Lattnere967b342003-06-04 05:10:11 +00005348 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005349 }
5350
Reid Spencer266e42b2006-12-23 06:05:41 +00005351 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005352 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5353 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5354 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005355 case Instruction::GetElementPtr:
5356 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005357 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005358 bool isAllZeros = true;
5359 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5360 if (!isa<Constant>(LHSI->getOperand(i)) ||
5361 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5362 isAllZeros = false;
5363 break;
5364 }
5365 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005366 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005367 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5368 }
5369 break;
5370
Chris Lattner77c32c32005-04-23 15:31:55 +00005371 case Instruction::PHI:
5372 if (Instruction *NV = FoldOpIntoPhi(I))
5373 return NV;
5374 break;
5375 case Instruction::Select:
5376 // If either operand of the select is a constant, we can fold the
5377 // comparison into the select arms, which will cause one to be
5378 // constant folded and the select turned into a bitwise or.
5379 Value *Op1 = 0, *Op2 = 0;
5380 if (LHSI->hasOneUse()) {
5381 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5382 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005383 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5384 // Insert a new ICmp of the other select operand.
5385 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5386 LHSI->getOperand(2), RHSC,
5387 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005388 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5389 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005390 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5391 // Insert a new ICmp of the other select operand.
5392 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5393 LHSI->getOperand(1), RHSC,
5394 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005395 }
5396 }
Jeff Cohen82639852005-04-23 21:38:35 +00005397
Chris Lattner77c32c32005-04-23 15:31:55 +00005398 if (Op1)
5399 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5400 break;
5401 }
5402 }
5403
Reid Spencer266e42b2006-12-23 06:05:41 +00005404 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005405 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005406 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005407 return NI;
5408 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005409 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5410 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005411 return NI;
5412
Reid Spencer266e42b2006-12-23 06:05:41 +00005413 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005414 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5415 // now.
5416 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5417 if (isa<PointerType>(Op0->getType()) &&
5418 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005419 // We keep moving the cast from the left operand over to the right
5420 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005421 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005422
Chris Lattner64d87b02007-01-06 01:45:59 +00005423 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5424 // so eliminate it as well.
5425 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5426 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005427
Chris Lattner16930792003-11-03 04:25:02 +00005428 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005429 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005430 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005431 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005432 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005433 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005434 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005435 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005436 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005437 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005438 }
5439
5440 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005441 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005442 // This comes up when you have code like
5443 // int X = A < B;
5444 // if (X) ...
5445 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005446 // with a constant or another cast from the same type.
5447 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005448 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005449 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005450 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005451
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005452 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005453 Value *A, *B, *C, *D;
5454 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5455 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5456 Value *OtherVal = A == Op1 ? B : A;
5457 return new ICmpInst(I.getPredicate(), OtherVal,
5458 Constant::getNullValue(A->getType()));
5459 }
5460
5461 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5462 // A^c1 == C^c2 --> A == C^(c1^c2)
5463 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5464 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5465 if (Op1->hasOneUse()) {
5466 Constant *NC = ConstantExpr::getXor(C1, C2);
5467 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5468 return new ICmpInst(I.getPredicate(), A,
5469 InsertNewInstBefore(Xor, I));
5470 }
5471
5472 // A^B == A^D -> B == D
5473 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5474 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5475 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5476 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5477 }
5478 }
5479
5480 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5481 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005482 // A == (A^B) -> B == 0
5483 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005484 return new ICmpInst(I.getPredicate(), OtherVal,
5485 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005486 }
5487 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005488 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005489 return new ICmpInst(I.getPredicate(), B,
5490 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005491 }
5492 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005493 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005494 return new ICmpInst(I.getPredicate(), B,
5495 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005496 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005497
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005498 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5499 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5500 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5501 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5502 Value *X = 0, *Y = 0, *Z = 0;
5503
5504 if (A == C) {
5505 X = B; Y = D; Z = A;
5506 } else if (A == D) {
5507 X = B; Y = C; Z = A;
5508 } else if (B == C) {
5509 X = A; Y = D; Z = B;
5510 } else if (B == D) {
5511 X = A; Y = C; Z = B;
5512 }
5513
5514 if (X) { // Build (X^Y) & Z
5515 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5516 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5517 I.setOperand(0, Op1);
5518 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5519 return &I;
5520 }
5521 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005522 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005523 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005524}
5525
Reid Spencer266e42b2006-12-23 06:05:41 +00005526// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005527// We only handle extending casts so far.
5528//
Reid Spencer266e42b2006-12-23 06:05:41 +00005529Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5530 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005531 Value *LHSCIOp = LHSCI->getOperand(0);
5532 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005533 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005534 Value *RHSCIOp;
5535
Reid Spencer266e42b2006-12-23 06:05:41 +00005536 // We only handle extension cast instructions, so far. Enforce this.
5537 if (LHSCI->getOpcode() != Instruction::ZExt &&
5538 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005539 return 0;
5540
Reid Spencer266e42b2006-12-23 06:05:41 +00005541 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5542 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005543
Reid Spencer266e42b2006-12-23 06:05:41 +00005544 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005545 // Not an extension from the same type?
5546 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005547 if (RHSCIOp->getType() != LHSCIOp->getType())
5548 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005549
5550 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5551 // and the other is a zext), then we can't handle this.
5552 if (CI->getOpcode() != LHSCI->getOpcode())
5553 return 0;
5554
5555 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5556 // then we can't handle this.
5557 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5558 return 0;
5559
5560 // Okay, just insert a compare of the reduced operands now!
5561 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005562 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005563
Reid Spencer266e42b2006-12-23 06:05:41 +00005564 // If we aren't dealing with a constant on the RHS, exit early
5565 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5566 if (!CI)
5567 return 0;
5568
5569 // Compute the constant that would happen if we truncated to SrcTy then
5570 // reextended to DestTy.
5571 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5572 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5573
5574 // If the re-extended constant didn't change...
5575 if (Res2 == CI) {
5576 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5577 // For example, we might have:
5578 // %A = sext short %X to uint
5579 // %B = icmp ugt uint %A, 1330
5580 // It is incorrect to transform this into
5581 // %B = icmp ugt short %X, 1330
5582 // because %A may have negative value.
5583 //
5584 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5585 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005586 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005587 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5588 else
5589 return 0;
5590 }
5591
5592 // The re-extended constant changed so the constant cannot be represented
5593 // in the shorter type. Consequently, we cannot emit a simple comparison.
5594
5595 // First, handle some easy cases. We know the result cannot be equal at this
5596 // point so handle the ICI.isEquality() cases
5597 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005598 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005599 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005600 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005601
5602 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5603 // should have been folded away previously and not enter in here.
5604 Value *Result;
5605 if (isSignedCmp) {
5606 // We're performing a signed comparison.
5607 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005608 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005609 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005610 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005611 } else {
5612 // We're performing an unsigned comparison.
5613 if (isSignedExt) {
5614 // We're performing an unsigned comp with a sign extended value.
5615 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005616 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005617 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5618 NegOne, ICI.getName()), ICI);
5619 } else {
5620 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005621 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005622 }
5623 }
5624
5625 // Finally, return the value computed.
5626 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5627 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5628 return ReplaceInstUsesWith(ICI, Result);
5629 } else {
5630 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5631 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5632 "ICmp should be folded!");
5633 if (Constant *CI = dyn_cast<Constant>(Result))
5634 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5635 else
5636 return BinaryOperator::createNot(Result);
5637 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005638}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005639
Reid Spencer2341c222007-02-02 02:16:23 +00005640Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5641 return commonShiftTransforms(I);
5642}
5643
5644Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5645 return commonShiftTransforms(I);
5646}
5647
5648Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5649 return commonShiftTransforms(I);
5650}
5651
5652Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5653 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005654 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005655
5656 // shl X, 0 == X and shr X, 0 == X
5657 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005658 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005659 Op0 == Constant::getNullValue(Op0->getType()))
5660 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005661
Reid Spencer266e42b2006-12-23 06:05:41 +00005662 if (isa<UndefValue>(Op0)) {
5663 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005664 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005665 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5667 }
5668 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005669 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5670 return ReplaceInstUsesWith(I, Op0);
5671 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005672 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005673 }
5674
Chris Lattnerd4dee402006-11-10 23:38:52 +00005675 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5676 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005677 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005678 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005679 return ReplaceInstUsesWith(I, CSI);
5680
Chris Lattner183b3362004-04-09 19:05:30 +00005681 // Try to fold constant and into select arguments.
5682 if (isa<Constant>(Op0))
5683 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005684 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005685 return R;
5686
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005687 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005688 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005689 if (MaskedValueIsZero(Op0,
5690 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005691 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005692 }
5693 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005694
Reid Spencere0fc4df2006-10-20 07:07:24 +00005695 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005696 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5697 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005698 return 0;
5699}
5700
Reid Spencere0fc4df2006-10-20 07:07:24 +00005701Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005702 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005703 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005704
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005705 // See if we can simplify any instructions used by the instruction whose sole
5706 // purpose is to compute bits we don't care about.
5707 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005708 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005709 KnownZero, KnownOne))
5710 return &I;
5711
Chris Lattner14553932006-01-06 07:12:35 +00005712 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5713 // of a signed value.
5714 //
5715 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005716 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005717 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005718 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5719 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005720 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005721 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005722 }
Chris Lattner14553932006-01-06 07:12:35 +00005723 }
5724
5725 // ((X*C1) << C2) == (X * (C1 << C2))
5726 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5727 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5728 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5729 return BinaryOperator::createMul(BO->getOperand(0),
5730 ConstantExpr::getShl(BOOp, Op1));
5731
5732 // Try to fold constant and into select arguments.
5733 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5734 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5735 return R;
5736 if (isa<PHINode>(Op0))
5737 if (Instruction *NV = FoldOpIntoPhi(I))
5738 return NV;
5739
5740 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005741 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5742 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5743 Value *V1, *V2;
5744 ConstantInt *CC;
5745 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005746 default: break;
5747 case Instruction::Add:
5748 case Instruction::And:
5749 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005750 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005751 // These operators commute.
5752 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005753 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5754 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005755 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005756 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005757 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005758 Op0BO->getName());
5759 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005760 Instruction *X =
5761 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5762 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005763 InsertNewInstBefore(X, I); // (X + (Y << C))
5764 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005765 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005766 return BinaryOperator::createAnd(X, C2);
5767 }
Chris Lattner14553932006-01-06 07:12:35 +00005768
Chris Lattner797dee72005-09-18 06:30:59 +00005769 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005770 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005771 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005772 match(Op0BOOp1,
5773 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005774 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5775 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005776 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005777 Op0BO->getOperand(0), Op1,
5778 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005779 InsertNewInstBefore(YS, I); // (Y << C)
5780 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005781 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005782 V1->getName()+".mask");
5783 InsertNewInstBefore(XM, I); // X & (CC << C)
5784
5785 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5786 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005787 }
Chris Lattner14553932006-01-06 07:12:35 +00005788
Reid Spencer2f34b982007-02-02 14:41:37 +00005789 // FALL THROUGH.
5790 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005791 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005792 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5793 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005794 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005795 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005796 Op0BO->getOperand(1), Op1,
5797 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005798 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005799 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005800 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005801 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005802 InsertNewInstBefore(X, I); // (X + (Y << C))
5803 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005804 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005805 return BinaryOperator::createAnd(X, C2);
5806 }
Chris Lattner14553932006-01-06 07:12:35 +00005807
Chris Lattner1df0e982006-05-31 21:14:00 +00005808 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005809 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5810 match(Op0BO->getOperand(0),
5811 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005812 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005813 cast<BinaryOperator>(Op0BO->getOperand(0))
5814 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005815 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005816 Op0BO->getOperand(1), Op1,
5817 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005818 InsertNewInstBefore(YS, I); // (Y << C)
5819 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005820 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005821 V1->getName()+".mask");
5822 InsertNewInstBefore(XM, I); // X & (CC << C)
5823
Chris Lattner1df0e982006-05-31 21:14:00 +00005824 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005825 }
Chris Lattner14553932006-01-06 07:12:35 +00005826
Chris Lattner27cb9db2005-09-18 05:12:10 +00005827 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005828 }
Chris Lattner14553932006-01-06 07:12:35 +00005829 }
5830
5831
5832 // If the operand is an bitwise operator with a constant RHS, and the
5833 // shift is the only use, we can pull it out of the shift.
5834 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5835 bool isValid = true; // Valid only for And, Or, Xor
5836 bool highBitSet = false; // Transform if high bit of constant set?
5837
5838 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005839 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005840 case Instruction::Add:
5841 isValid = isLeftShift;
5842 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005843 case Instruction::Or:
5844 case Instruction::Xor:
5845 highBitSet = false;
5846 break;
5847 case Instruction::And:
5848 highBitSet = true;
5849 break;
Chris Lattner14553932006-01-06 07:12:35 +00005850 }
5851
5852 // If this is a signed shift right, and the high bit is modified
5853 // by the logical operation, do not perform the transformation.
5854 // The highBitSet boolean indicates the value of the high bit of
5855 // the constant which would cause it to be modified for this
5856 // operation.
5857 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005858 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005859 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005860 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5861 }
5862
5863 if (isValid) {
5864 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5865
5866 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005867 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005868 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005869 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005870
5871 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5872 NewRHS);
5873 }
5874 }
5875 }
5876 }
5877
Chris Lattnereb372a02006-01-06 07:52:12 +00005878 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005879 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5880 if (ShiftOp && !ShiftOp->isShift())
5881 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005882
Reid Spencere0fc4df2006-10-20 07:07:24 +00005883 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005884 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00005885 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5886 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005887 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5888 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5889 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005890
Chris Lattner3e009e82007-02-05 00:57:54 +00005891 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5892 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5893 AmtSum = I.getType()->getPrimitiveSizeInBits();
5894
5895 const IntegerType *Ty = cast<IntegerType>(I.getType());
5896
5897 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005898 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005899 return BinaryOperator::create(I.getOpcode(), X,
5900 ConstantInt::get(Ty, AmtSum));
5901 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5902 I.getOpcode() == Instruction::AShr) {
5903 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5904 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5905 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5906 I.getOpcode() == Instruction::LShr) {
5907 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5908 Instruction *Shift =
5909 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5910 InsertNewInstBefore(Shift, I);
5911
5912 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5913 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005914 }
5915
Chris Lattner3e009e82007-02-05 00:57:54 +00005916 // Okay, if we get here, one shift must be left, and the other shift must be
5917 // right. See if the amounts are equal.
5918 if (ShiftAmt1 == ShiftAmt2) {
5919 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5920 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005921 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005922 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5923 }
5924 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5925 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005926 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005927 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5928 }
5929 // We can simplify ((X << C) >>s C) into a trunc + sext.
5930 // NOTE: we could do this for any C, but that would make 'unusual' integer
5931 // types. For now, just stick to ones well-supported by the code
5932 // generators.
5933 const Type *SExtType = 0;
5934 switch (Ty->getBitWidth() - ShiftAmt1) {
5935 case 8 : SExtType = Type::Int8Ty; break;
5936 case 16: SExtType = Type::Int16Ty; break;
5937 case 32: SExtType = Type::Int32Ty; break;
5938 default: break;
5939 }
5940 if (SExtType) {
5941 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5942 InsertNewInstBefore(NewTrunc, I);
5943 return new SExtInst(NewTrunc, Ty);
5944 }
5945 // Otherwise, we can't handle it yet.
5946 } else if (ShiftAmt1 < ShiftAmt2) {
5947 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005948
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005949 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005950 if (I.getOpcode() == Instruction::Shl) {
5951 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5952 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005953 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005954 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005955 InsertNewInstBefore(Shift, I);
5956
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005957 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005958 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005959 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005960
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005961 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005962 if (I.getOpcode() == Instruction::LShr) {
5963 assert(ShiftOp->getOpcode() == Instruction::Shl);
5964 Instruction *Shift =
5965 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5966 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005967
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005968 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005969 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005970 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005971
5972 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5973 } else {
5974 assert(ShiftAmt2 < ShiftAmt1);
5975 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5976
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005977 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005978 if (I.getOpcode() == Instruction::Shl) {
5979 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5980 ShiftOp->getOpcode() == Instruction::AShr);
5981 Instruction *Shift =
5982 BinaryOperator::create(ShiftOp->getOpcode(), X,
5983 ConstantInt::get(Ty, ShiftDiff));
5984 InsertNewInstBefore(Shift, I);
5985
5986 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5987 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5988 }
5989
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005990 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005991 if (I.getOpcode() == Instruction::LShr) {
5992 assert(ShiftOp->getOpcode() == Instruction::Shl);
5993 Instruction *Shift =
5994 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5995 InsertNewInstBefore(Shift, I);
5996
5997 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5998 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5999 }
6000
6001 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006002 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006003 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006004 return 0;
6005}
6006
Chris Lattner48a44f72002-05-02 17:06:02 +00006007
Chris Lattner8f663e82005-10-29 04:36:15 +00006008/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6009/// expression. If so, decompose it, returning some value X, such that Val is
6010/// X*Scale+Offset.
6011///
6012static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6013 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006014 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006015 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006016 Offset = CI->getZExtValue();
6017 Scale = 1;
6018 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006019 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6020 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006021 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006022 if (I->getOpcode() == Instruction::Shl) {
6023 // This is a value scaled by '1 << the shift amt'.
6024 Scale = 1U << CUI->getZExtValue();
6025 Offset = 0;
6026 return I->getOperand(0);
6027 } else if (I->getOpcode() == Instruction::Mul) {
6028 // This value is scaled by 'CUI'.
6029 Scale = CUI->getZExtValue();
6030 Offset = 0;
6031 return I->getOperand(0);
6032 } else if (I->getOpcode() == Instruction::Add) {
6033 // We have X+C. Check to see if we really have (X*C2)+C1,
6034 // where C1 is divisible by C2.
6035 unsigned SubScale;
6036 Value *SubVal =
6037 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6038 Offset += CUI->getZExtValue();
6039 if (SubScale > 1 && (Offset % SubScale == 0)) {
6040 Scale = SubScale;
6041 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006042 }
6043 }
6044 }
6045 }
6046 }
6047
6048 // Otherwise, we can't look past this.
6049 Scale = 1;
6050 Offset = 0;
6051 return Val;
6052}
6053
6054
Chris Lattner216be912005-10-24 06:03:58 +00006055/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6056/// try to eliminate the cast by moving the type information into the alloc.
6057Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6058 AllocationInst &AI) {
6059 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006060 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006061
Chris Lattnerac87beb2005-10-24 06:22:12 +00006062 // Remove any uses of AI that are dead.
6063 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006064
Chris Lattnerac87beb2005-10-24 06:22:12 +00006065 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6066 Instruction *User = cast<Instruction>(*UI++);
6067 if (isInstructionTriviallyDead(User)) {
6068 while (UI != E && *UI == User)
6069 ++UI; // If this instruction uses AI more than once, don't break UI.
6070
Chris Lattnerac87beb2005-10-24 06:22:12 +00006071 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006072 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006073 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006074 }
6075 }
6076
Chris Lattner216be912005-10-24 06:03:58 +00006077 // Get the type really allocated and the type casted to.
6078 const Type *AllocElTy = AI.getAllocatedType();
6079 const Type *CastElTy = PTy->getElementType();
6080 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006081
Chris Lattner945e4372007-02-14 05:52:17 +00006082 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6083 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006084 if (CastElTyAlign < AllocElTyAlign) return 0;
6085
Chris Lattner46705b22005-10-24 06:35:18 +00006086 // If the allocation has multiple uses, only promote it if we are strictly
6087 // increasing the alignment of the resultant allocation. If we keep it the
6088 // same, we open the door to infinite loops of various kinds.
6089 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6090
Chris Lattner216be912005-10-24 06:03:58 +00006091 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6092 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006093 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006094
Chris Lattner8270c332005-10-29 03:19:53 +00006095 // See if we can satisfy the modulus by pulling a scale out of the array
6096 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006097 unsigned ArraySizeScale, ArrayOffset;
6098 Value *NumElements = // See if the array size is a decomposable linear expr.
6099 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6100
Chris Lattner8270c332005-10-29 03:19:53 +00006101 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6102 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006103 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6104 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006105
Chris Lattner8270c332005-10-29 03:19:53 +00006106 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6107 Value *Amt = 0;
6108 if (Scale == 1) {
6109 Amt = NumElements;
6110 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006111 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006112 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6113 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006114 Amt = ConstantExpr::getMul(
6115 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6116 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006117 else if (Scale != 1) {
6118 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6119 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006120 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006121 }
6122
Chris Lattner8f663e82005-10-29 04:36:15 +00006123 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006124 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006125 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6126 Amt = InsertNewInstBefore(Tmp, AI);
6127 }
6128
Chris Lattner216be912005-10-24 06:03:58 +00006129 AllocationInst *New;
6130 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006131 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006132 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006133 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006134 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006135 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006136
6137 // If the allocation has multiple uses, insert a cast and change all things
6138 // that used it to use the new cast. This will also hack on CI, but it will
6139 // die soon.
6140 if (!AI.hasOneUse()) {
6141 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006142 // New is the allocation instruction, pointer typed. AI is the original
6143 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6144 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006145 InsertNewInstBefore(NewCast, AI);
6146 AI.replaceAllUsesWith(NewCast);
6147 }
Chris Lattner216be912005-10-24 06:03:58 +00006148 return ReplaceInstUsesWith(CI, New);
6149}
6150
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006151/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006152/// and return it as type Ty without inserting any new casts and without
6153/// changing the computed value. This is used by code that tries to decide
6154/// whether promoting or shrinking integer operations to wider or smaller types
6155/// will allow us to eliminate a truncate or extend.
6156///
6157/// This is a truncation operation if Ty is smaller than V->getType(), or an
6158/// extension operation if Ty is larger.
6159static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006160 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006161 // We can always evaluate constants in another type.
6162 if (isa<ConstantInt>(V))
6163 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006164
6165 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006166 if (!I) return false;
6167
6168 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006169
6170 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006171 case Instruction::Add:
6172 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006173 case Instruction::And:
6174 case Instruction::Or:
6175 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006176 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006177 // These operators can all arbitrarily be extended or truncated.
6178 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6179 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006180
Chris Lattner960acb02006-11-29 07:18:39 +00006181 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006182 if (!I->hasOneUse()) return false;
6183 // If we are truncating the result of this SHL, and if it's a shift of a
6184 // constant amount, we can always perform a SHL in a smaller type.
6185 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6186 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6187 CI->getZExtValue() < Ty->getBitWidth())
6188 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6189 }
6190 break;
6191 case Instruction::LShr:
6192 if (!I->hasOneUse()) return false;
6193 // If this is a truncate of a logical shr, we can truncate it to a smaller
6194 // lshr iff we know that the bits we would otherwise be shifting in are
6195 // already zeros.
6196 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6197 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6198 MaskedValueIsZero(I->getOperand(0),
6199 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6200 CI->getZExtValue() < Ty->getBitWidth()) {
6201 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6202 }
6203 }
Chris Lattner960acb02006-11-29 07:18:39 +00006204 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006205 case Instruction::Trunc:
6206 case Instruction::ZExt:
6207 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006208 // If this is a cast from the destination type, we can trivially eliminate
6209 // it, and this will remove a cast overall.
6210 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006211 // If the first operand is itself a cast, and is eliminable, do not count
6212 // this as an eliminable cast. We would prefer to eliminate those two
6213 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006214 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006215 return true;
6216
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006217 ++NumCastsRemoved;
6218 return true;
6219 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006220 break;
6221 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006222 // TODO: Can handle more cases here.
6223 break;
6224 }
6225
6226 return false;
6227}
6228
6229/// EvaluateInDifferentType - Given an expression that
6230/// CanEvaluateInDifferentType returns true for, actually insert the code to
6231/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006232Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006233 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006234 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006235 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006236
6237 // Otherwise, it must be an instruction.
6238 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006239 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006240 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006241 case Instruction::Add:
6242 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006243 case Instruction::And:
6244 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006245 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006246 case Instruction::AShr:
6247 case Instruction::LShr:
6248 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006249 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006250 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6251 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6252 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006253 break;
6254 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006255 case Instruction::Trunc:
6256 case Instruction::ZExt:
6257 case Instruction::SExt:
6258 case Instruction::BitCast:
6259 // If the source type of the cast is the type we're trying for then we can
6260 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006261 if (I->getOperand(0)->getType() == Ty)
6262 return I->getOperand(0);
6263
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006264 // Some other kind of cast, which shouldn't happen, so just ..
6265 // FALL THROUGH
6266 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006267 // TODO: Can handle more cases here.
6268 assert(0 && "Unreachable!");
6269 break;
6270 }
6271
6272 return InsertNewInstBefore(Res, *I);
6273}
6274
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006275/// @brief Implement the transforms common to all CastInst visitors.
6276Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006277 Value *Src = CI.getOperand(0);
6278
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006279 // Casting undef to anything results in undef so might as just replace it and
6280 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006281 if (isa<UndefValue>(Src)) // cast undef -> undef
6282 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6283
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006284 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6285 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006286 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006287 if (Instruction::CastOps opc =
6288 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6289 // The first cast (CSrc) is eliminable so we need to fix up or replace
6290 // the second cast (CI). CSrc will then have a good chance of being dead.
6291 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006292 }
6293 }
Chris Lattner03841652004-05-25 04:29:21 +00006294
Chris Lattnerd0d51602003-06-21 23:12:02 +00006295 // If casting the result of a getelementptr instruction with no offset, turn
6296 // this into a cast of the original pointer!
6297 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006298 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006299 bool AllZeroOperands = true;
6300 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6301 if (!isa<Constant>(GEP->getOperand(i)) ||
6302 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6303 AllZeroOperands = false;
6304 break;
6305 }
6306 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006307 // Changing the cast operand is usually not a good idea but it is safe
6308 // here because the pointer operand is being replaced with another
6309 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006310 CI.setOperand(0, GEP->getOperand(0));
6311 return &CI;
6312 }
6313 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006314
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006315 // If we are casting a malloc or alloca to a pointer to a type of the same
6316 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006317 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006318 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6319 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006320
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006321 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006322 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6323 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6324 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006325
6326 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006327 if (isa<PHINode>(Src))
6328 if (Instruction *NV = FoldOpIntoPhi(CI))
6329 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006330
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006331 return 0;
6332}
6333
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006334/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6335/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006336/// cases.
6337/// @brief Implement the transforms common to CastInst with integer operands
6338Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6339 if (Instruction *Result = commonCastTransforms(CI))
6340 return Result;
6341
6342 Value *Src = CI.getOperand(0);
6343 const Type *SrcTy = Src->getType();
6344 const Type *DestTy = CI.getType();
6345 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6346 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6347
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006348 // See if we can simplify any instructions used by the LHS whose sole
6349 // purpose is to compute bits we don't care about.
6350 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006351 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006352 KnownZero, KnownOne))
6353 return &CI;
6354
6355 // If the source isn't an instruction or has more than one use then we
6356 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006357 Instruction *SrcI = dyn_cast<Instruction>(Src);
6358 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006359 return 0;
6360
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006361 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006362 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006363 if (!isa<BitCastInst>(CI) &&
6364 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6365 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006366 // If this cast is a truncate, evaluting in a different type always
6367 // eliminates the cast, so it is always a win. If this is a noop-cast
6368 // this just removes a noop cast which isn't pointful, but simplifies
6369 // the code. If this is a zero-extension, we need to do an AND to
6370 // maintain the clear top-part of the computation, so we require that
6371 // the input have eliminated at least one cast. If this is a sign
6372 // extension, we insert two new casts (to do the extension) so we
6373 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006374 bool DoXForm;
6375 switch (CI.getOpcode()) {
6376 default:
6377 // All the others use floating point so we shouldn't actually
6378 // get here because of the check above.
6379 assert(0 && "Unknown cast type");
6380 case Instruction::Trunc:
6381 DoXForm = true;
6382 break;
6383 case Instruction::ZExt:
6384 DoXForm = NumCastsRemoved >= 1;
6385 break;
6386 case Instruction::SExt:
6387 DoXForm = NumCastsRemoved >= 2;
6388 break;
6389 case Instruction::BitCast:
6390 DoXForm = false;
6391 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006392 }
6393
6394 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006395 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6396 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006397 assert(Res->getType() == DestTy);
6398 switch (CI.getOpcode()) {
6399 default: assert(0 && "Unknown cast type!");
6400 case Instruction::Trunc:
6401 case Instruction::BitCast:
6402 // Just replace this cast with the result.
6403 return ReplaceInstUsesWith(CI, Res);
6404 case Instruction::ZExt: {
6405 // We need to emit an AND to clear the high bits.
6406 assert(SrcBitSize < DestBitSize && "Not a zext?");
6407 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006408 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006409 if (DestBitSize < 64)
6410 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006411 return BinaryOperator::createAnd(Res, C);
6412 }
6413 case Instruction::SExt:
6414 // We need to emit a cast to truncate, then a cast to sext.
6415 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006416 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6417 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006418 }
6419 }
6420 }
6421
6422 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6423 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6424
6425 switch (SrcI->getOpcode()) {
6426 case Instruction::Add:
6427 case Instruction::Mul:
6428 case Instruction::And:
6429 case Instruction::Or:
6430 case Instruction::Xor:
6431 // If we are discarding information, or just changing the sign,
6432 // rewrite.
6433 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6434 // Don't insert two casts if they cannot be eliminated. We allow
6435 // two casts to be inserted if the sizes are the same. This could
6436 // only be converting signedness, which is a noop.
6437 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006438 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6439 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006440 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006441 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6442 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6443 return BinaryOperator::create(
6444 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006445 }
6446 }
6447
6448 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6449 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6450 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006451 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006452 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006453 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006454 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6455 }
6456 break;
6457 case Instruction::SDiv:
6458 case Instruction::UDiv:
6459 case Instruction::SRem:
6460 case Instruction::URem:
6461 // If we are just changing the sign, rewrite.
6462 if (DestBitSize == SrcBitSize) {
6463 // Don't insert two casts if they cannot be eliminated. We allow
6464 // two casts to be inserted if the sizes are the same. This could
6465 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006466 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6467 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006468 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6469 Op0, DestTy, SrcI);
6470 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6471 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006472 return BinaryOperator::create(
6473 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6474 }
6475 }
6476 break;
6477
6478 case Instruction::Shl:
6479 // Allow changing the sign of the source operand. Do not allow
6480 // changing the size of the shift, UNLESS the shift amount is a
6481 // constant. We must not change variable sized shifts to a smaller
6482 // size, because it is undefined to shift more bits out than exist
6483 // in the value.
6484 if (DestBitSize == SrcBitSize ||
6485 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006486 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6487 Instruction::BitCast : Instruction::Trunc);
6488 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006489 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006490 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006491 }
6492 break;
6493 case Instruction::AShr:
6494 // If this is a signed shr, and if all bits shifted in are about to be
6495 // truncated off, turn it into an unsigned shr to allow greater
6496 // simplifications.
6497 if (DestBitSize < SrcBitSize &&
6498 isa<ConstantInt>(Op1)) {
6499 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6500 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6501 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006502 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006503 }
6504 }
6505 break;
6506
Reid Spencer266e42b2006-12-23 06:05:41 +00006507 case Instruction::ICmp:
6508 // If we are just checking for a icmp eq of a single bit and casting it
6509 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006510 // cast to integer to avoid the comparison.
6511 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6512 uint64_t Op1CV = Op1C->getZExtValue();
6513 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6514 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6515 // cast (X == 1) to int --> X iff X has only the low bit set.
6516 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6517 // cast (X != 0) to int --> X iff X has only the low bit set.
6518 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6519 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6520 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6521 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6522 // If Op1C some other power of two, convert:
6523 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006524 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006525 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006526
6527 // This only works for EQ and NE
6528 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6529 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6530 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006531
6532 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006533 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006534 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6535 // (X&4) == 2 --> false
6536 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006537 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006538 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006539 return ReplaceInstUsesWith(CI, Res);
6540 }
6541
6542 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6543 Value *In = Op0;
6544 if (ShiftAmt) {
6545 // Perform a logical shr by shiftamt.
6546 // Insert the shift to put the result in the low bit.
6547 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006548 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006549 ConstantInt::get(In->getType(), ShiftAmt),
6550 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006551 }
6552
Reid Spencer266e42b2006-12-23 06:05:41 +00006553 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006554 Constant *One = ConstantInt::get(In->getType(), 1);
6555 In = BinaryOperator::createXor(In, One, "tmp");
6556 InsertNewInstBefore(cast<Instruction>(In), CI);
6557 }
6558
6559 if (CI.getType() == In->getType())
6560 return ReplaceInstUsesWith(CI, In);
6561 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006562 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006563 }
6564 }
6565 }
6566 break;
6567 }
6568 return 0;
6569}
6570
6571Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006572 if (Instruction *Result = commonIntCastTransforms(CI))
6573 return Result;
6574
6575 Value *Src = CI.getOperand(0);
6576 const Type *Ty = CI.getType();
6577 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6578
6579 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6580 switch (SrcI->getOpcode()) {
6581 default: break;
6582 case Instruction::LShr:
6583 // We can shrink lshr to something smaller if we know the bits shifted in
6584 // are already zeros.
6585 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6586 unsigned ShAmt = ShAmtV->getZExtValue();
6587
6588 // Get a mask for the bits shifting in.
6589 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006590 Value* SrcIOp0 = SrcI->getOperand(0);
6591 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006592 if (ShAmt >= DestBitWidth) // All zeros.
6593 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6594
6595 // Okay, we can shrink this. Truncate the input, then return a new
6596 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006597 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6598 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6599 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006600 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006601 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006602 } else { // This is a variable shr.
6603
6604 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6605 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6606 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006607 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006608 Value *One = ConstantInt::get(SrcI->getType(), 1);
6609
Reid Spencer2341c222007-02-02 02:16:23 +00006610 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006611 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006612 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006613 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6614 SrcI->getOperand(0),
6615 "tmp"), CI);
6616 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006617 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006618 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006619 }
6620 break;
6621 }
6622 }
6623
6624 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006625}
6626
6627Instruction *InstCombiner::visitZExt(CastInst &CI) {
6628 // If one of the common conversion will work ..
6629 if (Instruction *Result = commonIntCastTransforms(CI))
6630 return Result;
6631
6632 Value *Src = CI.getOperand(0);
6633
6634 // If this is a cast of a cast
6635 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006636 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6637 // types and if the sizes are just right we can convert this into a logical
6638 // 'and' which will be much cheaper than the pair of casts.
6639 if (isa<TruncInst>(CSrc)) {
6640 // Get the sizes of the types involved
6641 Value *A = CSrc->getOperand(0);
6642 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6643 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6644 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6645 // If we're actually extending zero bits and the trunc is a no-op
6646 if (MidSize < DstSize && SrcSize == DstSize) {
6647 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006648 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006649 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6650 Instruction *And =
6651 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6652 // Unfortunately, if the type changed, we need to cast it back.
6653 if (And->getType() != CI.getType()) {
6654 And->setName(CSrc->getName()+".mask");
6655 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006656 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006657 }
6658 return And;
6659 }
6660 }
6661 }
6662
6663 return 0;
6664}
6665
6666Instruction *InstCombiner::visitSExt(CastInst &CI) {
6667 return commonIntCastTransforms(CI);
6668}
6669
6670Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6671 return commonCastTransforms(CI);
6672}
6673
6674Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6675 return commonCastTransforms(CI);
6676}
6677
6678Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006679 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006680}
6681
6682Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006683 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006684}
6685
6686Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6687 return commonCastTransforms(CI);
6688}
6689
6690Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6691 return commonCastTransforms(CI);
6692}
6693
6694Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006695 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006696}
6697
6698Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6699 return commonCastTransforms(CI);
6700}
6701
6702Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6703
6704 // If the operands are integer typed then apply the integer transforms,
6705 // otherwise just apply the common ones.
6706 Value *Src = CI.getOperand(0);
6707 const Type *SrcTy = Src->getType();
6708 const Type *DestTy = CI.getType();
6709
Chris Lattner03c49532007-01-15 02:27:26 +00006710 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006711 if (Instruction *Result = commonIntCastTransforms(CI))
6712 return Result;
6713 } else {
6714 if (Instruction *Result = commonCastTransforms(CI))
6715 return Result;
6716 }
6717
6718
6719 // Get rid of casts from one type to the same type. These are useless and can
6720 // be replaced by the operand.
6721 if (DestTy == Src->getType())
6722 return ReplaceInstUsesWith(CI, Src);
6723
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006724 // If the source and destination are pointers, and this cast is equivalent to
6725 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6726 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006727 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6728 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6729 const Type *DstElTy = DstPTy->getElementType();
6730 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006731
Reid Spencerc635f472006-12-31 05:48:39 +00006732 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006733 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006734 while (SrcElTy != DstElTy &&
6735 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6736 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6737 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006738 ++NumZeros;
6739 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006740
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006741 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006742 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006743 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6744 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006745 }
6746 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006747 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006748
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006749 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6750 if (SVI->hasOneUse()) {
6751 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6752 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006753 if (isa<VectorType>(DestTy) &&
6754 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006755 SVI->getType()->getNumElements()) {
6756 CastInst *Tmp;
6757 // If either of the operands is a cast from CI.getType(), then
6758 // evaluating the shuffle in the casted destination's type will allow
6759 // us to eliminate at least one cast.
6760 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6761 Tmp->getOperand(0)->getType() == DestTy) ||
6762 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6763 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006764 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6765 SVI->getOperand(0), DestTy, &CI);
6766 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6767 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006768 // Return a new shuffle vector. Use the same element ID's, as we
6769 // know the vector types match #elts.
6770 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006771 }
6772 }
6773 }
6774 }
Chris Lattner260ab202002-04-18 17:39:14 +00006775 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006776}
6777
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006778/// GetSelectFoldableOperands - We want to turn code that looks like this:
6779/// %C = or %A, %B
6780/// %D = select %cond, %C, %A
6781/// into:
6782/// %C = select %cond, %B, 0
6783/// %D = or %A, %C
6784///
6785/// Assuming that the specified instruction is an operand to the select, return
6786/// a bitmask indicating which operands of this instruction are foldable if they
6787/// equal the other incoming value of the select.
6788///
6789static unsigned GetSelectFoldableOperands(Instruction *I) {
6790 switch (I->getOpcode()) {
6791 case Instruction::Add:
6792 case Instruction::Mul:
6793 case Instruction::And:
6794 case Instruction::Or:
6795 case Instruction::Xor:
6796 return 3; // Can fold through either operand.
6797 case Instruction::Sub: // Can only fold on the amount subtracted.
6798 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006799 case Instruction::LShr:
6800 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006801 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006802 default:
6803 return 0; // Cannot fold
6804 }
6805}
6806
6807/// GetSelectFoldableConstant - For the same transformation as the previous
6808/// function, return the identity constant that goes into the select.
6809static Constant *GetSelectFoldableConstant(Instruction *I) {
6810 switch (I->getOpcode()) {
6811 default: assert(0 && "This cannot happen!"); abort();
6812 case Instruction::Add:
6813 case Instruction::Sub:
6814 case Instruction::Or:
6815 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006816 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006817 case Instruction::LShr:
6818 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006819 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006820 case Instruction::And:
6821 return ConstantInt::getAllOnesValue(I->getType());
6822 case Instruction::Mul:
6823 return ConstantInt::get(I->getType(), 1);
6824 }
6825}
6826
Chris Lattner411336f2005-01-19 21:50:18 +00006827/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6828/// have the same opcode and only one use each. Try to simplify this.
6829Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6830 Instruction *FI) {
6831 if (TI->getNumOperands() == 1) {
6832 // If this is a non-volatile load or a cast from the same type,
6833 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006834 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006835 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6836 return 0;
6837 } else {
6838 return 0; // unknown unary op.
6839 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006840
Chris Lattner411336f2005-01-19 21:50:18 +00006841 // Fold this by inserting a select from the input values.
6842 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6843 FI->getOperand(0), SI.getName()+".v");
6844 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006845 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6846 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006847 }
6848
Reid Spencer2341c222007-02-02 02:16:23 +00006849 // Only handle binary operators here.
6850 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006851 return 0;
6852
6853 // Figure out if the operations have any operands in common.
6854 Value *MatchOp, *OtherOpT, *OtherOpF;
6855 bool MatchIsOpZero;
6856 if (TI->getOperand(0) == FI->getOperand(0)) {
6857 MatchOp = TI->getOperand(0);
6858 OtherOpT = TI->getOperand(1);
6859 OtherOpF = FI->getOperand(1);
6860 MatchIsOpZero = true;
6861 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6862 MatchOp = TI->getOperand(1);
6863 OtherOpT = TI->getOperand(0);
6864 OtherOpF = FI->getOperand(0);
6865 MatchIsOpZero = false;
6866 } else if (!TI->isCommutative()) {
6867 return 0;
6868 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6869 MatchOp = TI->getOperand(0);
6870 OtherOpT = TI->getOperand(1);
6871 OtherOpF = FI->getOperand(0);
6872 MatchIsOpZero = true;
6873 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6874 MatchOp = TI->getOperand(1);
6875 OtherOpT = TI->getOperand(0);
6876 OtherOpF = FI->getOperand(1);
6877 MatchIsOpZero = true;
6878 } else {
6879 return 0;
6880 }
6881
6882 // If we reach here, they do have operations in common.
6883 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6884 OtherOpF, SI.getName()+".v");
6885 InsertNewInstBefore(NewSI, SI);
6886
6887 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6888 if (MatchIsOpZero)
6889 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6890 else
6891 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006892 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006893 assert(0 && "Shouldn't get here");
6894 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006895}
6896
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006897Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006898 Value *CondVal = SI.getCondition();
6899 Value *TrueVal = SI.getTrueValue();
6900 Value *FalseVal = SI.getFalseValue();
6901
6902 // select true, X, Y -> X
6903 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006904 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006905 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006906
6907 // select C, X, X -> X
6908 if (TrueVal == FalseVal)
6909 return ReplaceInstUsesWith(SI, TrueVal);
6910
Chris Lattner81a7a232004-10-16 18:11:37 +00006911 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6912 return ReplaceInstUsesWith(SI, FalseVal);
6913 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6914 return ReplaceInstUsesWith(SI, TrueVal);
6915 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6916 if (isa<Constant>(TrueVal))
6917 return ReplaceInstUsesWith(SI, TrueVal);
6918 else
6919 return ReplaceInstUsesWith(SI, FalseVal);
6920 }
6921
Reid Spencer542964f2007-01-11 18:21:29 +00006922 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006923 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006924 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006925 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006926 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006927 } else {
6928 // Change: A = select B, false, C --> A = and !B, C
6929 Value *NotCond =
6930 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6931 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006932 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006933 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006934 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006935 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006936 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006937 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006938 } else {
6939 // Change: A = select B, C, true --> A = or !B, C
6940 Value *NotCond =
6941 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6942 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006943 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006944 }
6945 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006946 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006947
Chris Lattner183b3362004-04-09 19:05:30 +00006948 // Selecting between two integer constants?
6949 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6950 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6951 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006952 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006953 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006954 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006955 // select C, 0, 1 -> cast !C to int
6956 Value *NotCond =
6957 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006958 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006959 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006960 }
Chris Lattner35167c32004-06-09 07:59:58 +00006961
Reid Spencer266e42b2006-12-23 06:05:41 +00006962 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006963
Reid Spencer266e42b2006-12-23 06:05:41 +00006964 // (x <s 0) ? -1 : 0 -> ashr x, 31
6965 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006966 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6967 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6968 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006969 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006970 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006971 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006972 else {
6973 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006974 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006975 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006976 }
6977
6978 if (CanXForm) {
6979 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006980 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006981 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006982 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006983 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6984 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6985 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006986 InsertNewInstBefore(SRA, SI);
6987
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006988 // Finally, convert to the type of the select RHS. We figure out
6989 // if this requires a SExt, Trunc or BitCast based on the sizes.
6990 Instruction::CastOps opc = Instruction::BitCast;
6991 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6992 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6993 if (SRASize < SISize)
6994 opc = Instruction::SExt;
6995 else if (SRASize > SISize)
6996 opc = Instruction::Trunc;
6997 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006998 }
6999 }
7000
7001
7002 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00007003 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007004 // non-constant value, eliminate this whole mess. This corresponds to
7005 // cases like this: ((X & 27) ? 27 : 0)
7006 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007007 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007008 cast<Constant>(IC->getOperand(1))->isNullValue())
7009 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7010 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007011 isa<ConstantInt>(ICA->getOperand(1)) &&
7012 (ICA->getOperand(1) == TrueValC ||
7013 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007014 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7015 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007016 // know whether we have a icmp_ne or icmp_eq and whether the
7017 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00007018 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007019 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007020 Value *V = ICA;
7021 if (ShouldNotVal)
7022 V = InsertNewInstBefore(BinaryOperator::create(
7023 Instruction::Xor, V, ICA->getOperand(1)), SI);
7024 return ReplaceInstUsesWith(SI, V);
7025 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007026 }
Chris Lattner533bc492004-03-30 19:37:13 +00007027 }
Chris Lattner623fba12004-04-10 22:21:27 +00007028
7029 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007030 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7031 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007032 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007033 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007034 return ReplaceInstUsesWith(SI, FalseVal);
7035 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007036 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007037 return ReplaceInstUsesWith(SI, TrueVal);
7038 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7039
Reid Spencer266e42b2006-12-23 06:05:41 +00007040 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007041 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007042 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007043 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007044 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007045 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7046 return ReplaceInstUsesWith(SI, TrueVal);
7047 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7048 }
7049 }
7050
7051 // See if we are selecting two values based on a comparison of the two values.
7052 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7053 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7054 // Transform (X == Y) ? X : Y -> Y
7055 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7056 return ReplaceInstUsesWith(SI, FalseVal);
7057 // Transform (X != Y) ? X : Y -> X
7058 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7059 return ReplaceInstUsesWith(SI, TrueVal);
7060 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7061
7062 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7063 // Transform (X == Y) ? Y : X -> X
7064 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7065 return ReplaceInstUsesWith(SI, FalseVal);
7066 // Transform (X != Y) ? Y : X -> Y
7067 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007068 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007069 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7070 }
7071 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007072
Chris Lattnera04c9042005-01-13 22:52:24 +00007073 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7074 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7075 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007076 Instruction *AddOp = 0, *SubOp = 0;
7077
Chris Lattner411336f2005-01-19 21:50:18 +00007078 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7079 if (TI->getOpcode() == FI->getOpcode())
7080 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7081 return IV;
7082
7083 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7084 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007085 if (TI->getOpcode() == Instruction::Sub &&
7086 FI->getOpcode() == Instruction::Add) {
7087 AddOp = FI; SubOp = TI;
7088 } else if (FI->getOpcode() == Instruction::Sub &&
7089 TI->getOpcode() == Instruction::Add) {
7090 AddOp = TI; SubOp = FI;
7091 }
7092
7093 if (AddOp) {
7094 Value *OtherAddOp = 0;
7095 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7096 OtherAddOp = AddOp->getOperand(1);
7097 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7098 OtherAddOp = AddOp->getOperand(0);
7099 }
7100
7101 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007102 // So at this point we know we have (Y -> OtherAddOp):
7103 // select C, (add X, Y), (sub X, Z)
7104 Value *NegVal; // Compute -Z
7105 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7106 NegVal = ConstantExpr::getNeg(C);
7107 } else {
7108 NegVal = InsertNewInstBefore(
7109 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007110 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007111
7112 Value *NewTrueOp = OtherAddOp;
7113 Value *NewFalseOp = NegVal;
7114 if (AddOp != TI)
7115 std::swap(NewTrueOp, NewFalseOp);
7116 Instruction *NewSel =
7117 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7118
7119 NewSel = InsertNewInstBefore(NewSel, SI);
7120 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007121 }
7122 }
7123 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007124
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007125 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007126 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007127 // See the comment above GetSelectFoldableOperands for a description of the
7128 // transformation we are doing here.
7129 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7130 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7131 !isa<Constant>(FalseVal))
7132 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7133 unsigned OpToFold = 0;
7134 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7135 OpToFold = 1;
7136 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7137 OpToFold = 2;
7138 }
7139
7140 if (OpToFold) {
7141 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007142 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007143 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007144 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007145 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7147 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007148 else {
7149 assert(0 && "Unknown instruction!!");
7150 }
7151 }
7152 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007153
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007154 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7155 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7156 !isa<Constant>(TrueVal))
7157 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7158 unsigned OpToFold = 0;
7159 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7160 OpToFold = 1;
7161 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7162 OpToFold = 2;
7163 }
7164
7165 if (OpToFold) {
7166 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007167 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007168 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007169 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007170 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7172 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007173 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007174 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007175 }
7176 }
7177 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007178
7179 if (BinaryOperator::isNot(CondVal)) {
7180 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7181 SI.setOperand(1, FalseVal);
7182 SI.setOperand(2, TrueVal);
7183 return &SI;
7184 }
7185
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007186 return 0;
7187}
7188
Chris Lattner82f2ef22006-03-06 20:18:44 +00007189/// GetKnownAlignment - If the specified pointer has an alignment that we can
7190/// determine, return it, otherwise return 0.
7191static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7192 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7193 unsigned Align = GV->getAlignment();
7194 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007195 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007196 return Align;
7197 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7198 unsigned Align = AI->getAlignment();
7199 if (Align == 0 && TD) {
7200 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007201 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007202 else if (isa<MallocInst>(AI)) {
7203 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007204 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007205 Align =
7206 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007207 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007208 Align =
7209 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007210 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007211 }
7212 }
7213 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007214 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007215 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007216 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007217 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007218 if (isa<PointerType>(CI->getOperand(0)->getType()))
7219 return GetKnownAlignment(CI->getOperand(0), TD);
7220 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007221 } else if (isa<GetElementPtrInst>(V) ||
7222 (isa<ConstantExpr>(V) &&
7223 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7224 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007225 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7226 if (BaseAlignment == 0) return 0;
7227
7228 // If all indexes are zero, it is just the alignment of the base pointer.
7229 bool AllZeroOperands = true;
7230 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7231 if (!isa<Constant>(GEPI->getOperand(i)) ||
7232 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7233 AllZeroOperands = false;
7234 break;
7235 }
7236 if (AllZeroOperands)
7237 return BaseAlignment;
7238
7239 // Otherwise, if the base alignment is >= the alignment we expect for the
7240 // base pointer type, then we know that the resultant pointer is aligned at
7241 // least as much as its type requires.
7242 if (!TD) return 0;
7243
7244 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007245 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007246 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007247 <= BaseAlignment) {
7248 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007249 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007250 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007251 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007252 return 0;
7253 }
7254 return 0;
7255}
7256
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007257
Chris Lattnerc66b2232006-01-13 20:11:04 +00007258/// visitCallInst - CallInst simplification. This mostly only handles folding
7259/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7260/// the heavy lifting.
7261///
Chris Lattner970c33a2003-06-19 17:00:31 +00007262Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007263 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7264 if (!II) return visitCallSite(&CI);
7265
Chris Lattner51ea1272004-02-28 05:22:00 +00007266 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7267 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007268 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007269 bool Changed = false;
7270
7271 // memmove/cpy/set of zero bytes is a noop.
7272 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7273 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7274
Chris Lattner00648e12004-10-12 04:52:52 +00007275 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007276 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007277 // Replace the instruction with just byte operations. We would
7278 // transform other cases to loads/stores, but we don't know if
7279 // alignment is sufficient.
7280 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007281 }
7282
Chris Lattner00648e12004-10-12 04:52:52 +00007283 // If we have a memmove and the source operation is a constant global,
7284 // then the source and dest pointers can't alias, so we can change this
7285 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007286 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007287 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7288 if (GVSrc->isConstant()) {
7289 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007290 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007291 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007292 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007293 Name = "llvm.memcpy.i32";
7294 else
7295 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007296 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007297 CI.getCalledFunction()->getFunctionType());
7298 CI.setOperand(0, MemCpy);
7299 Changed = true;
7300 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007301 }
Chris Lattner00648e12004-10-12 04:52:52 +00007302
Chris Lattner82f2ef22006-03-06 20:18:44 +00007303 // If we can determine a pointer alignment that is bigger than currently
7304 // set, update the alignment.
7305 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7306 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7307 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7308 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007309 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007310 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007311 Changed = true;
7312 }
7313 } else if (isa<MemSetInst>(MI)) {
7314 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007315 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007316 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007317 Changed = true;
7318 }
7319 }
7320
Chris Lattnerc66b2232006-01-13 20:11:04 +00007321 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007322 } else {
7323 switch (II->getIntrinsicID()) {
7324 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007325 case Intrinsic::ppc_altivec_lvx:
7326 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007327 case Intrinsic::x86_sse_loadu_ps:
7328 case Intrinsic::x86_sse2_loadu_pd:
7329 case Intrinsic::x86_sse2_loadu_dq:
7330 // Turn PPC lvx -> load if the pointer is known aligned.
7331 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007332 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007333 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007334 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007335 return new LoadInst(Ptr);
7336 }
7337 break;
7338 case Intrinsic::ppc_altivec_stvx:
7339 case Intrinsic::ppc_altivec_stvxl:
7340 // Turn stvx -> store if the pointer is known aligned.
7341 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007342 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007343 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7344 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007345 return new StoreInst(II->getOperand(1), Ptr);
7346 }
7347 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007348 case Intrinsic::x86_sse_storeu_ps:
7349 case Intrinsic::x86_sse2_storeu_pd:
7350 case Intrinsic::x86_sse2_storeu_dq:
7351 case Intrinsic::x86_sse2_storel_dq:
7352 // Turn X86 storeu -> store if the pointer is known aligned.
7353 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7354 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007355 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7356 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007357 return new StoreInst(II->getOperand(2), Ptr);
7358 }
7359 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007360
7361 case Intrinsic::x86_sse_cvttss2si: {
7362 // These intrinsics only demands the 0th element of its input vector. If
7363 // we can simplify the input based on that, do so now.
7364 uint64_t UndefElts;
7365 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7366 UndefElts)) {
7367 II->setOperand(1, V);
7368 return II;
7369 }
7370 break;
7371 }
7372
Chris Lattnere79d2492006-04-06 19:19:17 +00007373 case Intrinsic::ppc_altivec_vperm:
7374 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007375 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007376 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7377
7378 // Check that all of the elements are integer constants or undefs.
7379 bool AllEltsOk = true;
7380 for (unsigned i = 0; i != 16; ++i) {
7381 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7382 !isa<UndefValue>(Mask->getOperand(i))) {
7383 AllEltsOk = false;
7384 break;
7385 }
7386 }
7387
7388 if (AllEltsOk) {
7389 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007390 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7391 II->getOperand(1), Mask->getType(), CI);
7392 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7393 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007394 Value *Result = UndefValue::get(Op0->getType());
7395
7396 // Only extract each element once.
7397 Value *ExtractedElts[32];
7398 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7399
7400 for (unsigned i = 0; i != 16; ++i) {
7401 if (isa<UndefValue>(Mask->getOperand(i)))
7402 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007403 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007404 Idx &= 31; // Match the hardware behavior.
7405
7406 if (ExtractedElts[Idx] == 0) {
7407 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007408 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007409 InsertNewInstBefore(Elt, CI);
7410 ExtractedElts[Idx] = Elt;
7411 }
7412
7413 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007414 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007415 InsertNewInstBefore(cast<Instruction>(Result), CI);
7416 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007417 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007418 }
7419 }
7420 break;
7421
Chris Lattner503221f2006-01-13 21:28:09 +00007422 case Intrinsic::stackrestore: {
7423 // If the save is right next to the restore, remove the restore. This can
7424 // happen when variable allocas are DCE'd.
7425 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7426 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7427 BasicBlock::iterator BI = SS;
7428 if (&*++BI == II)
7429 return EraseInstFromFunction(CI);
7430 }
7431 }
7432
7433 // If the stack restore is in a return/unwind block and if there are no
7434 // allocas or calls between the restore and the return, nuke the restore.
7435 TerminatorInst *TI = II->getParent()->getTerminator();
7436 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7437 BasicBlock::iterator BI = II;
7438 bool CannotRemove = false;
7439 for (++BI; &*BI != TI; ++BI) {
7440 if (isa<AllocaInst>(BI) ||
7441 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7442 CannotRemove = true;
7443 break;
7444 }
7445 }
7446 if (!CannotRemove)
7447 return EraseInstFromFunction(CI);
7448 }
7449 break;
7450 }
7451 }
Chris Lattner00648e12004-10-12 04:52:52 +00007452 }
7453
Chris Lattnerc66b2232006-01-13 20:11:04 +00007454 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007455}
7456
7457// InvokeInst simplification
7458//
7459Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007460 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007461}
7462
Chris Lattneraec3d942003-10-07 22:32:43 +00007463// visitCallSite - Improvements for call and invoke instructions.
7464//
7465Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007466 bool Changed = false;
7467
7468 // If the callee is a constexpr cast of a function, attempt to move the cast
7469 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007470 if (transformConstExprCastCall(CS)) return 0;
7471
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007472 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007473
Chris Lattner61d9d812005-05-13 07:09:09 +00007474 if (Function *CalleeF = dyn_cast<Function>(Callee))
7475 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7476 Instruction *OldCall = CS.getInstruction();
7477 // If the call and callee calling conventions don't match, this call must
7478 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007479 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007480 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007481 if (!OldCall->use_empty())
7482 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7483 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7484 return EraseInstFromFunction(*OldCall);
7485 return 0;
7486 }
7487
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007488 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7489 // This instruction is not reachable, just remove it. We insert a store to
7490 // undef so that we know that this code is not reachable, despite the fact
7491 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007492 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007493 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007494 CS.getInstruction());
7495
7496 if (!CS.getInstruction()->use_empty())
7497 CS.getInstruction()->
7498 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7499
7500 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7501 // Don't break the CFG, insert a dummy cond branch.
7502 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007503 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007504 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007505 return EraseInstFromFunction(*CS.getInstruction());
7506 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007507
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007508 const PointerType *PTy = cast<PointerType>(Callee->getType());
7509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7510 if (FTy->isVarArg()) {
7511 // See if we can optimize any arguments passed through the varargs area of
7512 // the call.
7513 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7514 E = CS.arg_end(); I != E; ++I)
7515 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7516 // If this cast does not effect the value passed through the varargs
7517 // area, we can eliminate the use of the cast.
7518 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007519 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007520 *I = Op;
7521 Changed = true;
7522 }
7523 }
7524 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007525
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007526 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007527}
7528
Chris Lattner970c33a2003-06-19 17:00:31 +00007529// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7530// attempt to move the cast to the arguments of the call/invoke.
7531//
7532bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7533 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7534 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007535 if (CE->getOpcode() != Instruction::BitCast ||
7536 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007537 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007538 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007539 Instruction *Caller = CS.getInstruction();
7540
7541 // Okay, this is a cast from a function to a different type. Unless doing so
7542 // would cause a type conversion of one of our arguments, change this call to
7543 // be a direct call with arguments casted to the appropriate types.
7544 //
7545 const FunctionType *FT = Callee->getFunctionType();
7546 const Type *OldRetTy = Caller->getType();
7547
Chris Lattner1f7942f2004-01-14 06:06:08 +00007548 // Check to see if we are changing the return type...
7549 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007550 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007551 OldRetTy != FT->getReturnType() &&
7552 // Conversion is ok if changing from pointer to int of same size.
7553 !(isa<PointerType>(FT->getReturnType()) &&
7554 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007555 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007556
7557 // If the callsite is an invoke instruction, and the return value is used by
7558 // a PHI node in a successor, we cannot change the return type of the call
7559 // because there is no place to put the cast instruction (without breaking
7560 // the critical edge). Bail out in this case.
7561 if (!Caller->use_empty())
7562 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7563 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7564 UI != E; ++UI)
7565 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7566 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007567 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007568 return false;
7569 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007570
7571 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7572 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007573
Chris Lattner970c33a2003-06-19 17:00:31 +00007574 CallSite::arg_iterator AI = CS.arg_begin();
7575 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7576 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007577 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007578 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007579 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007580 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007581 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007582 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007583 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7584 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7585 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007586 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007587 }
7588
7589 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007590 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007591 return false; // Do not delete arguments unless we have a function body...
7592
7593 // Okay, we decided that this is a safe thing to do: go ahead and start
7594 // inserting cast instructions as necessary...
7595 std::vector<Value*> Args;
7596 Args.reserve(NumActualArgs);
7597
7598 AI = CS.arg_begin();
7599 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7600 const Type *ParamTy = FT->getParamType(i);
7601 if ((*AI)->getType() == ParamTy) {
7602 Args.push_back(*AI);
7603 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007604 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007605 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007606 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007607 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007608 }
7609 }
7610
7611 // If the function takes more arguments than the call was taking, add them
7612 // now...
7613 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7614 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7615
7616 // If we are removing arguments to the function, emit an obnoxious warning...
7617 if (FT->getNumParams() < NumActualArgs)
7618 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007619 cerr << "WARNING: While resolving call to function '"
7620 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007621 } else {
7622 // Add all of the arguments in their promoted form to the arg list...
7623 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7624 const Type *PTy = getPromotedType((*AI)->getType());
7625 if (PTy != (*AI)->getType()) {
7626 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007627 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7628 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007629 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007630 InsertNewInstBefore(Cast, *Caller);
7631 Args.push_back(Cast);
7632 } else {
7633 Args.push_back(*AI);
7634 }
7635 }
7636 }
7637
7638 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007639 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007640
7641 Instruction *NC;
7642 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007643 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007644 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007645 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007646 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007647 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007648 if (cast<CallInst>(Caller)->isTailCall())
7649 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007650 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007651 }
7652
Chris Lattner6e0123b2007-02-11 01:23:03 +00007653 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007654 Value *NV = NC;
7655 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7656 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007657 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007658 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7659 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007660 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007661
7662 // If this is an invoke instruction, we should insert it after the first
7663 // non-phi, instruction in the normal successor block.
7664 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7665 BasicBlock::iterator I = II->getNormalDest()->begin();
7666 while (isa<PHINode>(I)) ++I;
7667 InsertNewInstBefore(NC, *I);
7668 } else {
7669 // Otherwise, it's a call, just insert cast right after the call instr
7670 InsertNewInstBefore(NC, *Caller);
7671 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007672 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007673 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007674 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007675 }
7676 }
7677
7678 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7679 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007680 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007681 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007682 return true;
7683}
7684
Chris Lattnercadac0c2006-11-01 04:51:18 +00007685/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7686/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7687/// and a single binop.
7688Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7689 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007690 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7691 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007692 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007693 Value *LHSVal = FirstInst->getOperand(0);
7694 Value *RHSVal = FirstInst->getOperand(1);
7695
7696 const Type *LHSType = LHSVal->getType();
7697 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007698
7699 // Scan to see if all operands are the same opcode, all have one use, and all
7700 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007701 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007702 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007703 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007704 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007705 // types or GEP's with different index types.
7706 I->getOperand(0)->getType() != LHSType ||
7707 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007708 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007709
7710 // If they are CmpInst instructions, check their predicates
7711 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7712 if (cast<CmpInst>(I)->getPredicate() !=
7713 cast<CmpInst>(FirstInst)->getPredicate())
7714 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007715
7716 // Keep track of which operand needs a phi node.
7717 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7718 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007719 }
7720
Chris Lattner4f218d52006-11-08 19:42:28 +00007721 // Otherwise, this is safe to transform, determine if it is profitable.
7722
7723 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7724 // Indexes are often folded into load/store instructions, so we don't want to
7725 // hide them behind a phi.
7726 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7727 return 0;
7728
Chris Lattnercadac0c2006-11-01 04:51:18 +00007729 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007730 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007731 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007732 if (LHSVal == 0) {
7733 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7734 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7735 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007736 InsertNewInstBefore(NewLHS, PN);
7737 LHSVal = NewLHS;
7738 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007739
7740 if (RHSVal == 0) {
7741 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7742 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7743 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007744 InsertNewInstBefore(NewRHS, PN);
7745 RHSVal = NewRHS;
7746 }
7747
Chris Lattnercd62f112006-11-08 19:29:23 +00007748 // Add all operands to the new PHIs.
7749 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7750 if (NewLHS) {
7751 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7752 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7753 }
7754 if (NewRHS) {
7755 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7756 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7757 }
7758 }
7759
Chris Lattnercadac0c2006-11-01 04:51:18 +00007760 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007761 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007762 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7763 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7764 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007765 else {
7766 assert(isa<GetElementPtrInst>(FirstInst));
7767 return new GetElementPtrInst(LHSVal, RHSVal);
7768 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007769}
7770
Chris Lattner14f82c72006-11-01 07:13:54 +00007771/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7772/// of the block that defines it. This means that it must be obvious the value
7773/// of the load is not changed from the point of the load to the end of the
7774/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007775///
7776/// Finally, it is safe, but not profitable, to sink a load targetting a
7777/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7778/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007779static bool isSafeToSinkLoad(LoadInst *L) {
7780 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7781
7782 for (++BBI; BBI != E; ++BBI)
7783 if (BBI->mayWriteToMemory())
7784 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007785
7786 // Check for non-address taken alloca. If not address-taken already, it isn't
7787 // profitable to do this xform.
7788 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7789 bool isAddressTaken = false;
7790 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7791 UI != E; ++UI) {
7792 if (isa<LoadInst>(UI)) continue;
7793 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7794 // If storing TO the alloca, then the address isn't taken.
7795 if (SI->getOperand(1) == AI) continue;
7796 }
7797 isAddressTaken = true;
7798 break;
7799 }
7800
7801 if (!isAddressTaken)
7802 return false;
7803 }
7804
Chris Lattner14f82c72006-11-01 07:13:54 +00007805 return true;
7806}
7807
Chris Lattner970c33a2003-06-19 17:00:31 +00007808
Chris Lattner7515cab2004-11-14 19:13:23 +00007809// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7810// operator and they all are only used by the PHI, PHI together their
7811// inputs, and do the operation once, to the result of the PHI.
7812Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7813 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7814
7815 // Scan the instruction, looking for input operations that can be folded away.
7816 // If all input operands to the phi are the same instruction (e.g. a cast from
7817 // the same type or "+42") we can pull the operation through the PHI, reducing
7818 // code size and simplifying code.
7819 Constant *ConstantOp = 0;
7820 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007821 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007822 if (isa<CastInst>(FirstInst)) {
7823 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007824 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007825 // Can fold binop, compare or shift here if the RHS is a constant,
7826 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007827 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007828 if (ConstantOp == 0)
7829 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007830 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7831 isVolatile = LI->isVolatile();
7832 // We can't sink the load if the loaded value could be modified between the
7833 // load and the PHI.
7834 if (LI->getParent() != PN.getIncomingBlock(0) ||
7835 !isSafeToSinkLoad(LI))
7836 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007837 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007838 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007839 return FoldPHIArgBinOpIntoPHI(PN);
7840 // Can't handle general GEPs yet.
7841 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007842 } else {
7843 return 0; // Cannot fold this operation.
7844 }
7845
7846 // Check to see if all arguments are the same operation.
7847 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7848 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7849 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007850 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007851 return 0;
7852 if (CastSrcTy) {
7853 if (I->getOperand(0)->getType() != CastSrcTy)
7854 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007855 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007856 // We can't sink the load if the loaded value could be modified between
7857 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007858 if (LI->isVolatile() != isVolatile ||
7859 LI->getParent() != PN.getIncomingBlock(i) ||
7860 !isSafeToSinkLoad(LI))
7861 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007862 } else if (I->getOperand(1) != ConstantOp) {
7863 return 0;
7864 }
7865 }
7866
7867 // Okay, they are all the same operation. Create a new PHI node of the
7868 // correct type, and PHI together all of the LHS's of the instructions.
7869 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7870 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007871 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007872
7873 Value *InVal = FirstInst->getOperand(0);
7874 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007875
7876 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007877 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7878 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7879 if (NewInVal != InVal)
7880 InVal = 0;
7881 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7882 }
7883
7884 Value *PhiVal;
7885 if (InVal) {
7886 // The new PHI unions all of the same values together. This is really
7887 // common, so we handle it intelligently here for compile-time speed.
7888 PhiVal = InVal;
7889 delete NewPN;
7890 } else {
7891 InsertNewInstBefore(NewPN, PN);
7892 PhiVal = NewPN;
7893 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007894
Chris Lattner7515cab2004-11-14 19:13:23 +00007895 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007896 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7897 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007898 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007899 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007900 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007901 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007902 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7903 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7904 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007905 else
Reid Spencer2341c222007-02-02 02:16:23 +00007906 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007907 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007908}
Chris Lattner48a44f72002-05-02 17:06:02 +00007909
Chris Lattner71536432005-01-17 05:10:15 +00007910/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7911/// that is dead.
7912static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7913 if (PN->use_empty()) return true;
7914 if (!PN->hasOneUse()) return false;
7915
7916 // Remember this node, and if we find the cycle, return.
7917 if (!PotentiallyDeadPHIs.insert(PN).second)
7918 return true;
7919
7920 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7921 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007922
Chris Lattner71536432005-01-17 05:10:15 +00007923 return false;
7924}
7925
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007926// PHINode simplification
7927//
Chris Lattner113f4f42002-06-25 16:13:24 +00007928Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007929 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007930 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007931
Owen Andersonae8aa642006-07-10 22:03:18 +00007932 if (Value *V = PN.hasConstantValue())
7933 return ReplaceInstUsesWith(PN, V);
7934
Owen Andersonae8aa642006-07-10 22:03:18 +00007935 // If all PHI operands are the same operation, pull them through the PHI,
7936 // reducing code size.
7937 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7938 PN.getIncomingValue(0)->hasOneUse())
7939 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7940 return Result;
7941
7942 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7943 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7944 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007945 if (PN.hasOneUse()) {
7946 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7947 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007948 std::set<PHINode*> PotentiallyDeadPHIs;
7949 PotentiallyDeadPHIs.insert(&PN);
7950 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7951 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7952 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007953
7954 // If this phi has a single use, and if that use just computes a value for
7955 // the next iteration of a loop, delete the phi. This occurs with unused
7956 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7957 // common case here is good because the only other things that catch this
7958 // are induction variable analysis (sometimes) and ADCE, which is only run
7959 // late.
7960 if (PHIUser->hasOneUse() &&
7961 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7962 PHIUser->use_back() == &PN) {
7963 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7964 }
7965 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007966
Chris Lattner91daeb52003-12-19 05:58:40 +00007967 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007968}
7969
Reid Spencer13bc5d72006-12-12 09:18:51 +00007970static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7971 Instruction *InsertPoint,
7972 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007973 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7974 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007975 // We must cast correctly to the pointer type. Ensure that we
7976 // sign extend the integer value if it is smaller as this is
7977 // used for address computation.
7978 Instruction::CastOps opcode =
7979 (VTySize < PtrSize ? Instruction::SExt :
7980 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7981 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007982}
7983
Chris Lattner48a44f72002-05-02 17:06:02 +00007984
Chris Lattner113f4f42002-06-25 16:13:24 +00007985Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007986 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007987 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007988 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007989 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007990 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007991
Chris Lattner81a7a232004-10-16 18:11:37 +00007992 if (isa<UndefValue>(GEP.getOperand(0)))
7993 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7994
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007995 bool HasZeroPointerIndex = false;
7996 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7997 HasZeroPointerIndex = C->isNullValue();
7998
7999 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008001
Chris Lattner69193f92004-04-05 01:30:19 +00008002 // Eliminate unneeded casts for indices.
8003 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00008004 gep_type_iterator GTI = gep_type_begin(GEP);
8005 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8006 if (isa<SequentialType>(*GTI)) {
8007 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008008 if (CI->getOpcode() == Instruction::ZExt ||
8009 CI->getOpcode() == Instruction::SExt) {
8010 const Type *SrcTy = CI->getOperand(0)->getType();
8011 // We can eliminate a cast from i32 to i64 iff the target
8012 // is a 32-bit pointer target.
8013 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8014 MadeChange = true;
8015 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008016 }
8017 }
8018 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008019 // If we are using a wider index than needed for this platform, shrink it
8020 // to what we need. If the incoming value needs a cast instruction,
8021 // insert it. This explicit cast can make subsequent optimizations more
8022 // obvious.
8023 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008024 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008025 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008026 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008027 MadeChange = true;
8028 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008029 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8030 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008031 GEP.setOperand(i, Op);
8032 MadeChange = true;
8033 }
Chris Lattner69193f92004-04-05 01:30:19 +00008034 }
8035 if (MadeChange) return &GEP;
8036
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008037 // Combine Indices - If the source pointer to this getelementptr instruction
8038 // is a getelementptr instruction, combine the indices of the two
8039 // getelementptr instructions into a single instruction.
8040 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008041 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008042 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008043 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008044
8045 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008046 // Note that if our source is a gep chain itself that we wait for that
8047 // chain to be resolved before we perform this transformation. This
8048 // avoids us creating a TON of code in some cases.
8049 //
8050 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8051 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8052 return 0; // Wait until our source is folded to completion.
8053
Chris Lattneraf6094f2007-02-15 22:48:32 +00008054 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008055
8056 // Find out whether the last index in the source GEP is a sequential idx.
8057 bool EndsWithSequential = false;
8058 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8059 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008060 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008061
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008062 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008063 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008064 // Replace: gep (gep %P, long B), long A, ...
8065 // With: T = long A+B; gep %P, T, ...
8066 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008067 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008068 if (SO1 == Constant::getNullValue(SO1->getType())) {
8069 Sum = GO1;
8070 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8071 Sum = SO1;
8072 } else {
8073 // If they aren't the same type, convert both to an integer of the
8074 // target's pointer size.
8075 if (SO1->getType() != GO1->getType()) {
8076 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008077 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008078 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008079 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008080 } else {
8081 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008082 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008083 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008084 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008085
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008086 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008087 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008088 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008089 } else {
8090 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008091 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8092 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008093 }
8094 }
8095 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008096 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8097 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8098 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008099 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8100 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008101 }
Chris Lattner69193f92004-04-05 01:30:19 +00008102 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008103
8104 // Recycle the GEP we already have if possible.
8105 if (SrcGEPOperands.size() == 2) {
8106 GEP.setOperand(0, SrcGEPOperands[0]);
8107 GEP.setOperand(1, Sum);
8108 return &GEP;
8109 } else {
8110 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8111 SrcGEPOperands.end()-1);
8112 Indices.push_back(Sum);
8113 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8114 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008115 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008116 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008117 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008118 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008119 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8120 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008121 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8122 }
8123
8124 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008125 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8126 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008127
Chris Lattner5f667a62004-05-07 22:09:22 +00008128 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008129 // GEP of global variable. If all of the indices for this GEP are
8130 // constants, we can promote this to a constexpr instead of an instruction.
8131
8132 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008133 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008134 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8135 for (; I != E && isa<Constant>(*I); ++I)
8136 Indices.push_back(cast<Constant>(*I));
8137
8138 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008139 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8140 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008141
8142 // Replace all uses of the GEP with the new constexpr...
8143 return ReplaceInstUsesWith(GEP, CE);
8144 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008145 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008146 if (!isa<PointerType>(X->getType())) {
8147 // Not interesting. Source pointer must be a cast from pointer.
8148 } else if (HasZeroPointerIndex) {
8149 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8150 // into : GEP [10 x ubyte]* X, long 0, ...
8151 //
8152 // This occurs when the program declares an array extern like "int X[];"
8153 //
8154 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8155 const PointerType *XTy = cast<PointerType>(X->getType());
8156 if (const ArrayType *XATy =
8157 dyn_cast<ArrayType>(XTy->getElementType()))
8158 if (const ArrayType *CATy =
8159 dyn_cast<ArrayType>(CPTy->getElementType()))
8160 if (CATy->getElementType() == XATy->getElementType()) {
8161 // At this point, we know that the cast source type is a pointer
8162 // to an array of the same type as the destination pointer
8163 // array. Because the array type is never stepped over (there
8164 // is a leading zero) we can fold the cast into this GEP.
8165 GEP.setOperand(0, X);
8166 return &GEP;
8167 }
8168 } else if (GEP.getNumOperands() == 2) {
8169 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008170 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8171 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008172 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8173 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8174 if (isa<ArrayType>(SrcElTy) &&
8175 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8176 TD->getTypeSize(ResElTy)) {
8177 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008178 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008179 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008180 // V and GEP are both pointer types --> BitCast
8181 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008182 }
Chris Lattner2a893292005-09-13 18:36:04 +00008183
8184 // Transform things like:
8185 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8186 // (where tmp = 8*tmp2) into:
8187 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8188
8189 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008190 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008191 uint64_t ArrayEltSize =
8192 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8193
8194 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8195 // allow either a mul, shift, or constant here.
8196 Value *NewIdx = 0;
8197 ConstantInt *Scale = 0;
8198 if (ArrayEltSize == 1) {
8199 NewIdx = GEP.getOperand(1);
8200 Scale = ConstantInt::get(NewIdx->getType(), 1);
8201 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008202 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008203 Scale = CI;
8204 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8205 if (Inst->getOpcode() == Instruction::Shl &&
8206 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008207 unsigned ShAmt =
8208 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008209 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008210 NewIdx = Inst->getOperand(0);
8211 } else if (Inst->getOpcode() == Instruction::Mul &&
8212 isa<ConstantInt>(Inst->getOperand(1))) {
8213 Scale = cast<ConstantInt>(Inst->getOperand(1));
8214 NewIdx = Inst->getOperand(0);
8215 }
8216 }
8217
8218 // If the index will be to exactly the right offset with the scale taken
8219 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008220 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008221 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008222 Scale = ConstantInt::get(Scale->getType(),
8223 Scale->getZExtValue() / ArrayEltSize);
8224 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008225 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8226 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008227 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8228 NewIdx = InsertNewInstBefore(Sc, GEP);
8229 }
8230
8231 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008232 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008233 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008234 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008235 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8236 // The NewGEP must be pointer typed, so must the old one -> BitCast
8237 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008238 }
8239 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008240 }
Chris Lattnerca081252001-12-14 16:52:21 +00008241 }
8242
Chris Lattnerca081252001-12-14 16:52:21 +00008243 return 0;
8244}
8245
Chris Lattner1085bdf2002-11-04 16:18:53 +00008246Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8247 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8248 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008249 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8250 const Type *NewTy =
8251 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008252 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008253
8254 // Create and insert the replacement instruction...
8255 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008256 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008257 else {
8258 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008259 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008260 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008261
8262 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008263
Chris Lattner1085bdf2002-11-04 16:18:53 +00008264 // Scan to the end of the allocation instructions, to skip over a block of
8265 // allocas if possible...
8266 //
8267 BasicBlock::iterator It = New;
8268 while (isa<AllocationInst>(*It)) ++It;
8269
8270 // Now that I is pointing to the first non-allocation-inst in the block,
8271 // insert our getelementptr instruction...
8272 //
Reid Spencerc635f472006-12-31 05:48:39 +00008273 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008274 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8275 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008276
8277 // Now make everything use the getelementptr instead of the original
8278 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008279 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008280 } else if (isa<UndefValue>(AI.getArraySize())) {
8281 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008282 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008283
8284 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8285 // Note that we only do this for alloca's, because malloc should allocate and
8286 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008287 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008288 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008289 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8290
Chris Lattner1085bdf2002-11-04 16:18:53 +00008291 return 0;
8292}
8293
Chris Lattner8427bff2003-12-07 01:24:23 +00008294Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8295 Value *Op = FI.getOperand(0);
8296
8297 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8298 if (CastInst *CI = dyn_cast<CastInst>(Op))
8299 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8300 FI.setOperand(0, CI->getOperand(0));
8301 return &FI;
8302 }
8303
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008304 // free undef -> unreachable.
8305 if (isa<UndefValue>(Op)) {
8306 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008307 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008308 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008309 return EraseInstFromFunction(FI);
8310 }
8311
Chris Lattnerf3a36602004-02-28 04:57:37 +00008312 // If we have 'free null' delete the instruction. This can happen in stl code
8313 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008314 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008315 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008316
Chris Lattner8427bff2003-12-07 01:24:23 +00008317 return 0;
8318}
8319
8320
Chris Lattner72684fe2005-01-31 05:51:45 +00008321/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008322static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8323 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008324 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008325
8326 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008327 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008328 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008329
Reid Spencer31a4ef42007-01-22 05:51:25 +00008330 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008331 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008332 // If the source is an array, the code below will not succeed. Check to
8333 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8334 // constants.
8335 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8336 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8337 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008338 Value *Idxs[2];
8339 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8340 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008341 SrcTy = cast<PointerType>(CastOp->getType());
8342 SrcPTy = SrcTy->getElementType();
8343 }
8344
Reid Spencer31a4ef42007-01-22 05:51:25 +00008345 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008346 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008347 // Do not allow turning this into a load of an integer, which is then
8348 // casted to a pointer, this pessimizes pointer analysis a lot.
8349 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008350 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8351 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008352
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008353 // Okay, we are casting from one integer or pointer type to another of
8354 // the same size. Instead of casting the pointer before the load, cast
8355 // the result of the loaded value.
8356 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8357 CI->getName(),
8358 LI.isVolatile()),LI);
8359 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008360 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008361 }
Chris Lattner35e24772004-07-13 01:49:43 +00008362 }
8363 }
8364 return 0;
8365}
8366
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008367/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008368/// from this value cannot trap. If it is not obviously safe to load from the
8369/// specified pointer, we do a quick local scan of the basic block containing
8370/// ScanFrom, to determine if the address is already accessed.
8371static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8372 // If it is an alloca or global variable, it is always safe to load from.
8373 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8374
8375 // Otherwise, be a little bit agressive by scanning the local block where we
8376 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008377 // from/to. If so, the previous load or store would have already trapped,
8378 // so there is no harm doing an extra load (also, CSE will later eliminate
8379 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008380 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8381
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008382 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008383 --BBI;
8384
8385 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8386 if (LI->getOperand(0) == V) return true;
8387 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8388 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008389
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008390 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008391 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008392}
8393
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008394Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8395 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008396
Chris Lattnera9d84e32005-05-01 04:24:53 +00008397 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008398 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008399 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8400 return Res;
8401
8402 // None of the following transforms are legal for volatile loads.
8403 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008404
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008405 if (&LI.getParent()->front() != &LI) {
8406 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008407 // If the instruction immediately before this is a store to the same
8408 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008409 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8410 if (SI->getOperand(1) == LI.getOperand(0))
8411 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008412 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8413 if (LIB->getOperand(0) == LI.getOperand(0))
8414 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008415 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008416
8417 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8418 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8419 isa<UndefValue>(GEPI->getOperand(0))) {
8420 // Insert a new store to null instruction before the load to indicate
8421 // that this code is not reachable. We do this instead of inserting
8422 // an unreachable instruction directly because we cannot modify the
8423 // CFG.
8424 new StoreInst(UndefValue::get(LI.getType()),
8425 Constant::getNullValue(Op->getType()), &LI);
8426 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8427 }
8428
Chris Lattner81a7a232004-10-16 18:11:37 +00008429 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008430 // load null/undef -> undef
8431 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008432 // Insert a new store to null instruction before the load to indicate that
8433 // this code is not reachable. We do this instead of inserting an
8434 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008435 new StoreInst(UndefValue::get(LI.getType()),
8436 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008437 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008438 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008439
Chris Lattner81a7a232004-10-16 18:11:37 +00008440 // Instcombine load (constant global) into the value loaded.
8441 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008442 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008443 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008444
Chris Lattner81a7a232004-10-16 18:11:37 +00008445 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8447 if (CE->getOpcode() == Instruction::GetElementPtr) {
8448 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008449 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008450 if (Constant *V =
8451 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008452 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008453 if (CE->getOperand(0)->isNullValue()) {
8454 // Insert a new store to null instruction before the load to indicate
8455 // that this code is not reachable. We do this instead of inserting
8456 // an unreachable instruction directly because we cannot modify the
8457 // CFG.
8458 new StoreInst(UndefValue::get(LI.getType()),
8459 Constant::getNullValue(Op->getType()), &LI);
8460 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8461 }
8462
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008463 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008464 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8465 return Res;
8466 }
8467 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008468
Chris Lattnera9d84e32005-05-01 04:24:53 +00008469 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008470 // Change select and PHI nodes to select values instead of addresses: this
8471 // helps alias analysis out a lot, allows many others simplifications, and
8472 // exposes redundancy in the code.
8473 //
8474 // Note that we cannot do the transformation unless we know that the
8475 // introduced loads cannot trap! Something like this is valid as long as
8476 // the condition is always false: load (select bool %C, int* null, int* %G),
8477 // but it would not be valid if we transformed it to load from null
8478 // unconditionally.
8479 //
8480 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8481 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008482 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8483 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008484 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008485 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008486 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008487 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008488 return new SelectInst(SI->getCondition(), V1, V2);
8489 }
8490
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008491 // load (select (cond, null, P)) -> load P
8492 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8493 if (C->isNullValue()) {
8494 LI.setOperand(0, SI->getOperand(2));
8495 return &LI;
8496 }
8497
8498 // load (select (cond, P, null)) -> load P
8499 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8500 if (C->isNullValue()) {
8501 LI.setOperand(0, SI->getOperand(1));
8502 return &LI;
8503 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008504 }
8505 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008506 return 0;
8507}
8508
Reid Spencere928a152007-01-19 21:20:31 +00008509/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008510/// when possible.
8511static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8512 User *CI = cast<User>(SI.getOperand(1));
8513 Value *CastOp = CI->getOperand(0);
8514
8515 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8516 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8517 const Type *SrcPTy = SrcTy->getElementType();
8518
Reid Spencer31a4ef42007-01-22 05:51:25 +00008519 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008520 // If the source is an array, the code below will not succeed. Check to
8521 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8522 // constants.
8523 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8524 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8525 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008526 Value* Idxs[2];
8527 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8528 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008529 SrcTy = cast<PointerType>(CastOp->getType());
8530 SrcPTy = SrcTy->getElementType();
8531 }
8532
Reid Spencer9a4bed02007-01-20 23:35:48 +00008533 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8534 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8535 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008536
8537 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008538 // the same size. Instead of casting the pointer before
8539 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008540 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008541 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008542 Instruction::CastOps opcode = Instruction::BitCast;
8543 const Type* CastSrcTy = SIOp0->getType();
8544 const Type* CastDstTy = SrcPTy;
8545 if (isa<PointerType>(CastDstTy)) {
8546 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008547 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008548 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008549 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008550 opcode = Instruction::PtrToInt;
8551 }
8552 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008553 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008554 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008555 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008556 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8557 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008558 return new StoreInst(NewCast, CastOp);
8559 }
8560 }
8561 }
8562 return 0;
8563}
8564
Chris Lattner31f486c2005-01-31 05:36:43 +00008565Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8566 Value *Val = SI.getOperand(0);
8567 Value *Ptr = SI.getOperand(1);
8568
8569 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008570 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008571 ++NumCombined;
8572 return 0;
8573 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008574
8575 // If the RHS is an alloca with a single use, zapify the store, making the
8576 // alloca dead.
8577 if (Ptr->hasOneUse()) {
8578 if (isa<AllocaInst>(Ptr)) {
8579 EraseInstFromFunction(SI);
8580 ++NumCombined;
8581 return 0;
8582 }
8583
8584 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8585 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8586 GEP->getOperand(0)->hasOneUse()) {
8587 EraseInstFromFunction(SI);
8588 ++NumCombined;
8589 return 0;
8590 }
8591 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008592
Chris Lattner5997cf92006-02-08 03:25:32 +00008593 // Do really simple DSE, to catch cases where there are several consequtive
8594 // stores to the same location, separated by a few arithmetic operations. This
8595 // situation often occurs with bitfield accesses.
8596 BasicBlock::iterator BBI = &SI;
8597 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8598 --ScanInsts) {
8599 --BBI;
8600
8601 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8602 // Prev store isn't volatile, and stores to the same location?
8603 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8604 ++NumDeadStore;
8605 ++BBI;
8606 EraseInstFromFunction(*PrevSI);
8607 continue;
8608 }
8609 break;
8610 }
8611
Chris Lattnerdab43b22006-05-26 19:19:20 +00008612 // If this is a load, we have to stop. However, if the loaded value is from
8613 // the pointer we're loading and is producing the pointer we're storing,
8614 // then *this* store is dead (X = load P; store X -> P).
8615 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8616 if (LI == Val && LI->getOperand(0) == Ptr) {
8617 EraseInstFromFunction(SI);
8618 ++NumCombined;
8619 return 0;
8620 }
8621 // Otherwise, this is a load from some other location. Stores before it
8622 // may not be dead.
8623 break;
8624 }
8625
Chris Lattner5997cf92006-02-08 03:25:32 +00008626 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008627 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008628 break;
8629 }
8630
8631
8632 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008633
8634 // store X, null -> turns into 'unreachable' in SimplifyCFG
8635 if (isa<ConstantPointerNull>(Ptr)) {
8636 if (!isa<UndefValue>(Val)) {
8637 SI.setOperand(0, UndefValue::get(Val->getType()));
8638 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008639 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008640 ++NumCombined;
8641 }
8642 return 0; // Do not modify these!
8643 }
8644
8645 // store undef, Ptr -> noop
8646 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008647 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008648 ++NumCombined;
8649 return 0;
8650 }
8651
Chris Lattner72684fe2005-01-31 05:51:45 +00008652 // If the pointer destination is a cast, see if we can fold the cast into the
8653 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008654 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008655 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8656 return Res;
8657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008658 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008659 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8660 return Res;
8661
Chris Lattner219175c2005-09-12 23:23:25 +00008662
8663 // If this store is the last instruction in the basic block, and if the block
8664 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008665 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008666 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8667 if (BI->isUnconditional()) {
8668 // Check to see if the successor block has exactly two incoming edges. If
8669 // so, see if the other predecessor contains a store to the same location.
8670 // if so, insert a PHI node (if needed) and move the stores down.
8671 BasicBlock *Dest = BI->getSuccessor(0);
8672
8673 pred_iterator PI = pred_begin(Dest);
8674 BasicBlock *Other = 0;
8675 if (*PI != BI->getParent())
8676 Other = *PI;
8677 ++PI;
8678 if (PI != pred_end(Dest)) {
8679 if (*PI != BI->getParent())
8680 if (Other)
8681 Other = 0;
8682 else
8683 Other = *PI;
8684 if (++PI != pred_end(Dest))
8685 Other = 0;
8686 }
8687 if (Other) { // If only one other pred...
8688 BBI = Other->getTerminator();
8689 // Make sure this other block ends in an unconditional branch and that
8690 // there is an instruction before the branch.
8691 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8692 BBI != Other->begin()) {
8693 --BBI;
8694 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8695
8696 // If this instruction is a store to the same location.
8697 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8698 // Okay, we know we can perform this transformation. Insert a PHI
8699 // node now if we need it.
8700 Value *MergedVal = OtherStore->getOperand(0);
8701 if (MergedVal != SI.getOperand(0)) {
8702 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8703 PN->reserveOperandSpace(2);
8704 PN->addIncoming(SI.getOperand(0), SI.getParent());
8705 PN->addIncoming(OtherStore->getOperand(0), Other);
8706 MergedVal = InsertNewInstBefore(PN, Dest->front());
8707 }
8708
8709 // Advance to a place where it is safe to insert the new store and
8710 // insert it.
8711 BBI = Dest->begin();
8712 while (isa<PHINode>(BBI)) ++BBI;
8713 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8714 OtherStore->isVolatile()), *BBI);
8715
8716 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008717 EraseInstFromFunction(SI);
8718 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008719 ++NumCombined;
8720 return 0;
8721 }
8722 }
8723 }
8724 }
8725
Chris Lattner31f486c2005-01-31 05:36:43 +00008726 return 0;
8727}
8728
8729
Chris Lattner9eef8a72003-06-04 04:46:00 +00008730Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8731 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008732 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008733 BasicBlock *TrueDest;
8734 BasicBlock *FalseDest;
8735 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8736 !isa<Constant>(X)) {
8737 // Swap Destinations and condition...
8738 BI.setCondition(X);
8739 BI.setSuccessor(0, FalseDest);
8740 BI.setSuccessor(1, TrueDest);
8741 return &BI;
8742 }
8743
Reid Spencer266e42b2006-12-23 06:05:41 +00008744 // Cannonicalize fcmp_one -> fcmp_oeq
8745 FCmpInst::Predicate FPred; Value *Y;
8746 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8747 TrueDest, FalseDest)))
8748 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8749 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8750 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008751 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008752 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8753 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008754 // Swap Destinations and condition...
8755 BI.setCondition(NewSCC);
8756 BI.setSuccessor(0, FalseDest);
8757 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008758 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008759 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008760 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008761 return &BI;
8762 }
8763
8764 // Cannonicalize icmp_ne -> icmp_eq
8765 ICmpInst::Predicate IPred;
8766 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8767 TrueDest, FalseDest)))
8768 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8769 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8770 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8771 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008772 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008773 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8774 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008775 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008776 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008777 BI.setSuccessor(0, FalseDest);
8778 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008779 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008780 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008781 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008782 return &BI;
8783 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008784
Chris Lattner9eef8a72003-06-04 04:46:00 +00008785 return 0;
8786}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008787
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008788Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8789 Value *Cond = SI.getCondition();
8790 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8791 if (I->getOpcode() == Instruction::Add)
8792 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8793 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8794 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008795 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008796 AddRHS));
8797 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008798 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008799 return &SI;
8800 }
8801 }
8802 return 0;
8803}
8804
Chris Lattner6bc98652006-03-05 00:22:33 +00008805/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8806/// is to leave as a vector operation.
8807static bool CheapToScalarize(Value *V, bool isConstant) {
8808 if (isa<ConstantAggregateZero>(V))
8809 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008810 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008811 if (isConstant) return true;
8812 // If all elts are the same, we can extract.
8813 Constant *Op0 = C->getOperand(0);
8814 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8815 if (C->getOperand(i) != Op0)
8816 return false;
8817 return true;
8818 }
8819 Instruction *I = dyn_cast<Instruction>(V);
8820 if (!I) return false;
8821
8822 // Insert element gets simplified to the inserted element or is deleted if
8823 // this is constant idx extract element and its a constant idx insertelt.
8824 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8825 isa<ConstantInt>(I->getOperand(2)))
8826 return true;
8827 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8828 return true;
8829 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8830 if (BO->hasOneUse() &&
8831 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8832 CheapToScalarize(BO->getOperand(1), isConstant)))
8833 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008834 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8835 if (CI->hasOneUse() &&
8836 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8837 CheapToScalarize(CI->getOperand(1), isConstant)))
8838 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008839
8840 return false;
8841}
8842
Chris Lattner945e4372007-02-14 05:52:17 +00008843/// Read and decode a shufflevector mask.
8844///
8845/// It turns undef elements into values that are larger than the number of
8846/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008847static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8848 unsigned NElts = SVI->getType()->getNumElements();
8849 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8850 return std::vector<unsigned>(NElts, 0);
8851 if (isa<UndefValue>(SVI->getOperand(2)))
8852 return std::vector<unsigned>(NElts, 2*NElts);
8853
8854 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008855 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008856 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8857 if (isa<UndefValue>(CP->getOperand(i)))
8858 Result.push_back(NElts*2); // undef -> 8
8859 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008860 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008861 return Result;
8862}
8863
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008864/// FindScalarElement - Given a vector and an element number, see if the scalar
8865/// value is already around as a register, for example if it were inserted then
8866/// extracted from the vector.
8867static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008868 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8869 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008870 unsigned Width = PTy->getNumElements();
8871 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008872 return UndefValue::get(PTy->getElementType());
8873
8874 if (isa<UndefValue>(V))
8875 return UndefValue::get(PTy->getElementType());
8876 else if (isa<ConstantAggregateZero>(V))
8877 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008878 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008879 return CP->getOperand(EltNo);
8880 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8881 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008882 if (!isa<ConstantInt>(III->getOperand(2)))
8883 return 0;
8884 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008885
8886 // If this is an insert to the element we are looking for, return the
8887 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008888 if (EltNo == IIElt)
8889 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008890
8891 // Otherwise, the insertelement doesn't modify the value, recurse on its
8892 // vector input.
8893 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008894 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008895 unsigned InEl = getShuffleMask(SVI)[EltNo];
8896 if (InEl < Width)
8897 return FindScalarElement(SVI->getOperand(0), InEl);
8898 else if (InEl < Width*2)
8899 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8900 else
8901 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008902 }
8903
8904 // Otherwise, we don't know.
8905 return 0;
8906}
8907
Robert Bocchinoa8352962006-01-13 22:48:06 +00008908Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008909
Chris Lattner92346c32006-03-31 18:25:14 +00008910 // If packed val is undef, replace extract with scalar undef.
8911 if (isa<UndefValue>(EI.getOperand(0)))
8912 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8913
8914 // If packed val is constant 0, replace extract with scalar 0.
8915 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8916 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8917
Reid Spencerd84d35b2007-02-15 02:26:10 +00008918 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008919 // If packed val is constant with uniform operands, replace EI
8920 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008921 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008922 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008923 if (C->getOperand(i) != op0) {
8924 op0 = 0;
8925 break;
8926 }
8927 if (op0)
8928 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008929 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008930
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008931 // If extracting a specified index from the vector, see if we can recursively
8932 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008933 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008934 // This instruction only demands the single element from the input vector.
8935 // If the input vector has a single use, simplify it based on this use
8936 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008937 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008938 if (EI.getOperand(0)->hasOneUse()) {
8939 uint64_t UndefElts;
8940 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008941 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008942 UndefElts)) {
8943 EI.setOperand(0, V);
8944 return &EI;
8945 }
8946 }
8947
Reid Spencere0fc4df2006-10-20 07:07:24 +00008948 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008949 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008950 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008951
Chris Lattner83f65782006-05-25 22:53:38 +00008952 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008953 if (I->hasOneUse()) {
8954 // Push extractelement into predecessor operation if legal and
8955 // profitable to do so
8956 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008957 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8958 if (CheapToScalarize(BO, isConstantElt)) {
8959 ExtractElementInst *newEI0 =
8960 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8961 EI.getName()+".lhs");
8962 ExtractElementInst *newEI1 =
8963 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8964 EI.getName()+".rhs");
8965 InsertNewInstBefore(newEI0, EI);
8966 InsertNewInstBefore(newEI1, EI);
8967 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8968 }
Reid Spencerde46e482006-11-02 20:25:50 +00008969 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008970 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008971 PointerType::get(EI.getType()), EI);
8972 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008973 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008974 InsertNewInstBefore(GEP, EI);
8975 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008976 }
8977 }
8978 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8979 // Extracting the inserted element?
8980 if (IE->getOperand(2) == EI.getOperand(1))
8981 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8982 // If the inserted and extracted elements are constants, they must not
8983 // be the same value, extract from the pre-inserted value instead.
8984 if (isa<Constant>(IE->getOperand(2)) &&
8985 isa<Constant>(EI.getOperand(1))) {
8986 AddUsesToWorkList(EI);
8987 EI.setOperand(0, IE->getOperand(0));
8988 return &EI;
8989 }
8990 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8991 // If this is extracting an element from a shufflevector, figure out where
8992 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008993 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8994 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008995 Value *Src;
8996 if (SrcIdx < SVI->getType()->getNumElements())
8997 Src = SVI->getOperand(0);
8998 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8999 SrcIdx -= SVI->getType()->getNumElements();
9000 Src = SVI->getOperand(1);
9001 } else {
9002 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009003 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009004 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009005 }
9006 }
Chris Lattner83f65782006-05-25 22:53:38 +00009007 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009008 return 0;
9009}
9010
Chris Lattner90951862006-04-16 00:51:47 +00009011/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9012/// elements from either LHS or RHS, return the shuffle mask and true.
9013/// Otherwise, return false.
9014static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9015 std::vector<Constant*> &Mask) {
9016 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9017 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009018 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009019
9020 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009021 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009022 return true;
9023 } else if (V == LHS) {
9024 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009025 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009026 return true;
9027 } else if (V == RHS) {
9028 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009029 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009030 return true;
9031 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9032 // If this is an insert of an extract from some other vector, include it.
9033 Value *VecOp = IEI->getOperand(0);
9034 Value *ScalarOp = IEI->getOperand(1);
9035 Value *IdxOp = IEI->getOperand(2);
9036
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009037 if (!isa<ConstantInt>(IdxOp))
9038 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009039 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009040
9041 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9042 // Okay, we can handle this if the vector we are insertinting into is
9043 // transitively ok.
9044 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9045 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009046 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009047 return true;
9048 }
9049 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9050 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009051 EI->getOperand(0)->getType() == V->getType()) {
9052 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009053 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009054
9055 // This must be extracting from either LHS or RHS.
9056 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9057 // Okay, we can handle this if the vector we are insertinting into is
9058 // transitively ok.
9059 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9060 // If so, update the mask to reflect the inserted value.
9061 if (EI->getOperand(0) == LHS) {
9062 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009063 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009064 } else {
9065 assert(EI->getOperand(0) == RHS);
9066 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009067 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009068
9069 }
9070 return true;
9071 }
9072 }
9073 }
9074 }
9075 }
9076 // TODO: Handle shufflevector here!
9077
9078 return false;
9079}
9080
9081/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9082/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9083/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009084static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009085 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009086 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009087 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009088 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009089 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009090
9091 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009092 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009093 return V;
9094 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009095 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009096 return V;
9097 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9098 // If this is an insert of an extract from some other vector, include it.
9099 Value *VecOp = IEI->getOperand(0);
9100 Value *ScalarOp = IEI->getOperand(1);
9101 Value *IdxOp = IEI->getOperand(2);
9102
9103 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9104 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9105 EI->getOperand(0)->getType() == V->getType()) {
9106 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009107 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9108 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009109
9110 // Either the extracted from or inserted into vector must be RHSVec,
9111 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009112 if (EI->getOperand(0) == RHS || RHS == 0) {
9113 RHS = EI->getOperand(0);
9114 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009115 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009116 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009117 return V;
9118 }
9119
Chris Lattner90951862006-04-16 00:51:47 +00009120 if (VecOp == RHS) {
9121 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009122 // Everything but the extracted element is replaced with the RHS.
9123 for (unsigned i = 0; i != NumElts; ++i) {
9124 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009125 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009126 }
9127 return V;
9128 }
Chris Lattner90951862006-04-16 00:51:47 +00009129
9130 // If this insertelement is a chain that comes from exactly these two
9131 // vectors, return the vector and the effective shuffle.
9132 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9133 return EI->getOperand(0);
9134
Chris Lattner39fac442006-04-15 01:39:45 +00009135 }
9136 }
9137 }
Chris Lattner90951862006-04-16 00:51:47 +00009138 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009139
9140 // Otherwise, can't do anything fancy. Return an identity vector.
9141 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009142 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009143 return V;
9144}
9145
9146Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9147 Value *VecOp = IE.getOperand(0);
9148 Value *ScalarOp = IE.getOperand(1);
9149 Value *IdxOp = IE.getOperand(2);
9150
9151 // If the inserted element was extracted from some other vector, and if the
9152 // indexes are constant, try to turn this into a shufflevector operation.
9153 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9154 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9155 EI->getOperand(0)->getType() == IE.getType()) {
9156 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009157 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9158 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009159
9160 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9161 return ReplaceInstUsesWith(IE, VecOp);
9162
9163 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9164 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9165
9166 // If we are extracting a value from a vector, then inserting it right
9167 // back into the same place, just use the input vector.
9168 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9169 return ReplaceInstUsesWith(IE, VecOp);
9170
9171 // We could theoretically do this for ANY input. However, doing so could
9172 // turn chains of insertelement instructions into a chain of shufflevector
9173 // instructions, and right now we do not merge shufflevectors. As such,
9174 // only do this in a situation where it is clear that there is benefit.
9175 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9176 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9177 // the values of VecOp, except then one read from EIOp0.
9178 // Build a new shuffle mask.
9179 std::vector<Constant*> Mask;
9180 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009181 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009182 else {
9183 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009184 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009185 NumVectorElts));
9186 }
Reid Spencerc635f472006-12-31 05:48:39 +00009187 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009188 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009189 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009190 }
9191
9192 // If this insertelement isn't used by some other insertelement, turn it
9193 // (and any insertelements it points to), into one big shuffle.
9194 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9195 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009196 Value *RHS = 0;
9197 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9198 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9199 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009200 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009201 }
9202 }
9203 }
9204
9205 return 0;
9206}
9207
9208
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009209Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9210 Value *LHS = SVI.getOperand(0);
9211 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009212 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009213
9214 bool MadeChange = false;
9215
Chris Lattner2deeaea2006-10-05 06:55:50 +00009216 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009217 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009218 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9219
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009220 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009221 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009222 if (isa<UndefValue>(SVI.getOperand(1))) {
9223 // Scan to see if there are any references to the RHS. If so, replace them
9224 // with undef element refs and set MadeChange to true.
9225 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9226 if (Mask[i] >= e && Mask[i] != 2*e) {
9227 Mask[i] = 2*e;
9228 MadeChange = true;
9229 }
9230 }
9231
9232 if (MadeChange) {
9233 // Remap any references to RHS to use LHS.
9234 std::vector<Constant*> Elts;
9235 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9236 if (Mask[i] == 2*e)
9237 Elts.push_back(UndefValue::get(Type::Int32Ty));
9238 else
9239 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9240 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009241 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009242 }
9243 }
Chris Lattner39fac442006-04-15 01:39:45 +00009244
Chris Lattner12249be2006-05-25 23:48:38 +00009245 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9246 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9247 if (LHS == RHS || isa<UndefValue>(LHS)) {
9248 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009249 // shuffle(undef,undef,mask) -> undef.
9250 return ReplaceInstUsesWith(SVI, LHS);
9251 }
9252
Chris Lattner12249be2006-05-25 23:48:38 +00009253 // Remap any references to RHS to use LHS.
9254 std::vector<Constant*> Elts;
9255 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009256 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009257 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009258 else {
9259 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9260 (Mask[i] < e && isa<UndefValue>(LHS)))
9261 Mask[i] = 2*e; // Turn into undef.
9262 else
9263 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009264 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009265 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009266 }
Chris Lattner12249be2006-05-25 23:48:38 +00009267 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009268 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009269 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009270 LHS = SVI.getOperand(0);
9271 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009272 MadeChange = true;
9273 }
9274
Chris Lattner0e477162006-05-26 00:29:06 +00009275 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009276 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009277
Chris Lattner12249be2006-05-25 23:48:38 +00009278 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9279 if (Mask[i] >= e*2) continue; // Ignore undef values.
9280 // Is this an identity shuffle of the LHS value?
9281 isLHSID &= (Mask[i] == i);
9282
9283 // Is this an identity shuffle of the RHS value?
9284 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009285 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009286
Chris Lattner12249be2006-05-25 23:48:38 +00009287 // Eliminate identity shuffles.
9288 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9289 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009290
Chris Lattner0e477162006-05-26 00:29:06 +00009291 // If the LHS is a shufflevector itself, see if we can combine it with this
9292 // one without producing an unusual shuffle. Here we are really conservative:
9293 // we are absolutely afraid of producing a shuffle mask not in the input
9294 // program, because the code gen may not be smart enough to turn a merged
9295 // shuffle into two specific shuffles: it may produce worse code. As such,
9296 // we only merge two shuffles if the result is one of the two input shuffle
9297 // masks. In this case, merging the shuffles just removes one instruction,
9298 // which we know is safe. This is good for things like turning:
9299 // (splat(splat)) -> splat.
9300 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9301 if (isa<UndefValue>(RHS)) {
9302 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9303
9304 std::vector<unsigned> NewMask;
9305 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9306 if (Mask[i] >= 2*e)
9307 NewMask.push_back(2*e);
9308 else
9309 NewMask.push_back(LHSMask[Mask[i]]);
9310
9311 // If the result mask is equal to the src shuffle or this shuffle mask, do
9312 // the replacement.
9313 if (NewMask == LHSMask || NewMask == Mask) {
9314 std::vector<Constant*> Elts;
9315 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9316 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009317 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009318 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009319 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009320 }
9321 }
9322 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9323 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009324 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009325 }
9326 }
9327 }
Chris Lattner4284f642007-01-30 22:32:46 +00009328
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009329 return MadeChange ? &SVI : 0;
9330}
9331
9332
Robert Bocchinoa8352962006-01-13 22:48:06 +00009333
Chris Lattner39c98bb2004-12-08 23:43:58 +00009334
9335/// TryToSinkInstruction - Try to move the specified instruction from its
9336/// current block into the beginning of DestBlock, which can only happen if it's
9337/// safe to move the instruction past all of the instructions between it and the
9338/// end of its block.
9339static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9340 assert(I->hasOneUse() && "Invariants didn't hold!");
9341
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009342 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9343 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009344
Chris Lattner39c98bb2004-12-08 23:43:58 +00009345 // Do not sink alloca instructions out of the entry block.
9346 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9347 return false;
9348
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009349 // We can only sink load instructions if there is nothing between the load and
9350 // the end of block that could change the value.
9351 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009352 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9353 Scan != E; ++Scan)
9354 if (Scan->mayWriteToMemory())
9355 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009356 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009357
9358 BasicBlock::iterator InsertPos = DestBlock->begin();
9359 while (isa<PHINode>(InsertPos)) ++InsertPos;
9360
Chris Lattner9f269e42005-08-08 19:11:57 +00009361 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009362 ++NumSunkInst;
9363 return true;
9364}
9365
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009366
9367/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9368/// all reachable code to the worklist.
9369///
9370/// This has a couple of tricks to make the code faster and more powerful. In
9371/// particular, we constant fold and DCE instructions as we go, to avoid adding
9372/// them to the worklist (this significantly speeds up instcombine on code where
9373/// many instructions are dead or constant). Additionally, if we find a branch
9374/// whose condition is a known constant, we only visit the reachable successors.
9375///
9376static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009377 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009378 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009379 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009380 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009381 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009382
9383 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9384 Instruction *Inst = BBI++;
9385
9386 // DCE instruction if trivially dead.
9387 if (isInstructionTriviallyDead(Inst)) {
9388 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009389 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009390 Inst->eraseFromParent();
9391 continue;
9392 }
9393
9394 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009395 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009396 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009397 Inst->replaceAllUsesWith(C);
9398 ++NumConstProp;
9399 Inst->eraseFromParent();
9400 continue;
9401 }
9402
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009403 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009404 }
9405
9406 // Recursively visit successors. If this is a branch or switch on a constant,
9407 // only visit the reachable successor.
9408 TerminatorInst *TI = BB->getTerminator();
9409 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009410 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009411 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009412 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009413 return;
9414 }
9415 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9416 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9417 // See if this is an explicit destination.
9418 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9419 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009420 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009421 return;
9422 }
9423
9424 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009425 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009426 return;
9427 }
9428 }
9429
9430 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009431 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009432}
9433
Chris Lattner960a5432007-03-03 02:04:50 +00009434bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009435 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009436 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009437
9438 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9439 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009440
Chris Lattner4ed40f72005-07-07 20:40:38 +00009441 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009442 // Do a depth-first traversal of the function, populate the worklist with
9443 // the reachable instructions. Ignore blocks that are not reachable. Keep
9444 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009445 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009446 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009447
Chris Lattner4ed40f72005-07-07 20:40:38 +00009448 // Do a quick scan over the function. If we find any blocks that are
9449 // unreachable, remove any instructions inside of them. This prevents
9450 // the instcombine code from having to deal with some bad special cases.
9451 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9452 if (!Visited.count(BB)) {
9453 Instruction *Term = BB->getTerminator();
9454 while (Term != BB->begin()) { // Remove instrs bottom-up
9455 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009456
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009457 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009458 ++NumDeadInst;
9459
9460 if (!I->use_empty())
9461 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9462 I->eraseFromParent();
9463 }
9464 }
9465 }
Chris Lattnerca081252001-12-14 16:52:21 +00009466
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009467 while (!Worklist.empty()) {
9468 Instruction *I = RemoveOneFromWorkList();
9469 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009470
Chris Lattner1443bc52006-05-11 17:11:52 +00009471 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009472 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009473 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009474 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009475 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009476 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009477
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009478 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009479
9480 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009481 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009482 continue;
9483 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009484
Chris Lattner1443bc52006-05-11 17:11:52 +00009485 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009486 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009487 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009488
Chris Lattner1443bc52006-05-11 17:11:52 +00009489 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009490 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009491 ReplaceInstUsesWith(*I, C);
9492
Chris Lattner99f48c62002-09-02 04:59:56 +00009493 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009494 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009495 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009496 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009497 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009498
Chris Lattner39c98bb2004-12-08 23:43:58 +00009499 // See if we can trivially sink this instruction to a successor basic block.
9500 if (I->hasOneUse()) {
9501 BasicBlock *BB = I->getParent();
9502 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9503 if (UserParent != BB) {
9504 bool UserIsSuccessor = false;
9505 // See if the user is one of our successors.
9506 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9507 if (*SI == UserParent) {
9508 UserIsSuccessor = true;
9509 break;
9510 }
9511
9512 // If the user is one of our immediate successors, and if that successor
9513 // only has us as a predecessors (we'd have to split the critical edge
9514 // otherwise), we can keep going.
9515 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9516 next(pred_begin(UserParent)) == pred_end(UserParent))
9517 // Okay, the CFG is simple enough, try to sink this instruction.
9518 Changed |= TryToSinkInstruction(I, UserParent);
9519 }
9520 }
9521
Chris Lattnerca081252001-12-14 16:52:21 +00009522 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009523 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009524 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009525 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009526 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009527 DOUT << "IC: Old = " << *I
9528 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009529
Chris Lattner396dbfe2004-06-09 05:08:07 +00009530 // Everything uses the new instruction now.
9531 I->replaceAllUsesWith(Result);
9532
9533 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009534 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009535 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009536
Chris Lattner6e0123b2007-02-11 01:23:03 +00009537 // Move the name to the new instruction first.
9538 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009539
9540 // Insert the new instruction into the basic block...
9541 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009542 BasicBlock::iterator InsertPos = I;
9543
9544 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9545 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9546 ++InsertPos;
9547
9548 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009549
Chris Lattner63d75af2004-05-01 23:27:23 +00009550 // Make sure that we reprocess all operands now that we reduced their
9551 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009552 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009553
Chris Lattner396dbfe2004-06-09 05:08:07 +00009554 // Instructions can end up on the worklist more than once. Make sure
9555 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009556 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009557
9558 // Erase the old instruction.
9559 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009560 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009561 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009562
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009563 // If the instruction was modified, it's possible that it is now dead.
9564 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009565 if (isInstructionTriviallyDead(I)) {
9566 // Make sure we process all operands now that we are reducing their
9567 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009568 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009569
Chris Lattner63d75af2004-05-01 23:27:23 +00009570 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009571 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009572 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009573 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009574 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009575 AddToWorkList(I);
9576 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009577 }
Chris Lattner053c0932002-05-14 15:24:07 +00009578 }
Chris Lattner260ab202002-04-18 17:39:14 +00009579 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009580 }
9581 }
9582
Chris Lattner960a5432007-03-03 02:04:50 +00009583 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009584 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009585}
9586
Chris Lattner960a5432007-03-03 02:04:50 +00009587
9588bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009589 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9590
Chris Lattner960a5432007-03-03 02:04:50 +00009591 bool EverMadeChange = false;
9592
9593 // Iterate while there is work to do.
9594 unsigned Iteration = 0;
9595 while (DoOneIteration(F, Iteration++))
9596 EverMadeChange = true;
9597 return EverMadeChange;
9598}
9599
Brian Gaeke38b79e82004-07-27 17:43:21 +00009600FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009601 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009602}
Brian Gaeke960707c2003-11-11 22:41:34 +00009603