blob: 9d327c7883d3614d958dd9309540a3fadc4fca3c [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());
678 APInt NotIn(~SrcTy->getMask());
679 APInt NewBits = APInt::getAllOnesValue(BitWidth) &
680 NotIn.zext(BitWidth);
681
682 Mask &= ~NotIn;
683 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 // The top bits are known to be zero.
686 KnownZero |= NewBits;
687 return;
688 }
689 case Instruction::SExt: {
690 // Compute the bits in the result that are not present in the input.
691 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
692 APInt NotIn(~SrcTy->getMask());
693 APInt NewBits = APInt::getAllOnesValue(BitWidth) &
694 NotIn.zext(BitWidth);
695
696 Mask &= ~NotIn;
697 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
699
700 // If the sign bit of the input is known set or clear, then we know the
701 // top bits of the result.
702 APInt InSignBit(APInt::getSignedMinValue(SrcTy->getBitWidth()));
703 InSignBit.zextOrTrunc(BitWidth);
704 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
705 KnownZero |= NewBits;
706 KnownOne &= ~NewBits;
707 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
708 KnownOne |= NewBits;
709 KnownZero &= ~NewBits;
710 } else { // Input sign bit unknown
711 KnownZero &= ~NewBits;
712 KnownOne &= ~NewBits;
713 }
714 return;
715 }
716 case Instruction::Shl:
717 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
718 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
719 uint64_t ShiftAmt = SA->getZExtValue();
720 Mask = APIntOps::lshr(Mask, ShiftAmt);
721 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
722 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
723 KnownZero = APIntOps::shl(KnownZero, ShiftAmt);
724 KnownOne = APIntOps::shl(KnownOne, ShiftAmt);
725 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
726 return;
727 }
728 break;
729 case Instruction::LShr:
730 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
731 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732 // Compute the new bits that are at the top now.
733 uint64_t ShiftAmt = SA->getZExtValue();
734 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
735
736 // Unsigned shift right.
737 Mask = APIntOps::shl(Mask, ShiftAmt);
738 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
739 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
740 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
741 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
742 KnownZero |= HighBits; // high bits known zero.
743 return;
744 }
745 break;
746 case Instruction::AShr:
747 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
748 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
749 // Compute the new bits that are at the top now.
750 uint64_t ShiftAmt = SA->getZExtValue();
751 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
752
753 // Signed shift right.
754 Mask = APIntOps::shl(Mask, ShiftAmt);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
756 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
757 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
758 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
759
760 // Handle the sign bits and adjust to where it is now in the mask.
761 APInt SignBit = APInt::getSignedMinValue(BitWidth).lshr(ShiftAmt);
762
763 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
764 KnownZero |= HighBits;
765 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
766 KnownOne |= HighBits;
767 }
768 return;
769 }
770 break;
771 }
772}
773
774/// ComputeMaskedBits - Determine which of the bits specified in Mask are
775/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner4534dd592006-02-09 07:38:58 +0000776/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
777/// processing.
Reid Spenceraa696402007-03-08 01:46:38 +0000778static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner4534dd592006-02-09 07:38:58 +0000779 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000780 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
781 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000782 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000783 // optimized based on the contradictory assumption that it is non-zero.
784 // Because instcombine aggressively folds operations with undef args anyway,
785 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000786 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000787 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000788 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000789 KnownZero = ~KnownOne & Mask;
790 return;
791 }
792
793 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000794 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000795 return; // Limit search depth.
796
797 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000798 Instruction *I = dyn_cast<Instruction>(V);
799 if (!I) return;
800
Reid Spencera94d3942007-01-19 21:13:56 +0000801 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000802
Chris Lattner0157e7f2006-02-11 09:31:47 +0000803 switch (I->getOpcode()) {
804 case Instruction::And:
805 // If either the LHS or the RHS are Zero, the result is zero.
806 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
807 Mask &= ~KnownZero;
808 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
809 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
810 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
811
812 // Output known-1 bits are only known if set in both the LHS & RHS.
813 KnownOne &= KnownOne2;
814 // Output known-0 are known to be clear if zero in either the LHS | RHS.
815 KnownZero |= KnownZero2;
816 return;
817 case Instruction::Or:
818 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
819 Mask &= ~KnownOne;
820 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
821 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
822 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
823
824 // Output known-0 bits are only known if clear in both the LHS & RHS.
825 KnownZero &= KnownZero2;
826 // Output known-1 are known to be set if set in either the LHS | RHS.
827 KnownOne |= KnownOne2;
828 return;
829 case Instruction::Xor: {
830 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
831 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
832 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
833 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
834
835 // Output known-0 bits are known if clear or set in both the LHS & RHS.
836 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
837 // Output known-1 are known to be set if set in only one of the LHS, RHS.
838 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
839 KnownZero = KnownZeroOut;
840 return;
841 }
842 case Instruction::Select:
843 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
845 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
846 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
847
848 // Only known if known in both the LHS and RHS.
849 KnownOne &= KnownOne2;
850 KnownZero &= KnownZero2;
851 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000852 case Instruction::FPTrunc:
853 case Instruction::FPExt:
854 case Instruction::FPToUI:
855 case Instruction::FPToSI:
856 case Instruction::SIToFP:
857 case Instruction::PtrToInt:
858 case Instruction::UIToFP:
859 case Instruction::IntToPtr:
860 return; // Can't work with floating point or pointers
861 case Instruction::Trunc:
862 // All these have integer operands
863 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
864 return;
865 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000866 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000867 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000869 return;
870 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000871 break;
872 }
873 case Instruction::ZExt: {
874 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000875 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
876 uint64_t NotIn = ~SrcTy->getBitMask();
877 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000878
Reid Spencera94d3942007-01-19 21:13:56 +0000879 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000880 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
881 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
882 // The top bits are known to be zero.
883 KnownZero |= NewBits;
884 return;
885 }
886 case Instruction::SExt: {
887 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000888 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
889 uint64_t NotIn = ~SrcTy->getBitMask();
890 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000891
Reid Spencera94d3942007-01-19 21:13:56 +0000892 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000893 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000895
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000896 // If the sign bit of the input is known set or clear, then we know the
897 // top bits of the result.
898 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
899 if (KnownZero & InSignBit) { // Input sign bit known zero
900 KnownZero |= NewBits;
901 KnownOne &= ~NewBits;
902 } else if (KnownOne & InSignBit) { // Input sign bit known set
903 KnownOne |= NewBits;
904 KnownZero &= ~NewBits;
905 } else { // Input sign bit unknown
906 KnownZero &= ~NewBits;
907 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 }
909 return;
910 }
911 case Instruction::Shl:
912 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000913 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
914 uint64_t ShiftAmt = SA->getZExtValue();
915 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000916 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
917 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000918 KnownZero <<= ShiftAmt;
919 KnownOne <<= ShiftAmt;
920 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000921 return;
922 }
923 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000924 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000925 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000926 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000927 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000928 uint64_t ShiftAmt = SA->getZExtValue();
929 uint64_t HighBits = (1ULL << ShiftAmt)-1;
930 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000931
Reid Spencerfdff9382006-11-08 06:47:33 +0000932 // Unsigned shift right.
933 Mask <<= ShiftAmt;
934 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
935 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
936 KnownZero >>= ShiftAmt;
937 KnownOne >>= ShiftAmt;
938 KnownZero |= HighBits; // high bits known zero.
939 return;
940 }
941 break;
942 case Instruction::AShr:
943 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
944 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
945 // Compute the new bits that are at the top now.
946 uint64_t ShiftAmt = SA->getZExtValue();
947 uint64_t HighBits = (1ULL << ShiftAmt)-1;
948 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
949
950 // Signed shift right.
951 Mask <<= ShiftAmt;
952 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
953 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
954 KnownZero >>= ShiftAmt;
955 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000956
Reid Spencerfdff9382006-11-08 06:47:33 +0000957 // Handle the sign bits.
958 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
959 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000960
Reid Spencerfdff9382006-11-08 06:47:33 +0000961 if (KnownZero & SignBit) { // New bits are known zero.
962 KnownZero |= HighBits;
963 } else if (KnownOne & SignBit) { // New bits are known one.
964 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000965 }
966 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000967 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000968 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000969 }
Chris Lattner92a68652006-02-07 08:05:22 +0000970}
971
972/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
973/// this predicate to simplify operations downstream. Mask is known to be zero
974/// for bits that V cannot have.
975static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000976 uint64_t KnownZero, KnownOne;
977 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
978 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
979 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000980}
981
Reid Spencerbb5741f2007-03-08 01:52:58 +0000982/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
983/// this predicate to simplify operations downstream. Mask is known to be zero
984/// for bits that V cannot have.
985static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
986 APInt KnownZero(Mask), KnownOne(Mask);
987 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
988 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
989 return (KnownZero & Mask) == Mask;
990}
991
Chris Lattner0157e7f2006-02-11 09:31:47 +0000992/// ShrinkDemandedConstant - Check to see if the specified operand of the
993/// specified instruction is a constant integer. If so, check to see if there
994/// are any bits set in the constant that are not demanded. If so, shrink the
995/// constant and return true.
996static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
997 uint64_t Demanded) {
998 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
999 if (!OpC) return false;
1000
1001 // If there are no bits set that aren't demanded, nothing to do.
1002 if ((~Demanded & OpC->getZExtValue()) == 0)
1003 return false;
1004
1005 // This is producing any bits that are not needed, shrink the RHS.
1006 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001007 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001008 return true;
1009}
1010
Chris Lattneree0f2802006-02-12 02:07:56 +00001011// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1012// set of known zero and one bits, compute the maximum and minimum values that
1013// could have the specified known zero and known one bits, returning them in
1014// min/max.
1015static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1016 uint64_t KnownZero,
1017 uint64_t KnownOne,
1018 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001019 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001020 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1021
1022 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
1023
1024 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1025 // bit if it is unknown.
1026 Min = KnownOne;
1027 Max = KnownOne|UnknownBits;
1028
1029 if (SignBit & UnknownBits) { // Sign bit is unknown
1030 Min |= SignBit;
1031 Max &= ~SignBit;
1032 }
1033
1034 // Sign extend the min/max values.
1035 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
1036 Min = (Min << ShAmt) >> ShAmt;
1037 Max = (Max << ShAmt) >> ShAmt;
1038}
1039
1040// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1041// a set of known zero and one bits, compute the maximum and minimum values that
1042// could have the specified known zero and known one bits, returning them in
1043// min/max.
1044static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1045 uint64_t KnownZero,
1046 uint64_t KnownOne,
1047 uint64_t &Min,
1048 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +00001049 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +00001050 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
1051
1052 // The minimum value is when the unknown bits are all zeros.
1053 Min = KnownOne;
1054 // The maximum value is when the unknown bits are all ones.
1055 Max = KnownOne|UnknownBits;
1056}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001057
1058
1059/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1060/// DemandedMask bits of the result of V are ever used downstream. If we can
1061/// use this information to simplify V, do so and return true. Otherwise,
1062/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1063/// the expression (used to simplify the caller). The KnownZero/One bits may
1064/// only be accurate for those bits in the DemandedMask.
1065bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1066 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +00001067 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001068 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +00001069 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 // We know all of the bits for a constant!
1071 KnownOne = CI->getZExtValue() & DemandedMask;
1072 KnownZero = ~KnownOne & DemandedMask;
1073 return false;
1074 }
1075
1076 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001077 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001078 if (Depth != 0) { // Not at the root.
1079 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1080 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +00001081 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001082 }
Chris Lattner2590e512006-02-07 06:56:34 +00001083 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001084 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001085 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001086 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001087 if (V != UndefValue::get(VTy))
1088 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +00001089 return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001090 } else if (Depth == 6) { // Limit search depth.
1091 return false;
1092 }
1093
1094 Instruction *I = dyn_cast<Instruction>(V);
1095 if (!I) return false; // Only analyze instructions.
1096
Chris Lattnerab2f9132007-03-04 23:16:36 +00001097 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +00001098
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001099 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001100 switch (I->getOpcode()) {
1101 default: break;
1102 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001103 // If either the LHS or the RHS are Zero, the result is zero.
1104 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1105 KnownZero, KnownOne, Depth+1))
1106 return true;
1107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108
1109 // If something is known zero on the RHS, the bits aren't demanded on the
1110 // LHS.
1111 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1112 KnownZero2, KnownOne2, Depth+1))
1113 return true;
1114 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1115
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001116 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001117 // These bits cannot contribute to the result of the 'and'.
1118 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1119 return UpdateValueUsesWith(I, I->getOperand(0));
1120 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1121 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001122
1123 // If all of the demanded bits in the inputs are known zeros, return zero.
1124 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001125 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001126
Chris Lattner0157e7f2006-02-11 09:31:47 +00001127 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001128 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001129 return UpdateValueUsesWith(I, I);
1130
1131 // Output known-1 bits are only known if set in both the LHS & RHS.
1132 KnownOne &= KnownOne2;
1133 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1134 KnownZero |= KnownZero2;
1135 break;
1136 case Instruction::Or:
1137 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1138 KnownZero, KnownOne, Depth+1))
1139 return true;
1140 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1142 KnownZero2, KnownOne2, Depth+1))
1143 return true;
1144 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1145
1146 // If all of the demanded bits are known zero on one side, return the other.
1147 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +00001148 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001149 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +00001150 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001151 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001152
1153 // If all of the potentially set bits on one side are known to be set on
1154 // the other side, just use the 'other' side.
1155 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1156 (DemandedMask & (~KnownZero)))
1157 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +00001158 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1159 (DemandedMask & (~KnownZero2)))
1160 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001161
1162 // If the RHS is a constant, see if we can simplify it.
1163 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1164 return UpdateValueUsesWith(I, I);
1165
1166 // Output known-0 bits are only known if clear in both the LHS & RHS.
1167 KnownZero &= KnownZero2;
1168 // Output known-1 are known to be set if set in either the LHS | RHS.
1169 KnownOne |= KnownOne2;
1170 break;
1171 case Instruction::Xor: {
1172 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1173 KnownZero, KnownOne, Depth+1))
1174 return true;
1175 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1176 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1177 KnownZero2, KnownOne2, Depth+1))
1178 return true;
1179 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1180
1181 // If all of the demanded bits are known zero on one side, return the other.
1182 // These bits cannot contribute to the result of the 'xor'.
1183 if ((DemandedMask & KnownZero) == DemandedMask)
1184 return UpdateValueUsesWith(I, I->getOperand(0));
1185 if ((DemandedMask & KnownZero2) == DemandedMask)
1186 return UpdateValueUsesWith(I, I->getOperand(1));
1187
1188 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1189 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1190 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1191 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1192
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001193 // If all of the demanded bits are known to be zero on one side or the
1194 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001195 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001196 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1197 Instruction *Or =
1198 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1199 I->getName());
1200 InsertNewInstBefore(Or, *I);
1201 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001202 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001203
Chris Lattner5b2edb12006-02-12 08:02:11 +00001204 // If all of the demanded bits on one side are known, and all of the set
1205 // bits on that side are also known to be set on the other side, turn this
1206 // into an AND, as we know the bits will be cleared.
1207 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1208 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1209 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001210 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +00001211 Instruction *And =
1212 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1213 InsertNewInstBefore(And, *I);
1214 return UpdateValueUsesWith(I, And);
1215 }
1216 }
1217
Chris Lattner0157e7f2006-02-11 09:31:47 +00001218 // If the RHS is a constant, see if we can simplify it.
1219 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1220 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1221 return UpdateValueUsesWith(I, I);
1222
1223 KnownZero = KnownZeroOut;
1224 KnownOne = KnownOneOut;
1225 break;
1226 }
1227 case Instruction::Select:
1228 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1229 KnownZero, KnownOne, Depth+1))
1230 return true;
1231 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1232 KnownZero2, KnownOne2, Depth+1))
1233 return true;
1234 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1235 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1236
1237 // If the operands are constants, see if we can simplify them.
1238 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1239 return UpdateValueUsesWith(I, I);
1240 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1241 return UpdateValueUsesWith(I, I);
1242
1243 // Only known if known in both the LHS and RHS.
1244 KnownOne &= KnownOne2;
1245 KnownZero &= KnownZero2;
1246 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001247 case Instruction::Trunc:
1248 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1249 KnownZero, KnownOne, Depth+1))
1250 return true;
1251 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1252 break;
1253 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001254 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001255 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001256
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001257 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1258 KnownZero, KnownOne, Depth+1))
1259 return true;
1260 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1261 break;
1262 case Instruction::ZExt: {
1263 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001264 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1265 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001266 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001267
Reid Spencera94d3942007-01-19 21:13:56 +00001268 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001269 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1270 KnownZero, KnownOne, Depth+1))
1271 return true;
1272 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1273 // The top bits are known to be zero.
1274 KnownZero |= NewBits;
1275 break;
1276 }
1277 case Instruction::SExt: {
1278 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001279 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1280 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001281 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001282
1283 // Get the sign bit for the source type
1284 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001285 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001286
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001287 // If any of the sign extended bits are demanded, we know that the sign
1288 // bit is demanded.
1289 if (NewBits & DemandedMask)
1290 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001291
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001292 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1293 KnownZero, KnownOne, Depth+1))
1294 return true;
1295 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001296
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001297 // If the sign bit of the input is known set or clear, then we know the
1298 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001299
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001300 // If the input sign bit is known zero, or if the NewBits are not demanded
1301 // convert this into a zero extension.
1302 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1303 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001304 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001305 return UpdateValueUsesWith(I, NewCast);
1306 } else if (KnownOne & InSignBit) { // Input sign bit known set
1307 KnownOne |= NewBits;
1308 KnownZero &= ~NewBits;
1309 } else { // Input sign bit unknown
1310 KnownZero &= ~NewBits;
1311 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001312 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001313 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001314 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001315 case Instruction::Add:
1316 // If there is a constant on the RHS, there are a variety of xformations
1317 // we can do.
1318 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1319 // If null, this should be simplified elsewhere. Some of the xforms here
1320 // won't work if the RHS is zero.
1321 if (RHS->isNullValue())
1322 break;
1323
1324 // Figure out what the input bits are. If the top bits of the and result
1325 // are not demanded, then the add doesn't demand them from its input
1326 // either.
1327
1328 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001329 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001330 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1331
1332 // If the top bit of the output is demanded, demand everything from the
1333 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001334 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001335
1336 // Find information about known zero/one bits in the input.
1337 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1338 KnownZero2, KnownOne2, Depth+1))
1339 return true;
1340
1341 // If the RHS of the add has bits set that can't affect the input, reduce
1342 // the constant.
1343 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1344 return UpdateValueUsesWith(I, I);
1345
1346 // Avoid excess work.
1347 if (KnownZero2 == 0 && KnownOne2 == 0)
1348 break;
1349
1350 // Turn it into OR if input bits are zero.
1351 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1352 Instruction *Or =
1353 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1354 I->getName());
1355 InsertNewInstBefore(Or, *I);
1356 return UpdateValueUsesWith(I, Or);
1357 }
1358
1359 // We can say something about the output known-zero and known-one bits,
1360 // depending on potential carries from the input constant and the
1361 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1362 // bits set and the RHS constant is 0x01001, then we know we have a known
1363 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1364
1365 // To compute this, we first compute the potential carry bits. These are
1366 // the bits which may be modified. I'm not aware of a better way to do
1367 // this scan.
1368 uint64_t RHSVal = RHS->getZExtValue();
1369
1370 bool CarryIn = false;
1371 uint64_t CarryBits = 0;
1372 uint64_t CurBit = 1;
1373 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1374 // Record the current carry in.
1375 if (CarryIn) CarryBits |= CurBit;
1376
1377 bool CarryOut;
1378
1379 // This bit has a carry out unless it is "zero + zero" or
1380 // "zero + anything" with no carry in.
1381 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1382 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1383 } else if (!CarryIn &&
1384 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1385 CarryOut = false; // 0 + anything has no carry out if no carry in.
1386 } else {
1387 // Otherwise, we have to assume we have a carry out.
1388 CarryOut = true;
1389 }
1390
1391 // This stage's carry out becomes the next stage's carry-in.
1392 CarryIn = CarryOut;
1393 }
1394
1395 // Now that we know which bits have carries, compute the known-1/0 sets.
1396
1397 // Bits are known one if they are known zero in one operand and one in the
1398 // other, and there is no input carry.
1399 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1400
1401 // Bits are known zero if they are known zero in both operands and there
1402 // is no input carry.
1403 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner5fdded12007-03-05 00:02:29 +00001404 } else {
1405 // If the high-bits of this ADD are not demanded, then it does not demand
1406 // the high bits of its LHS or RHS.
1407 if ((DemandedMask & VTy->getSignBit()) == 0) {
1408 // Right fill the mask of bits for this ADD to demand the most
1409 // significant bit and all those below it.
1410 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1411 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1412 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1413 KnownZero2, KnownOne2, Depth+1))
1414 return true;
1415 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1416 KnownZero2, KnownOne2, Depth+1))
1417 return true;
1418 }
1419 }
1420 break;
1421 case Instruction::Sub:
1422 // If the high-bits of this SUB are not demanded, then it does not demand
1423 // the high bits of its LHS or RHS.
1424 if ((DemandedMask & VTy->getSignBit()) == 0) {
1425 // Right fill the mask of bits for this SUB to demand the most
1426 // significant bit and all those below it.
1427 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1428 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1429 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1430 KnownZero2, KnownOne2, Depth+1))
1431 return true;
1432 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1433 KnownZero2, KnownOne2, Depth+1))
1434 return true;
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001435 }
1436 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001437 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001438 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1439 uint64_t ShiftAmt = SA->getZExtValue();
1440 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001441 KnownZero, KnownOne, Depth+1))
1442 return true;
1443 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001444 KnownZero <<= ShiftAmt;
1445 KnownOne <<= ShiftAmt;
1446 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001447 }
Chris Lattner2590e512006-02-07 06:56:34 +00001448 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001449 case Instruction::LShr:
1450 // For a logical shift right
1451 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1452 unsigned ShiftAmt = SA->getZExtValue();
1453
1454 // Compute the new bits that are at the top now.
1455 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001456 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1457 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001458 // Unsigned shift right.
1459 if (SimplifyDemandedBits(I->getOperand(0),
1460 (DemandedMask << ShiftAmt) & TypeMask,
1461 KnownZero, KnownOne, Depth+1))
1462 return true;
1463 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1464 KnownZero &= TypeMask;
1465 KnownOne &= TypeMask;
1466 KnownZero >>= ShiftAmt;
1467 KnownOne >>= ShiftAmt;
1468 KnownZero |= HighBits; // high bits known zero.
1469 }
1470 break;
1471 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001472 // If this is an arithmetic shift right and only the low-bit is set, we can
1473 // always convert this into a logical shr, even if the shift amount is
1474 // variable. The low bit of the shift cannot be an input sign bit unless
1475 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001476 if (DemandedMask == 1) {
1477 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001478 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001479 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001480 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001481 return UpdateValueUsesWith(I, NewVal);
1482 }
1483
Reid Spencere0fc4df2006-10-20 07:07:24 +00001484 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1485 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001486
1487 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001488 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001489 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1490 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001491 // Signed shift right.
1492 if (SimplifyDemandedBits(I->getOperand(0),
1493 (DemandedMask << ShiftAmt) & TypeMask,
1494 KnownZero, KnownOne, Depth+1))
1495 return true;
1496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1497 KnownZero &= TypeMask;
1498 KnownOne &= TypeMask;
1499 KnownZero >>= ShiftAmt;
1500 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001501
Reid Spencerfdff9382006-11-08 06:47:33 +00001502 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001503 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001504 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001505
Reid Spencerfdff9382006-11-08 06:47:33 +00001506 // If the input sign bit is known to be zero, or if none of the top bits
1507 // are demanded, turn this into an unsigned shift right.
1508 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1509 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001510 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001511 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001512 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1513 return UpdateValueUsesWith(I, NewVal);
1514 } else if (KnownOne & SignBit) { // New bits are known one.
1515 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001516 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001517 }
Chris Lattner2590e512006-02-07 06:56:34 +00001518 break;
1519 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001520
1521 // If the client is only demanding bits that we know, return the known
1522 // constant.
1523 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001524 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001525 return false;
1526}
1527
Chris Lattner2deeaea2006-10-05 06:55:50 +00001528
1529/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1530/// 64 or fewer elements. DemandedElts contains the set of elements that are
1531/// actually used by the caller. This method analyzes which elements of the
1532/// operand are undef and returns that information in UndefElts.
1533///
1534/// If the information about demanded elements can be used to simplify the
1535/// operation, the operation is simplified, then the resultant value is
1536/// returned. This returns null if no change was made.
1537Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1538 uint64_t &UndefElts,
1539 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001540 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001541 assert(VWidth <= 64 && "Vector too wide to analyze!");
1542 uint64_t EltMask = ~0ULL >> (64-VWidth);
1543 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1544 "Invalid DemandedElts!");
1545
1546 if (isa<UndefValue>(V)) {
1547 // If the entire vector is undefined, just return this info.
1548 UndefElts = EltMask;
1549 return 0;
1550 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1551 UndefElts = EltMask;
1552 return UndefValue::get(V->getType());
1553 }
1554
1555 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001556 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1557 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001558 Constant *Undef = UndefValue::get(EltTy);
1559
1560 std::vector<Constant*> Elts;
1561 for (unsigned i = 0; i != VWidth; ++i)
1562 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1563 Elts.push_back(Undef);
1564 UndefElts |= (1ULL << i);
1565 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1566 Elts.push_back(Undef);
1567 UndefElts |= (1ULL << i);
1568 } else { // Otherwise, defined.
1569 Elts.push_back(CP->getOperand(i));
1570 }
1571
1572 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001573 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001574 return NewCP != CP ? NewCP : 0;
1575 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001576 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001577 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001578 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001579 Constant *Zero = Constant::getNullValue(EltTy);
1580 Constant *Undef = UndefValue::get(EltTy);
1581 std::vector<Constant*> Elts;
1582 for (unsigned i = 0; i != VWidth; ++i)
1583 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1584 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001585 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001586 }
1587
1588 if (!V->hasOneUse()) { // Other users may use these bits.
1589 if (Depth != 0) { // Not at the root.
1590 // TODO: Just compute the UndefElts information recursively.
1591 return false;
1592 }
1593 return false;
1594 } else if (Depth == 10) { // Limit search depth.
1595 return false;
1596 }
1597
1598 Instruction *I = dyn_cast<Instruction>(V);
1599 if (!I) return false; // Only analyze instructions.
1600
1601 bool MadeChange = false;
1602 uint64_t UndefElts2;
1603 Value *TmpV;
1604 switch (I->getOpcode()) {
1605 default: break;
1606
1607 case Instruction::InsertElement: {
1608 // If this is a variable index, we don't know which element it overwrites.
1609 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001610 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001611 if (Idx == 0) {
1612 // Note that we can't propagate undef elt info, because we don't know
1613 // which elt is getting updated.
1614 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1615 UndefElts2, Depth+1);
1616 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1617 break;
1618 }
1619
1620 // If this is inserting an element that isn't demanded, remove this
1621 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001622 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001623 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1624 return AddSoonDeadInstToWorklist(*I, 0);
1625
1626 // Otherwise, the element inserted overwrites whatever was there, so the
1627 // input demanded set is simpler than the output set.
1628 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1629 DemandedElts & ~(1ULL << IdxNo),
1630 UndefElts, Depth+1);
1631 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1632
1633 // The inserted element is defined.
1634 UndefElts |= 1ULL << IdxNo;
1635 break;
1636 }
1637
1638 case Instruction::And:
1639 case Instruction::Or:
1640 case Instruction::Xor:
1641 case Instruction::Add:
1642 case Instruction::Sub:
1643 case Instruction::Mul:
1644 // div/rem demand all inputs, because they don't want divide by zero.
1645 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1646 UndefElts, Depth+1);
1647 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1648 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1649 UndefElts2, Depth+1);
1650 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1651
1652 // Output elements are undefined if both are undefined. Consider things
1653 // like undef&0. The result is known zero, not undef.
1654 UndefElts &= UndefElts2;
1655 break;
1656
1657 case Instruction::Call: {
1658 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1659 if (!II) break;
1660 switch (II->getIntrinsicID()) {
1661 default: break;
1662
1663 // Binary vector operations that work column-wise. A dest element is a
1664 // function of the corresponding input elements from the two inputs.
1665 case Intrinsic::x86_sse_sub_ss:
1666 case Intrinsic::x86_sse_mul_ss:
1667 case Intrinsic::x86_sse_min_ss:
1668 case Intrinsic::x86_sse_max_ss:
1669 case Intrinsic::x86_sse2_sub_sd:
1670 case Intrinsic::x86_sse2_mul_sd:
1671 case Intrinsic::x86_sse2_min_sd:
1672 case Intrinsic::x86_sse2_max_sd:
1673 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1674 UndefElts, Depth+1);
1675 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1676 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1677 UndefElts2, Depth+1);
1678 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1679
1680 // If only the low elt is demanded and this is a scalarizable intrinsic,
1681 // scalarize it now.
1682 if (DemandedElts == 1) {
1683 switch (II->getIntrinsicID()) {
1684 default: break;
1685 case Intrinsic::x86_sse_sub_ss:
1686 case Intrinsic::x86_sse_mul_ss:
1687 case Intrinsic::x86_sse2_sub_sd:
1688 case Intrinsic::x86_sse2_mul_sd:
1689 // TODO: Lower MIN/MAX/ABS/etc
1690 Value *LHS = II->getOperand(1);
1691 Value *RHS = II->getOperand(2);
1692 // Extract the element as scalars.
1693 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1694 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1695
1696 switch (II->getIntrinsicID()) {
1697 default: assert(0 && "Case stmts out of sync!");
1698 case Intrinsic::x86_sse_sub_ss:
1699 case Intrinsic::x86_sse2_sub_sd:
1700 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1701 II->getName()), *II);
1702 break;
1703 case Intrinsic::x86_sse_mul_ss:
1704 case Intrinsic::x86_sse2_mul_sd:
1705 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1706 II->getName()), *II);
1707 break;
1708 }
1709
1710 Instruction *New =
1711 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1712 II->getName());
1713 InsertNewInstBefore(New, *II);
1714 AddSoonDeadInstToWorklist(*II, 0);
1715 return New;
1716 }
1717 }
1718
1719 // Output elements are undefined if both are undefined. Consider things
1720 // like undef&0. The result is known zero, not undef.
1721 UndefElts &= UndefElts2;
1722 break;
1723 }
1724 break;
1725 }
1726 }
1727 return MadeChange ? I : 0;
1728}
1729
Reid Spencer266e42b2006-12-23 06:05:41 +00001730/// @returns true if the specified compare instruction is
1731/// true when both operands are equal...
1732/// @brief Determine if the ICmpInst returns true if both operands are equal
1733static bool isTrueWhenEqual(ICmpInst &ICI) {
1734 ICmpInst::Predicate pred = ICI.getPredicate();
1735 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1736 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1737 pred == ICmpInst::ICMP_SLE;
1738}
1739
Chris Lattnerb8b97502003-08-13 19:01:45 +00001740/// AssociativeOpt - Perform an optimization on an associative operator. This
1741/// function is designed to check a chain of associative operators for a
1742/// potential to apply a certain optimization. Since the optimization may be
1743/// applicable if the expression was reassociated, this checks the chain, then
1744/// reassociates the expression as necessary to expose the optimization
1745/// opportunity. This makes use of a special Functor, which must define
1746/// 'shouldApply' and 'apply' methods.
1747///
1748template<typename Functor>
1749Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1750 unsigned Opcode = Root.getOpcode();
1751 Value *LHS = Root.getOperand(0);
1752
1753 // Quick check, see if the immediate LHS matches...
1754 if (F.shouldApply(LHS))
1755 return F.apply(Root);
1756
1757 // Otherwise, if the LHS is not of the same opcode as the root, return.
1758 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001759 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001760 // Should we apply this transform to the RHS?
1761 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1762
1763 // If not to the RHS, check to see if we should apply to the LHS...
1764 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1765 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1766 ShouldApply = true;
1767 }
1768
1769 // If the functor wants to apply the optimization to the RHS of LHSI,
1770 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1771 if (ShouldApply) {
1772 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001773
Chris Lattnerb8b97502003-08-13 19:01:45 +00001774 // Now all of the instructions are in the current basic block, go ahead
1775 // and perform the reassociation.
1776 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1777
1778 // First move the selected RHS to the LHS of the root...
1779 Root.setOperand(0, LHSI->getOperand(1));
1780
1781 // Make what used to be the LHS of the root be the user of the root...
1782 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001783 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001784 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1785 return 0;
1786 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001787 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001788 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001789 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1790 BasicBlock::iterator ARI = &Root; ++ARI;
1791 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1792 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001793
1794 // Now propagate the ExtraOperand down the chain of instructions until we
1795 // get to LHSI.
1796 while (TmpLHSI != LHSI) {
1797 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001798 // Move the instruction to immediately before the chain we are
1799 // constructing to avoid breaking dominance properties.
1800 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1801 BB->getInstList().insert(ARI, NextLHSI);
1802 ARI = NextLHSI;
1803
Chris Lattnerb8b97502003-08-13 19:01:45 +00001804 Value *NextOp = NextLHSI->getOperand(1);
1805 NextLHSI->setOperand(1, ExtraOperand);
1806 TmpLHSI = NextLHSI;
1807 ExtraOperand = NextOp;
1808 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001809
Chris Lattnerb8b97502003-08-13 19:01:45 +00001810 // Now that the instructions are reassociated, have the functor perform
1811 // the transformation...
1812 return F.apply(Root);
1813 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001814
Chris Lattnerb8b97502003-08-13 19:01:45 +00001815 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1816 }
1817 return 0;
1818}
1819
1820
1821// AddRHS - Implements: X + X --> X << 1
1822struct AddRHS {
1823 Value *RHS;
1824 AddRHS(Value *rhs) : RHS(rhs) {}
1825 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1826 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001827 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001828 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001829 }
1830};
1831
1832// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1833// iff C1&C2 == 0
1834struct AddMaskingAnd {
1835 Constant *C2;
1836 AddMaskingAnd(Constant *c) : C2(c) {}
1837 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001838 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001839 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001840 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001841 }
1842 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001843 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001844 }
1845};
1846
Chris Lattner86102b82005-01-01 16:22:27 +00001847static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001848 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001849 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001850 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001851 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001852
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001853 return IC->InsertNewInstBefore(CastInst::create(
1854 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001855 }
1856
Chris Lattner183b3362004-04-09 19:05:30 +00001857 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001858 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1859 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001860
Chris Lattner183b3362004-04-09 19:05:30 +00001861 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1862 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001863 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1864 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001865 }
1866
1867 Value *Op0 = SO, *Op1 = ConstOperand;
1868 if (!ConstIsRHS)
1869 std::swap(Op0, Op1);
1870 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001871 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1872 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001873 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1874 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1875 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001876 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001877 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001878 abort();
1879 }
Chris Lattner86102b82005-01-01 16:22:27 +00001880 return IC->InsertNewInstBefore(New, I);
1881}
1882
1883// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1884// constant as the other operand, try to fold the binary operator into the
1885// select arguments. This also works for Cast instructions, which obviously do
1886// not have a second operand.
1887static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1888 InstCombiner *IC) {
1889 // Don't modify shared select instructions
1890 if (!SI->hasOneUse()) return 0;
1891 Value *TV = SI->getOperand(1);
1892 Value *FV = SI->getOperand(2);
1893
1894 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001895 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001896 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001897
Chris Lattner86102b82005-01-01 16:22:27 +00001898 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1899 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1900
1901 return new SelectInst(SI->getCondition(), SelectTrueVal,
1902 SelectFalseVal);
1903 }
1904 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001905}
1906
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001907
1908/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1909/// node as operand #0, see if we can fold the instruction into the PHI (which
1910/// is only possible if all operands to the PHI are constants).
1911Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1912 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001913 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001914 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001915
Chris Lattner04689872006-09-09 22:02:56 +00001916 // Check to see if all of the operands of the PHI are constants. If there is
1917 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001918 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001919 BasicBlock *NonConstBB = 0;
1920 for (unsigned i = 0; i != NumPHIValues; ++i)
1921 if (!isa<Constant>(PN->getIncomingValue(i))) {
1922 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001923 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001924 NonConstBB = PN->getIncomingBlock(i);
1925
1926 // If the incoming non-constant value is in I's block, we have an infinite
1927 // loop.
1928 if (NonConstBB == I.getParent())
1929 return 0;
1930 }
1931
1932 // If there is exactly one non-constant value, we can insert a copy of the
1933 // operation in that block. However, if this is a critical edge, we would be
1934 // inserting the computation one some other paths (e.g. inside a loop). Only
1935 // do this if the pred block is unconditionally branching into the phi block.
1936 if (NonConstBB) {
1937 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1938 if (!BI || !BI->isUnconditional()) return 0;
1939 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001940
1941 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001942 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001943 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001944 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001945 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001946
1947 // Next, add all of the operands to the PHI.
1948 if (I.getNumOperands() == 2) {
1949 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001950 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001951 Value *InV;
1952 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001953 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1954 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1955 else
1956 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001957 } else {
1958 assert(PN->getIncomingBlock(i) == NonConstBB);
1959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1960 InV = BinaryOperator::create(BO->getOpcode(),
1961 PN->getIncomingValue(i), C, "phitmp",
1962 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001963 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1964 InV = CmpInst::create(CI->getOpcode(),
1965 CI->getPredicate(),
1966 PN->getIncomingValue(i), C, "phitmp",
1967 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001968 else
1969 assert(0 && "Unknown binop!");
1970
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001971 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001972 }
1973 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001974 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001975 } else {
1976 CastInst *CI = cast<CastInst>(&I);
1977 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001978 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001979 Value *InV;
1980 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001981 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001982 } else {
1983 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001984 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1985 I.getType(), "phitmp",
1986 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001987 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001988 }
1989 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001990 }
1991 }
1992 return ReplaceInstUsesWith(I, NewPN);
1993}
1994
Chris Lattner113f4f42002-06-25 16:13:24 +00001995Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001996 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001997 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001998
Chris Lattnercf4a9962004-04-10 22:01:55 +00001999 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002000 // X + undef -> undef
2001 if (isa<UndefValue>(RHS))
2002 return ReplaceInstUsesWith(I, RHS);
2003
Chris Lattnercf4a9962004-04-10 22:01:55 +00002004 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002005 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002006 if (RHSC->isNullValue())
2007 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002008 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2009 if (CFP->isExactlyValue(-0.0))
2010 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002011 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002012
Chris Lattnercf4a9962004-04-10 22:01:55 +00002013 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002014 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00002015 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00002016 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002017 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002018
2019 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2020 // (X & 254)+1 -> (X&254)|1
2021 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002022 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00002023 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002024 KnownZero, KnownOne))
2025 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00002026 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002027
2028 if (isa<PHINode>(LHS))
2029 if (Instruction *NV = FoldOpIntoPhi(I))
2030 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002031
Chris Lattner330628a2006-01-06 17:59:59 +00002032 ConstantInt *XorRHS = 0;
2033 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002034 if (isa<ConstantInt>(RHSC) &&
2035 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002036 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2037 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2038 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2039
2040 uint64_t C0080Val = 1ULL << 31;
2041 int64_t CFF80Val = -C0080Val;
2042 unsigned Size = 32;
2043 do {
2044 if (TySizeBits > Size) {
2045 bool Found = false;
2046 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2047 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2048 if (RHSSExt == CFF80Val) {
2049 if (XorRHS->getZExtValue() == C0080Val)
2050 Found = true;
2051 } else if (RHSZExt == C0080Val) {
2052 if (XorRHS->getSExtValue() == CFF80Val)
2053 Found = true;
2054 }
2055 if (Found) {
2056 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002057 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002058 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00002059 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002060 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002061 Size = 0; // Not a sign ext, but can't be any others either.
2062 goto FoundSExt;
2063 }
2064 }
2065 Size >>= 1;
2066 C0080Val >>= Size;
2067 CFF80Val >>= Size;
2068 } while (Size >= 8);
2069
2070FoundSExt:
2071 const Type *MiddleType = 0;
2072 switch (Size) {
2073 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00002074 case 32: MiddleType = Type::Int32Ty; break;
2075 case 16: MiddleType = Type::Int16Ty; break;
2076 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002077 }
2078 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002079 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002080 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002081 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002082 }
2083 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002084 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002085
Chris Lattnerb8b97502003-08-13 19:01:45 +00002086 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002087 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002088 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002089
2090 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2091 if (RHSI->getOpcode() == Instruction::Sub)
2092 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2093 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2094 }
2095 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2096 if (LHSI->getOpcode() == Instruction::Sub)
2097 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2098 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2099 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002100 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002101
Chris Lattner147e9752002-05-08 22:46:53 +00002102 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002103 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002104 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002105
2106 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002107 if (!isa<Constant>(RHS))
2108 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002109 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002110
Misha Brukmanb1c93172005-04-21 23:48:37 +00002111
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002112 ConstantInt *C2;
2113 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2114 if (X == RHS) // X*C + X --> X * (C+1)
2115 return BinaryOperator::createMul(RHS, AddOne(C2));
2116
2117 // X*C1 + X*C2 --> X * (C1+C2)
2118 ConstantInt *C1;
2119 if (X == dyn_castFoldableMul(RHS, C1))
2120 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002121 }
2122
2123 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002124 if (dyn_castFoldableMul(RHS, C2) == LHS)
2125 return BinaryOperator::createMul(LHS, AddOne(C2));
2126
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002127 // X + ~X --> -1 since ~X = -X-1
2128 if (dyn_castNotVal(LHS) == RHS ||
2129 dyn_castNotVal(RHS) == LHS)
2130 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2131
Chris Lattner57c8d992003-02-18 19:57:07 +00002132
Chris Lattnerb8b97502003-08-13 19:01:45 +00002133 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002134 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002135 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2136 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002137
Chris Lattnerb9cde762003-10-02 15:11:26 +00002138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002139 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002140 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2141 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2142 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00002143 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00002144
Chris Lattnerbff91d92004-10-08 05:07:56 +00002145 // (X & FF00) + xx00 -> (X+xx00) & FF00
2146 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2147 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2148 if (Anded == CRHS) {
2149 // See if all bits from the first bit set in the Add RHS up are included
2150 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002151 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002152
2153 // Form a mask of all bits from the lowest bit added through the top.
2154 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00002155 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002156
2157 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002158 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002159
Chris Lattnerbff91d92004-10-08 05:07:56 +00002160 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2161 // Okay, the xform is safe. Insert the new add pronto.
2162 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2163 LHS->getName()), I);
2164 return BinaryOperator::createAnd(NewAdd, C2);
2165 }
2166 }
2167 }
2168
Chris Lattnerd4252a72004-07-30 07:50:03 +00002169 // Try to fold constant add into select arguments.
2170 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002171 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002172 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002173 }
2174
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002175 // add (cast *A to intptrtype) B ->
2176 // cast (GEP (cast *A to sbyte*) B) ->
2177 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002178 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002179 CastInst *CI = dyn_cast<CastInst>(LHS);
2180 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002181 if (!CI) {
2182 CI = dyn_cast<CastInst>(RHS);
2183 Other = LHS;
2184 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002185 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002186 (CI->getType()->getPrimitiveSizeInBits() ==
2187 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002188 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002189 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002190 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002191 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002192 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002193 }
2194 }
2195
Chris Lattner113f4f42002-06-25 16:13:24 +00002196 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002197}
2198
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002199// isSignBit - Return true if the value represented by the constant only has the
2200// highest order bit set.
2201static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002202 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00002203 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002204}
2205
Chris Lattner113f4f42002-06-25 16:13:24 +00002206Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002208
Chris Lattnere6794492002-08-12 21:17:25 +00002209 if (Op0 == Op1) // sub X, X -> 0
2210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002211
Chris Lattnere6794492002-08-12 21:17:25 +00002212 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002213 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002214 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002215
Chris Lattner81a7a232004-10-16 18:11:37 +00002216 if (isa<UndefValue>(Op0))
2217 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2218 if (isa<UndefValue>(Op1))
2219 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2220
Chris Lattner8f2f5982003-11-05 01:06:05 +00002221 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2222 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002223 if (C->isAllOnesValue())
2224 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002225
Chris Lattner8f2f5982003-11-05 01:06:05 +00002226 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002227 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002228 if (match(Op1, m_Not(m_Value(X))))
2229 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002230 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002231 // -(X >>u 31) -> (X >>s 31)
2232 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002233 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002234 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002235 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002236 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002237 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002238 if (CU->getZExtValue() ==
2239 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002240 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002241 return BinaryOperator::create(Instruction::AShr,
2242 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002243 }
2244 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002245 }
2246 else if (SI->getOpcode() == Instruction::AShr) {
2247 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2248 // Check to see if we are shifting out everything but the sign bit.
2249 if (CU->getZExtValue() ==
2250 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002251 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002252 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002253 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002254 }
2255 }
2256 }
Chris Lattner022167f2004-03-13 00:11:49 +00002257 }
Chris Lattner183b3362004-04-09 19:05:30 +00002258
2259 // Try to fold constant sub into select arguments.
2260 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002261 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002262 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002263
2264 if (isa<PHINode>(Op0))
2265 if (Instruction *NV = FoldOpIntoPhi(I))
2266 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002267 }
2268
Chris Lattnera9be4492005-04-07 16:15:25 +00002269 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2270 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002271 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002272 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002273 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002274 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002275 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002276 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2277 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2278 // C1-(X+C2) --> (C1-C2)-X
2279 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2280 Op1I->getOperand(0));
2281 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002282 }
2283
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002284 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002285 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2286 // is not used by anyone else...
2287 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002288 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002289 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002290 // Swap the two operands of the subexpr...
2291 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2292 Op1I->setOperand(0, IIOp1);
2293 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002294
Chris Lattner3082c5a2003-02-18 19:28:33 +00002295 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002296 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002297 }
2298
2299 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2300 //
2301 if (Op1I->getOpcode() == Instruction::And &&
2302 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2303 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2304
Chris Lattner396dbfe2004-06-09 05:08:07 +00002305 Value *NewNot =
2306 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002307 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002308 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002309
Reid Spencer3c514952006-10-16 23:08:08 +00002310 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002311 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002312 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002313 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002314 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002315 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002316 ConstantExpr::getNeg(DivRHS));
2317
Chris Lattner57c8d992003-02-18 19:57:07 +00002318 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002319 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002320 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002321 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002322 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002323 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002324 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002325 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002326 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002327
Chris Lattner7a002fe2006-12-02 00:13:08 +00002328 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002329 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2330 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002331 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2332 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2333 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2334 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002335 } else if (Op0I->getOpcode() == Instruction::Sub) {
2336 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2337 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002338 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002339
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002340 ConstantInt *C1;
2341 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2342 if (X == Op1) { // X*C - X --> X * (C-1)
2343 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2344 return BinaryOperator::createMul(Op1, CP1);
2345 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002346
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002347 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2348 if (X == dyn_castFoldableMul(Op1, C2))
2349 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2350 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002351 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002352}
2353
Reid Spencer266e42b2006-12-23 06:05:41 +00002354/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002355/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002356static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2357 switch (pred) {
2358 case ICmpInst::ICMP_SLT:
2359 // True if LHS s< RHS and RHS == 0
2360 return RHS->isNullValue();
2361 case ICmpInst::ICMP_SLE:
2362 // True if LHS s<= RHS and RHS == -1
2363 return RHS->isAllOnesValue();
2364 case ICmpInst::ICMP_UGE:
2365 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2366 return RHS->getZExtValue() == (1ULL <<
2367 (RHS->getType()->getPrimitiveSizeInBits()-1));
2368 case ICmpInst::ICMP_UGT:
2369 // True if LHS u> RHS and RHS == high-bit-mask - 1
2370 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002371 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002372 default:
2373 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002374 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002375}
2376
Chris Lattner113f4f42002-06-25 16:13:24 +00002377Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002378 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002379 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002380
Chris Lattner81a7a232004-10-16 18:11:37 +00002381 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2382 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2383
Chris Lattnere6794492002-08-12 21:17:25 +00002384 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002385 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2386 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002387
2388 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002389 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002390 if (SI->getOpcode() == Instruction::Shl)
2391 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002392 return BinaryOperator::createMul(SI->getOperand(0),
2393 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002394
Chris Lattnercce81be2003-09-11 22:24:54 +00002395 if (CI->isNullValue())
2396 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2397 if (CI->equalsInt(1)) // X * 1 == X
2398 return ReplaceInstUsesWith(I, Op0);
2399 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002400 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002401
Reid Spencere0fc4df2006-10-20 07:07:24 +00002402 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002403 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2404 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002405 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002406 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002407 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002408 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002409 if (Op1F->isNullValue())
2410 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002411
Chris Lattner3082c5a2003-02-18 19:28:33 +00002412 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2413 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2414 if (Op1F->getValue() == 1.0)
2415 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2416 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002417
2418 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2419 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2420 isa<ConstantInt>(Op0I->getOperand(1))) {
2421 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2422 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2423 Op1, "tmp");
2424 InsertNewInstBefore(Add, I);
2425 Value *C1C2 = ConstantExpr::getMul(Op1,
2426 cast<Constant>(Op0I->getOperand(1)));
2427 return BinaryOperator::createAdd(Add, C1C2);
2428
2429 }
Chris Lattner183b3362004-04-09 19:05:30 +00002430
2431 // Try to fold constant mul into select arguments.
2432 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002433 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002434 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002435
2436 if (isa<PHINode>(Op0))
2437 if (Instruction *NV = FoldOpIntoPhi(I))
2438 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002439 }
2440
Chris Lattner934a64cf2003-03-10 23:23:04 +00002441 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2442 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002443 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002444
Chris Lattner2635b522004-02-23 05:39:21 +00002445 // If one of the operands of the multiply is a cast from a boolean value, then
2446 // we know the bool is either zero or one, so this is a 'masking' multiply.
2447 // See if we can simplify things based on how the boolean was originally
2448 // formed.
2449 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002450 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
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 Spencer74a528b2006-12-13 18:21:21 +00002454 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002455 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002456 BoolCast = CI;
2457 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002458 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002459 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2460 const Type *SCOpTy = SCIOp0->getType();
2461
Reid Spencer266e42b2006-12-23 06:05:41 +00002462 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002463 // multiply into a shift/and combination.
2464 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002465 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002466 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002467 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002468 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002469 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002470 InsertNewInstBefore(
2471 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002472 BoolCast->getOperand(0)->getName()+
2473 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002474
2475 // If the multiply type is not the same as the source type, sign extend
2476 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002477 if (I.getType() != V->getType()) {
2478 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2479 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2480 Instruction::CastOps opcode =
2481 (SrcBits == DstBits ? Instruction::BitCast :
2482 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2483 V = InsertCastBefore(opcode, V, I.getType(), I);
2484 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002485
Chris Lattner2635b522004-02-23 05:39:21 +00002486 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002487 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002488 }
2489 }
2490 }
2491
Chris Lattner113f4f42002-06-25 16:13:24 +00002492 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002493}
2494
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002495/// This function implements the transforms on div instructions that work
2496/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2497/// used by the visitors to those instructions.
2498/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002499Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002501
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002502 // undef / X -> 0
2503 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002504 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002505
2506 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002507 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002508 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002509
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002510 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002511 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2512 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002513 // same basic block, then we replace the select with Y, and the condition
2514 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002515 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002516 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002517 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2518 if (ST->isNullValue()) {
2519 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2520 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002521 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002522 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2523 I.setOperand(1, SI->getOperand(2));
2524 else
2525 UpdateValueUsesWith(SI, SI->getOperand(2));
2526 return &I;
2527 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002528
Chris Lattnerd79dc792006-09-09 20:26:32 +00002529 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2530 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2531 if (ST->isNullValue()) {
2532 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2533 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002534 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002535 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2536 I.setOperand(1, SI->getOperand(1));
2537 else
2538 UpdateValueUsesWith(SI, SI->getOperand(1));
2539 return &I;
2540 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002541 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002542
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002543 return 0;
2544}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002545
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002546/// This function implements the transforms common to both integer division
2547/// instructions (udiv and sdiv). It is called by the visitors to those integer
2548/// division instructions.
2549/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002550Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002551 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2552
2553 if (Instruction *Common = commonDivTransforms(I))
2554 return Common;
2555
2556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2557 // div X, 1 == X
2558 if (RHS->equalsInt(1))
2559 return ReplaceInstUsesWith(I, Op0);
2560
2561 // (X / C1) / C2 -> X / (C1*C2)
2562 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2563 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2564 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2565 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2566 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002567 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002568
2569 if (!RHS->isNullValue()) { // avoid X udiv 0
2570 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2571 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2572 return R;
2573 if (isa<PHINode>(Op0))
2574 if (Instruction *NV = FoldOpIntoPhi(I))
2575 return NV;
2576 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002577 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002578
Chris Lattner3082c5a2003-02-18 19:28:33 +00002579 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002580 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002581 if (LHS->equalsInt(0))
2582 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2583
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002584 return 0;
2585}
2586
2587Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590 // Handle the integer div common cases
2591 if (Instruction *Common = commonIDivTransforms(I))
2592 return Common;
2593
2594 // X udiv C^2 -> X >> C
2595 // Check to see if this is an unsigned division with an exact power of 2,
2596 // if so, convert to a right shift.
2597 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2598 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2599 if (isPowerOf2_64(Val)) {
2600 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002601 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002602 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002603 }
2604 }
2605
2606 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002607 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002608 if (RHSI->getOpcode() == Instruction::Shl &&
2609 isa<ConstantInt>(RHSI->getOperand(0))) {
2610 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2611 if (isPowerOf2_64(C1)) {
2612 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002613 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002614 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002615 Constant *C2V = ConstantInt::get(NTy, C2);
2616 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002617 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002618 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002619 }
2620 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002621 }
2622
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002623 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2624 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002625 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002626 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002627 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2628 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2629 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2630 // Compute the shift amounts
2631 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2632 // Construct the "on true" case of the select
2633 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2634 Instruction *TSI = BinaryOperator::createLShr(
2635 Op0, TC, SI->getName()+".t");
2636 TSI = InsertNewInstBefore(TSI, I);
2637
2638 // Construct the "on false" case of the select
2639 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2640 Instruction *FSI = BinaryOperator::createLShr(
2641 Op0, FC, SI->getName()+".f");
2642 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002643
Reid Spencer3939b1a2007-03-05 23:36:13 +00002644 // construct the select instruction and return it.
2645 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002646 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002647 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002648 return 0;
2649}
2650
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002651Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2653
2654 // Handle the integer div common cases
2655 if (Instruction *Common = commonIDivTransforms(I))
2656 return Common;
2657
2658 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2659 // sdiv X, -1 == -X
2660 if (RHS->isAllOnesValue())
2661 return BinaryOperator::createNeg(Op0);
2662
2663 // -X/C -> X/-C
2664 if (Value *LHSNeg = dyn_castNegVal(Op0))
2665 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2666 }
2667
2668 // If the sign bits of both operands are zero (i.e. we can prove they are
2669 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002670 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002671 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2672 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2673 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2674 }
2675 }
2676
2677 return 0;
2678}
2679
2680Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2681 return commonDivTransforms(I);
2682}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002683
Chris Lattner85dda9a2006-03-02 06:50:58 +00002684/// GetFactor - If we can prove that the specified value is at least a multiple
2685/// of some factor, return that factor.
2686static Constant *GetFactor(Value *V) {
2687 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2688 return CI;
2689
2690 // Unless we can be tricky, we know this is a multiple of 1.
2691 Constant *Result = ConstantInt::get(V->getType(), 1);
2692
2693 Instruction *I = dyn_cast<Instruction>(V);
2694 if (!I) return Result;
2695
2696 if (I->getOpcode() == Instruction::Mul) {
2697 // Handle multiplies by a constant, etc.
2698 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2699 GetFactor(I->getOperand(1)));
2700 } else if (I->getOpcode() == Instruction::Shl) {
2701 // (X<<C) -> X * (1 << C)
2702 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2703 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2704 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2705 }
2706 } else if (I->getOpcode() == Instruction::And) {
2707 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2708 // X & 0xFFF0 is known to be a multiple of 16.
2709 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2710 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2711 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002712 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002713 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002714 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002715 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002716 if (!CI->isIntegerCast())
2717 return Result;
2718 Value *Op = CI->getOperand(0);
2719 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002720 }
2721 return Result;
2722}
2723
Reid Spencer7eb55b32006-11-02 01:53:59 +00002724/// This function implements the transforms on rem instructions that work
2725/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2726/// is used by the visitors to those instructions.
2727/// @brief Transforms common to all three rem instructions
2728Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002730
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002731 // 0 % X == 0, we don't need to preserve faults!
2732 if (Constant *LHS = dyn_cast<Constant>(Op0))
2733 if (LHS->isNullValue())
2734 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2735
2736 if (isa<UndefValue>(Op0)) // undef % X -> 0
2737 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2738 if (isa<UndefValue>(Op1))
2739 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002740
2741 // Handle cases involving: rem X, (select Cond, Y, Z)
2742 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2743 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2744 // the same basic block, then we replace the select with Y, and the
2745 // condition of the select with false (if the cond value is in the same
2746 // BB). If the select has uses other than the div, this allows them to be
2747 // simplified also.
2748 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2749 if (ST->isNullValue()) {
2750 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2751 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002752 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002753 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2754 I.setOperand(1, SI->getOperand(2));
2755 else
2756 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002757 return &I;
2758 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002759 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2760 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2761 if (ST->isNullValue()) {
2762 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2763 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002764 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002765 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2766 I.setOperand(1, SI->getOperand(1));
2767 else
2768 UpdateValueUsesWith(SI, SI->getOperand(1));
2769 return &I;
2770 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002771 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002772
Reid Spencer7eb55b32006-11-02 01:53:59 +00002773 return 0;
2774}
2775
2776/// This function implements the transforms common to both integer remainder
2777/// instructions (urem and srem). It is called by the visitors to those integer
2778/// remainder instructions.
2779/// @brief Common integer remainder transforms
2780Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2781 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2782
2783 if (Instruction *common = commonRemTransforms(I))
2784 return common;
2785
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002787 // X % 0 == undef, we don't need to preserve faults!
2788 if (RHS->equalsInt(0))
2789 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2790
Chris Lattner3082c5a2003-02-18 19:28:33 +00002791 if (RHS->equalsInt(1)) // X % 1 == 0
2792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2793
Chris Lattnerb70f1412006-02-28 05:49:21 +00002794 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2797 return R;
2798 } else if (isa<PHINode>(Op0I)) {
2799 if (Instruction *NV = FoldOpIntoPhi(I))
2800 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002801 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002802 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2803 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002804 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002805 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002806 }
2807
Reid Spencer7eb55b32006-11-02 01:53:59 +00002808 return 0;
2809}
2810
2811Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2812 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2813
2814 if (Instruction *common = commonIRemTransforms(I))
2815 return common;
2816
2817 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2818 // X urem C^2 -> X and C
2819 // Check to see if this is an unsigned remainder with an exact power of 2,
2820 // if so, convert to a bitwise and.
2821 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2822 if (isPowerOf2_64(C->getZExtValue()))
2823 return BinaryOperator::createAnd(Op0, SubOne(C));
2824 }
2825
Chris Lattner2e90b732006-02-05 07:54:04 +00002826 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002827 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2828 if (RHSI->getOpcode() == Instruction::Shl &&
2829 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002830 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002831 if (isPowerOf2_64(C1)) {
2832 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2833 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2834 "tmp"), I);
2835 return BinaryOperator::createAnd(Op0, Add);
2836 }
2837 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002838 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002839
Reid Spencer7eb55b32006-11-02 01:53:59 +00002840 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2841 // where C1&C2 are powers of two.
2842 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2843 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2844 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2845 // STO == 0 and SFO == 0 handled above.
2846 if (isPowerOf2_64(STO->getZExtValue()) &&
2847 isPowerOf2_64(SFO->getZExtValue())) {
2848 Value *TrueAnd = InsertNewInstBefore(
2849 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2850 Value *FalseAnd = InsertNewInstBefore(
2851 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2852 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2853 }
2854 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002855 }
2856
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002857 return 0;
2858}
2859
Reid Spencer7eb55b32006-11-02 01:53:59 +00002860Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2862
2863 if (Instruction *common = commonIRemTransforms(I))
2864 return common;
2865
2866 if (Value *RHSNeg = dyn_castNegVal(Op1))
2867 if (!isa<ConstantInt>(RHSNeg) ||
2868 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2869 // X % -Y -> X % Y
2870 AddUsesToWorkList(I);
2871 I.setOperand(1, RHSNeg);
2872 return &I;
2873 }
2874
2875 // If the top bits of both operands are zero (i.e. we can prove they are
2876 // unsigned inputs), turn this into a urem.
2877 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2878 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2879 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2880 return BinaryOperator::createURem(Op0, Op1, I.getName());
2881 }
2882
2883 return 0;
2884}
2885
2886Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002887 return commonRemTransforms(I);
2888}
2889
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002890// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002891static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2892 if (isSigned) {
2893 // Calculate 0111111111..11111
2894 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2895 int64_t Val = INT64_MAX; // All ones
2896 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2897 return C->getSExtValue() == Val-1;
2898 }
Reid Spencera94d3942007-01-19 21:13:56 +00002899 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002900}
2901
2902// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002903static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2904 if (isSigned) {
2905 // Calculate 1111111111000000000000
2906 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2907 int64_t Val = -1; // All ones
2908 Val <<= TypeBits-1; // Shift over to the right spot
2909 return C->getSExtValue() == Val+1;
2910 }
2911 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002912}
2913
Chris Lattner35167c32004-06-09 07:59:58 +00002914// isOneBitSet - Return true if there is exactly one bit set in the specified
2915// constant.
2916static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002917 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002918 return V && (V & (V-1)) == 0;
2919}
2920
Chris Lattner8fc5af42004-09-23 21:46:38 +00002921#if 0 // Currently unused
2922// isLowOnes - Return true if the constant is of the form 0+1+.
2923static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002924 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002925
2926 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002927 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002928
2929 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2930 return U && V && (U & V) == 0;
2931}
2932#endif
2933
2934// isHighOnes - Return true if the constant is of the form 1+0+.
2935// This is the same as lowones(~X).
2936static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002937 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002938 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002939
2940 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002941 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002942
2943 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2944 return U && V && (U & V) == 0;
2945}
2946
Reid Spencer266e42b2006-12-23 06:05:41 +00002947/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002948/// are carefully arranged to allow folding of expressions such as:
2949///
2950/// (A < B) | (A > B) --> (A != B)
2951///
Reid Spencer266e42b2006-12-23 06:05:41 +00002952/// Note that this is only valid if the first and second predicates have the
2953/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002954///
Reid Spencer266e42b2006-12-23 06:05:41 +00002955/// Three bits are used to represent the condition, as follows:
2956/// 0 A > B
2957/// 1 A == B
2958/// 2 A < B
2959///
2960/// <=> Value Definition
2961/// 000 0 Always false
2962/// 001 1 A > B
2963/// 010 2 A == B
2964/// 011 3 A >= B
2965/// 100 4 A < B
2966/// 101 5 A != B
2967/// 110 6 A <= B
2968/// 111 7 Always true
2969///
2970static unsigned getICmpCode(const ICmpInst *ICI) {
2971 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002972 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002973 case ICmpInst::ICMP_UGT: return 1; // 001
2974 case ICmpInst::ICMP_SGT: return 1; // 001
2975 case ICmpInst::ICMP_EQ: return 2; // 010
2976 case ICmpInst::ICMP_UGE: return 3; // 011
2977 case ICmpInst::ICMP_SGE: return 3; // 011
2978 case ICmpInst::ICMP_ULT: return 4; // 100
2979 case ICmpInst::ICMP_SLT: return 4; // 100
2980 case ICmpInst::ICMP_NE: return 5; // 101
2981 case ICmpInst::ICMP_ULE: return 6; // 110
2982 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002983 // True -> 7
2984 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002985 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002986 return 0;
2987 }
2988}
2989
Reid Spencer266e42b2006-12-23 06:05:41 +00002990/// getICmpValue - This is the complement of getICmpCode, which turns an
2991/// opcode and two operands into either a constant true or false, or a brand
2992/// new /// ICmp instruction. The sign is passed in to determine which kind
2993/// of predicate to use in new icmp instructions.
2994static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2995 switch (code) {
2996 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002997 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002998 case 1:
2999 if (sign)
3000 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3001 else
3002 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3003 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3004 case 3:
3005 if (sign)
3006 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3007 else
3008 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3009 case 4:
3010 if (sign)
3011 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3012 else
3013 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3014 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3015 case 6:
3016 if (sign)
3017 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3018 else
3019 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003020 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003021 }
3022}
3023
Reid Spencer266e42b2006-12-23 06:05:41 +00003024static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3025 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3026 (ICmpInst::isSignedPredicate(p1) &&
3027 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3028 (ICmpInst::isSignedPredicate(p2) &&
3029 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3030}
3031
3032namespace {
3033// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3034struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003035 InstCombiner &IC;
3036 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003037 ICmpInst::Predicate pred;
3038 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3039 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3040 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003041 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003042 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3043 if (PredicatesFoldable(pred, ICI->getPredicate()))
3044 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3045 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003046 return false;
3047 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003048 Instruction *apply(Instruction &Log) const {
3049 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3050 if (ICI->getOperand(0) != LHS) {
3051 assert(ICI->getOperand(1) == LHS);
3052 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003053 }
3054
Reid Spencer266e42b2006-12-23 06:05:41 +00003055 unsigned LHSCode = getICmpCode(ICI);
3056 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00003057 unsigned Code;
3058 switch (Log.getOpcode()) {
3059 case Instruction::And: Code = LHSCode & RHSCode; break;
3060 case Instruction::Or: Code = LHSCode | RHSCode; break;
3061 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003062 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003063 }
3064
Reid Spencer266e42b2006-12-23 06:05:41 +00003065 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003066 if (Instruction *I = dyn_cast<Instruction>(RV))
3067 return I;
3068 // Otherwise, it's a constant boolean value...
3069 return IC.ReplaceInstUsesWith(Log, RV);
3070 }
3071};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003072} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003073
Chris Lattnerba1cb382003-09-19 17:17:26 +00003074// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3075// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003076// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003077Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003078 ConstantInt *OpRHS,
3079 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003080 BinaryOperator &TheAnd) {
3081 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003082 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003083 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003084 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003085
Chris Lattnerba1cb382003-09-19 17:17:26 +00003086 switch (Op->getOpcode()) {
3087 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003088 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003089 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003090 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003091 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003092 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003093 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003094 }
3095 break;
3096 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003097 if (Together == AndRHS) // (X | C) & C --> C
3098 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003099
Chris Lattner86102b82005-01-01 16:22:27 +00003100 if (Op->hasOneUse() && Together != OpRHS) {
3101 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003102 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003103 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003104 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003105 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003106 }
3107 break;
3108 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003109 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003110 // Adding a one to a single bit bit-field should be turned into an XOR
3111 // of the bit. First thing to check is to see if this AND is with a
3112 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003113 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003114
3115 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00003116 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00003117
3118 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003119 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003120 // Ok, at this point, we know that we are masking the result of the
3121 // ADD down to exactly one bit. If the constant we are adding has
3122 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003123 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003124
Chris Lattnerba1cb382003-09-19 17:17:26 +00003125 // Check to see if any bits below the one bit set in AndRHSV are set.
3126 if ((AddRHS & (AndRHSV-1)) == 0) {
3127 // If not, the only thing that can effect the output of the AND is
3128 // the bit specified by AndRHSV. If that bit is set, the effect of
3129 // the XOR is to toggle the bit. If it is clear, then the ADD has
3130 // no effect.
3131 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3132 TheAnd.setOperand(0, X);
3133 return &TheAnd;
3134 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003135 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003136 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003137 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003138 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003139 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003140 }
3141 }
3142 }
3143 }
3144 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003145
3146 case Instruction::Shl: {
3147 // We know that the AND will not produce any of the bits shifted in, so if
3148 // the anded constant includes them, clear them now!
3149 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003150 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00003151 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3152 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003153
Chris Lattner7e794272004-09-24 15:21:34 +00003154 if (CI == ShlMask) { // Masking out bits that the shift already masks
3155 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3156 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003157 TheAnd.setOperand(1, CI);
3158 return &TheAnd;
3159 }
3160 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003161 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003162 case Instruction::LShr:
3163 {
Chris Lattner2da29172003-09-19 19:05:02 +00003164 // We know that the AND will not produce any of the bits shifted in, so if
3165 // the anded constant includes them, clear them now! This only applies to
3166 // unsigned shifts, because a signed shr may bring in set bits!
3167 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003168 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003169 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3170 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003171
Reid Spencerfdff9382006-11-08 06:47:33 +00003172 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3173 return ReplaceInstUsesWith(TheAnd, Op);
3174 } else if (CI != AndRHS) {
3175 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3176 return &TheAnd;
3177 }
3178 break;
3179 }
3180 case Instruction::AShr:
3181 // Signed shr.
3182 // See if this is shifting in some sign extension, then masking it out
3183 // with an and.
3184 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003185 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003186 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003187 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3188 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003189 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003190 // Make the argument unsigned.
3191 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003192 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003193 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003194 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003195 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003196 }
Chris Lattner2da29172003-09-19 19:05:02 +00003197 }
3198 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003199 }
3200 return 0;
3201}
3202
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003203
Chris Lattner6862fbd2004-09-29 17:40:11 +00003204/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3205/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003206/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3207/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003208/// insert new instructions.
3209Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003210 bool isSigned, bool Inside,
3211 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003212 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003213 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003214 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003215
Chris Lattner6862fbd2004-09-29 17:40:11 +00003216 if (Inside) {
3217 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003218 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003219
Reid Spencer266e42b2006-12-23 06:05:41 +00003220 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003221 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003222 ICmpInst::Predicate pred = (isSigned ?
3223 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3224 return new ICmpInst(pred, V, Hi);
3225 }
3226
3227 // Emit V-Lo <u Hi-Lo
3228 Constant *NegLo = ConstantExpr::getNeg(Lo);
3229 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003230 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003231 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3232 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003233 }
3234
3235 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003236 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003237
Reid Spencer266e42b2006-12-23 06:05:41 +00003238 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003239 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003240 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003241 ICmpInst::Predicate pred = (isSigned ?
3242 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3243 return new ICmpInst(pred, V, Hi);
3244 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003245
Reid Spencer266e42b2006-12-23 06:05:41 +00003246 // Emit V-Lo > Hi-1-Lo
3247 Constant *NegLo = ConstantExpr::getNeg(Lo);
3248 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003249 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003250 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3251 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003252}
3253
Chris Lattnerb4b25302005-09-18 07:22:02 +00003254// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3255// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3256// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3257// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003258static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003259 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003260 if (!isShiftedMask_64(V)) return false;
3261
3262 // look for the first zero bit after the run of ones
3263 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3264 // look for the first non-zero bit
3265 ME = 64-CountLeadingZeros_64(V);
3266 return true;
3267}
3268
3269
3270
3271/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3272/// where isSub determines whether the operator is a sub. If we can fold one of
3273/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003274///
3275/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3276/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3277/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3278///
3279/// return (A +/- B).
3280///
3281Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003282 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003283 Instruction &I) {
3284 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3285 if (!LHSI || LHSI->getNumOperands() != 2 ||
3286 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3287
3288 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3289
3290 switch (LHSI->getOpcode()) {
3291 default: return 0;
3292 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003293 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3294 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003295 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003296 break;
3297
3298 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3299 // part, we don't need any explicit masks to take them out of A. If that
3300 // is all N is, ignore it.
3301 unsigned MB, ME;
3302 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003303 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003304 Mask >>= 64-MB+1;
3305 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003306 break;
3307 }
3308 }
Chris Lattneraf517572005-09-18 04:24:45 +00003309 return 0;
3310 case Instruction::Or:
3311 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003312 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003313 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003314 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003315 break;
3316 return 0;
3317 }
3318
3319 Instruction *New;
3320 if (isSub)
3321 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3322 else
3323 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3324 return InsertNewInstBefore(New, I);
3325}
3326
Chris Lattner113f4f42002-06-25 16:13:24 +00003327Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003328 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003329 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003330
Chris Lattner81a7a232004-10-16 18:11:37 +00003331 if (isa<UndefValue>(Op1)) // X & undef -> 0
3332 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3333
Chris Lattner86102b82005-01-01 16:22:27 +00003334 // and X, X = X
3335 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003336 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003337
Chris Lattner5b2edb12006-02-12 08:02:11 +00003338 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003339 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003340 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003341 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003342 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003343 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003344 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003345 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003346 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003347 if (CP->isAllOnesValue())
3348 return ReplaceInstUsesWith(I, I.getOperand(0));
3349 }
3350 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003351
Zhou Sheng75b871f2007-01-11 12:24:14 +00003352 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003353 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003354 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003355 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003356
Chris Lattnerba1cb382003-09-19 17:17:26 +00003357 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003358 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003359 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003360 Value *Op0LHS = Op0I->getOperand(0);
3361 Value *Op0RHS = Op0I->getOperand(1);
3362 switch (Op0I->getOpcode()) {
3363 case Instruction::Xor:
3364 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003365 // If the mask is only needed on one incoming arm, push it up.
3366 if (Op0I->hasOneUse()) {
3367 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3368 // Not masking anything out for the LHS, move to RHS.
3369 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3370 Op0RHS->getName()+".masked");
3371 InsertNewInstBefore(NewRHS, I);
3372 return BinaryOperator::create(
3373 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003374 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003375 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003376 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3377 // Not masking anything out for the RHS, move to LHS.
3378 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3379 Op0LHS->getName()+".masked");
3380 InsertNewInstBefore(NewLHS, I);
3381 return BinaryOperator::create(
3382 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3383 }
3384 }
3385
Chris Lattner86102b82005-01-01 16:22:27 +00003386 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003387 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003388 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3389 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3390 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3391 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3392 return BinaryOperator::createAnd(V, AndRHS);
3393 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3394 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003395 break;
3396
3397 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003398 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3399 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3400 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3401 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3402 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003403 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003404 }
3405
Chris Lattner16464b32003-07-23 19:25:52 +00003406 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003407 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003408 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003409 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003410 // If this is an integer truncation or change from signed-to-unsigned, and
3411 // if the source is an and/or with immediate, transform it. This
3412 // frequently occurs for bitfield accesses.
3413 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003414 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003415 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003416 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003417 if (CastOp->getOpcode() == Instruction::And) {
3418 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003419 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3420 // This will fold the two constants together, which may allow
3421 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003422 Instruction *NewCast = CastInst::createTruncOrBitCast(
3423 CastOp->getOperand(0), I.getType(),
3424 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003425 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003426 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003427 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003428 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003429 return BinaryOperator::createAnd(NewCast, C3);
3430 } else if (CastOp->getOpcode() == Instruction::Or) {
3431 // Change: and (cast (or X, C1) to T), C2
3432 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003433 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003434 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3435 return ReplaceInstUsesWith(I, AndRHS);
3436 }
3437 }
Chris Lattner33217db2003-07-23 19:36:21 +00003438 }
Chris Lattner183b3362004-04-09 19:05:30 +00003439
3440 // Try to fold constant and into select arguments.
3441 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003442 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003443 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003444 if (isa<PHINode>(Op0))
3445 if (Instruction *NV = FoldOpIntoPhi(I))
3446 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003447 }
3448
Chris Lattnerbb74e222003-03-10 23:06:50 +00003449 Value *Op0NotVal = dyn_castNotVal(Op0);
3450 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003451
Chris Lattner023a4832004-06-18 06:07:51 +00003452 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3453 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3454
Misha Brukman9c003d82004-07-30 12:50:08 +00003455 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003456 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003457 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3458 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003459 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003460 return BinaryOperator::createNot(Or);
3461 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003462
3463 {
3464 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003465 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3466 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3467 return ReplaceInstUsesWith(I, Op1);
3468 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3469 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3470 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003471
3472 if (Op0->hasOneUse() &&
3473 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3474 if (A == Op1) { // (A^B)&A -> A&(A^B)
3475 I.swapOperands(); // Simplify below
3476 std::swap(Op0, Op1);
3477 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3478 cast<BinaryOperator>(Op0)->swapOperands();
3479 I.swapOperands(); // Simplify below
3480 std::swap(Op0, Op1);
3481 }
3482 }
3483 if (Op1->hasOneUse() &&
3484 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3485 if (B == Op0) { // B&(A^B) -> B&(B^A)
3486 cast<BinaryOperator>(Op1)->swapOperands();
3487 std::swap(A, B);
3488 }
3489 if (A == Op0) { // A&(A^B) -> A & ~B
3490 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3491 InsertNewInstBefore(NotB, I);
3492 return BinaryOperator::createAnd(A, NotB);
3493 }
3494 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003495 }
3496
Reid Spencer266e42b2006-12-23 06:05:41 +00003497 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3498 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3499 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003500 return R;
3501
Chris Lattner623826c2004-09-28 21:48:02 +00003502 Value *LHSVal, *RHSVal;
3503 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003504 ICmpInst::Predicate LHSCC, RHSCC;
3505 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3506 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3507 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3508 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3509 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3510 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3511 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3512 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003513 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003514 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3515 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3516 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3517 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003518 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003519 std::swap(LHS, RHS);
3520 std::swap(LHSCst, RHSCst);
3521 std::swap(LHSCC, RHSCC);
3522 }
3523
Reid Spencer266e42b2006-12-23 06:05:41 +00003524 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003525 // comparing a value against two constants and and'ing the result
3526 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003527 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3528 // (from the FoldICmpLogical check above), that the two constants
3529 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003530 assert(LHSCst != RHSCst && "Compares not folded above?");
3531
3532 switch (LHSCC) {
3533 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003534 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003535 switch (RHSCC) {
3536 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003537 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3538 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3539 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003540 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003541 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3542 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3543 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003544 return ReplaceInstUsesWith(I, LHS);
3545 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003546 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003547 switch (RHSCC) {
3548 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003549 case ICmpInst::ICMP_ULT:
3550 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3551 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3552 break; // (X != 13 & X u< 15) -> no change
3553 case ICmpInst::ICMP_SLT:
3554 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3555 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3556 break; // (X != 13 & X s< 15) -> no change
3557 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3558 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3559 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003560 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003561 case ICmpInst::ICMP_NE:
3562 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003563 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3564 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3565 LHSVal->getName()+".off");
3566 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003567 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3568 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003569 }
3570 break; // (X != 13 & X != 15) -> no change
3571 }
3572 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003573 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003574 switch (RHSCC) {
3575 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003576 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3577 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003579 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3580 break;
3581 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3582 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003583 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003584 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3585 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003586 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003587 break;
3588 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003589 switch (RHSCC) {
3590 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003591 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3592 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003593 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003594 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3595 break;
3596 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3597 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003598 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003599 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3600 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003601 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003602 break;
3603 case ICmpInst::ICMP_UGT:
3604 switch (RHSCC) {
3605 default: assert(0 && "Unknown integer condition code!");
3606 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3607 return ReplaceInstUsesWith(I, LHS);
3608 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3609 return ReplaceInstUsesWith(I, RHS);
3610 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3611 break;
3612 case ICmpInst::ICMP_NE:
3613 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3614 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3615 break; // (X u> 13 & X != 15) -> no change
3616 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3617 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3618 true, I);
3619 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3620 break;
3621 }
3622 break;
3623 case ICmpInst::ICMP_SGT:
3624 switch (RHSCC) {
3625 default: assert(0 && "Unknown integer condition code!");
3626 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3627 return ReplaceInstUsesWith(I, LHS);
3628 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3629 return ReplaceInstUsesWith(I, RHS);
3630 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3631 break;
3632 case ICmpInst::ICMP_NE:
3633 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3634 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3635 break; // (X s> 13 & X != 15) -> no change
3636 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3637 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3638 true, I);
3639 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3640 break;
3641 }
3642 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003643 }
3644 }
3645 }
3646
Chris Lattner3af10532006-05-05 06:39:07 +00003647 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003648 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3649 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3650 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3651 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003652 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003653 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003654 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3655 I.getType(), TD) &&
3656 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3657 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003658 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3659 Op1C->getOperand(0),
3660 I.getName());
3661 InsertNewInstBefore(NewOp, I);
3662 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3663 }
Chris Lattner3af10532006-05-05 06:39:07 +00003664 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003665
3666 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003667 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3668 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3669 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003670 SI0->getOperand(1) == SI1->getOperand(1) &&
3671 (SI0->hasOneUse() || SI1->hasOneUse())) {
3672 Instruction *NewOp =
3673 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3674 SI1->getOperand(0),
3675 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003676 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3677 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003678 }
Chris Lattner3af10532006-05-05 06:39:07 +00003679 }
3680
Chris Lattner113f4f42002-06-25 16:13:24 +00003681 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003682}
3683
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003684/// CollectBSwapParts - Look to see if the specified value defines a single byte
3685/// in the result. If it does, and if the specified byte hasn't been filled in
3686/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003687static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003688 Instruction *I = dyn_cast<Instruction>(V);
3689 if (I == 0) return true;
3690
3691 // If this is an or instruction, it is an inner node of the bswap.
3692 if (I->getOpcode() == Instruction::Or)
3693 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3694 CollectBSwapParts(I->getOperand(1), ByteValues);
3695
3696 // If this is a shift by a constant int, and it is "24", then its operand
3697 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003698 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003699 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003700 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003701 8*(ByteValues.size()-1))
3702 return true;
3703
3704 unsigned DestNo;
3705 if (I->getOpcode() == Instruction::Shl) {
3706 // X << 24 defines the top byte with the lowest of the input bytes.
3707 DestNo = ByteValues.size()-1;
3708 } else {
3709 // X >>u 24 defines the low byte with the highest of the input bytes.
3710 DestNo = 0;
3711 }
3712
3713 // If the destination byte value is already defined, the values are or'd
3714 // together, which isn't a bswap (unless it's an or of the same bits).
3715 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3716 return true;
3717 ByteValues[DestNo] = I->getOperand(0);
3718 return false;
3719 }
3720
3721 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3722 // don't have this.
3723 Value *Shift = 0, *ShiftLHS = 0;
3724 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3725 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3726 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3727 return true;
3728 Instruction *SI = cast<Instruction>(Shift);
3729
3730 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003731 if (ShiftAmt->getZExtValue() & 7 ||
3732 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003733 return true;
3734
3735 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3736 unsigned DestByte;
3737 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003738 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003739 break;
3740 // Unknown mask for bswap.
3741 if (DestByte == ByteValues.size()) return true;
3742
Reid Spencere0fc4df2006-10-20 07:07:24 +00003743 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003744 unsigned SrcByte;
3745 if (SI->getOpcode() == Instruction::Shl)
3746 SrcByte = DestByte - ShiftBytes;
3747 else
3748 SrcByte = DestByte + ShiftBytes;
3749
3750 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3751 if (SrcByte != ByteValues.size()-DestByte-1)
3752 return true;
3753
3754 // If the destination byte value is already defined, the values are or'd
3755 // together, which isn't a bswap (unless it's an or of the same bits).
3756 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3757 return true;
3758 ByteValues[DestByte] = SI->getOperand(0);
3759 return false;
3760}
3761
3762/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3763/// If so, insert the new bswap intrinsic and return it.
3764Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003765 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003766 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003767 return 0;
3768
3769 /// ByteValues - For each byte of the result, we keep track of which value
3770 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003771 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003772 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003773
3774 // Try to find all the pieces corresponding to the bswap.
3775 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3776 CollectBSwapParts(I.getOperand(1), ByteValues))
3777 return 0;
3778
3779 // Check to see if all of the bytes come from the same value.
3780 Value *V = ByteValues[0];
3781 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3782
3783 // Check to make sure that all of the bytes come from the same value.
3784 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3785 if (ByteValues[i] != V)
3786 return 0;
3787
3788 // If they do then *success* we can turn this into a bswap. Figure out what
3789 // bswap to make it into.
3790 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003791 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003792 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003793 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003794 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003795 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003796 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003797 FnName = "llvm.bswap.i64";
3798 else
3799 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003800 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003801 return new CallInst(F, V);
3802}
3803
3804
Chris Lattner113f4f42002-06-25 16:13:24 +00003805Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003806 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003807 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003808
Chris Lattner81a7a232004-10-16 18:11:37 +00003809 if (isa<UndefValue>(Op1))
3810 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003811 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003812
Chris Lattner5b2edb12006-02-12 08:02:11 +00003813 // or X, X = X
3814 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003815 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003816
Chris Lattner5b2edb12006-02-12 08:02:11 +00003817 // See if we can simplify any instructions used by the instruction whose sole
3818 // purpose is to compute bits we don't care about.
3819 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003820 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003821 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003822 KnownZero, KnownOne))
3823 return &I;
3824
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003825 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003826 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003827 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003828 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3829 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003830 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003831 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003832 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003833 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3834 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003835
Chris Lattnerd4252a72004-07-30 07:50:03 +00003836 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3837 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003838 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003839 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003840 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003841 return BinaryOperator::createXor(Or,
3842 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003843 }
Chris Lattner183b3362004-04-09 19:05:30 +00003844
3845 // Try to fold constant and into select arguments.
3846 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003847 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003848 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003849 if (isa<PHINode>(Op0))
3850 if (Instruction *NV = FoldOpIntoPhi(I))
3851 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003852 }
3853
Chris Lattner330628a2006-01-06 17:59:59 +00003854 Value *A = 0, *B = 0;
3855 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003856
3857 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3858 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3859 return ReplaceInstUsesWith(I, Op1);
3860 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3861 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3862 return ReplaceInstUsesWith(I, Op0);
3863
Chris Lattnerb7845d62006-07-10 20:25:24 +00003864 // (A | B) | C and A | (B | C) -> bswap if possible.
3865 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003866 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003867 match(Op1, m_Or(m_Value(), m_Value())) ||
3868 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3869 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003870 if (Instruction *BSwap = MatchBSwap(I))
3871 return BSwap;
3872 }
3873
Chris Lattnerb62f5082005-05-09 04:58:36 +00003874 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3875 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003876 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003877 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3878 InsertNewInstBefore(NOr, I);
3879 NOr->takeName(Op0);
3880 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003881 }
3882
3883 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3884 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003885 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003886 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3887 InsertNewInstBefore(NOr, I);
3888 NOr->takeName(Op0);
3889 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003890 }
3891
Chris Lattner15212982005-09-18 03:42:07 +00003892 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003893 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003894 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3895
3896 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3897 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3898
3899
Chris Lattner01f56c62005-09-18 06:02:59 +00003900 // If we have: ((V + N) & C1) | (V & C2)
3901 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3902 // replace with V+N.
3903 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003904 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003905 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003906 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3907 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003908 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003909 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003910 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003911 return ReplaceInstUsesWith(I, A);
3912 }
3913 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003914 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003915 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3916 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003917 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003918 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003919 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003920 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003921 }
3922 }
3923 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003924
3925 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003926 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3927 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3928 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003929 SI0->getOperand(1) == SI1->getOperand(1) &&
3930 (SI0->hasOneUse() || SI1->hasOneUse())) {
3931 Instruction *NewOp =
3932 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3933 SI1->getOperand(0),
3934 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003935 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3936 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003937 }
3938 }
Chris Lattner812aab72003-08-12 19:11:07 +00003939
Chris Lattnerd4252a72004-07-30 07:50:03 +00003940 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3941 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003942 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003943 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003944 } else {
3945 A = 0;
3946 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003947 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003948 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3949 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003950 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003951 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003952
Misha Brukman9c003d82004-07-30 12:50:08 +00003953 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003954 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3955 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3956 I.getName()+".demorgan"), I);
3957 return BinaryOperator::createNot(And);
3958 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003959 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003960
Reid Spencer266e42b2006-12-23 06:05:41 +00003961 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3962 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3963 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003964 return R;
3965
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003966 Value *LHSVal, *RHSVal;
3967 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003968 ICmpInst::Predicate LHSCC, RHSCC;
3969 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3970 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3971 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3972 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3973 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3974 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3975 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3976 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003977 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003978 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3979 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3980 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3981 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003982 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003983 std::swap(LHS, RHS);
3984 std::swap(LHSCst, RHSCst);
3985 std::swap(LHSCC, RHSCC);
3986 }
3987
Reid Spencer266e42b2006-12-23 06:05:41 +00003988 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003989 // comparing a value against two constants and or'ing the result
3990 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003991 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3992 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003993 // equal.
3994 assert(LHSCst != RHSCst && "Compares not folded above?");
3995
3996 switch (LHSCC) {
3997 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003998 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003999 switch (RHSCC) {
4000 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004002 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4003 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4004 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4005 LHSVal->getName()+".off");
4006 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004007 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004008 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004009 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004010 break; // (X == 13 | X == 15) -> no change
4011 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4012 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004013 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004014 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4015 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4016 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004017 return ReplaceInstUsesWith(I, RHS);
4018 }
4019 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004020 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004021 switch (RHSCC) {
4022 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004023 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4024 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4025 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004026 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004027 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4028 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4029 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004030 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004031 }
4032 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004033 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004034 switch (RHSCC) {
4035 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004036 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004037 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004038 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4039 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4040 false, I);
4041 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4042 break;
4043 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4044 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004045 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4047 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004048 }
4049 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004050 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004051 switch (RHSCC) {
4052 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004053 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4054 break;
4055 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4056 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4057 false, I);
4058 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4059 break;
4060 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4061 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4062 return ReplaceInstUsesWith(I, RHS);
4063 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4064 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004065 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004066 break;
4067 case ICmpInst::ICMP_UGT:
4068 switch (RHSCC) {
4069 default: assert(0 && "Unknown integer condition code!");
4070 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4071 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4072 return ReplaceInstUsesWith(I, LHS);
4073 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4074 break;
4075 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4076 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004077 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004078 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4079 break;
4080 }
4081 break;
4082 case ICmpInst::ICMP_SGT:
4083 switch (RHSCC) {
4084 default: assert(0 && "Unknown integer condition code!");
4085 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4086 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4087 return ReplaceInstUsesWith(I, LHS);
4088 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4089 break;
4090 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4091 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004092 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4094 break;
4095 }
4096 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004097 }
4098 }
4099 }
Chris Lattner3af10532006-05-05 06:39:07 +00004100
4101 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004102 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004103 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004104 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4105 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004106 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004107 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004108 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4109 I.getType(), TD) &&
4110 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4111 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004112 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4113 Op1C->getOperand(0),
4114 I.getName());
4115 InsertNewInstBefore(NewOp, I);
4116 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4117 }
Chris Lattner3af10532006-05-05 06:39:07 +00004118 }
Chris Lattner3af10532006-05-05 06:39:07 +00004119
Chris Lattner15212982005-09-18 03:42:07 +00004120
Chris Lattner113f4f42002-06-25 16:13:24 +00004121 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004122}
4123
Chris Lattnerc2076352004-02-16 01:20:27 +00004124// XorSelf - Implements: X ^ X --> 0
4125struct XorSelf {
4126 Value *RHS;
4127 XorSelf(Value *rhs) : RHS(rhs) {}
4128 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4129 Instruction *apply(BinaryOperator &Xor) const {
4130 return &Xor;
4131 }
4132};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004133
4134
Chris Lattner113f4f42002-06-25 16:13:24 +00004135Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004136 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004137 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004138
Chris Lattner81a7a232004-10-16 18:11:37 +00004139 if (isa<UndefValue>(Op1))
4140 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4141
Chris Lattnerc2076352004-02-16 01:20:27 +00004142 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4143 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4144 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004146 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004147
4148 // See if we can simplify any instructions used by the instruction whose sole
4149 // purpose is to compute bits we don't care about.
4150 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004151 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00004152 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004153 KnownZero, KnownOne))
4154 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004155
Zhou Sheng75b871f2007-01-11 12:24:14 +00004156 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004157 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4158 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004159 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004160 return new ICmpInst(ICI->getInversePredicate(),
4161 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004162
Reid Spencer266e42b2006-12-23 06:05:41 +00004163 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004164 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004165 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4166 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004167 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4168 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004169 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004170 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004171 }
Chris Lattner023a4832004-06-18 06:07:51 +00004172
4173 // ~(~X & Y) --> (X | ~Y)
4174 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4175 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4176 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4177 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004178 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004179 Op0I->getOperand(1)->getName()+".not");
4180 InsertNewInstBefore(NotY, I);
4181 return BinaryOperator::createOr(Op0NotVal, NotY);
4182 }
4183 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004184
Chris Lattner97638592003-07-23 21:37:07 +00004185 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004186 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004187 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004188 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004189 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4190 return BinaryOperator::createSub(
4191 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004192 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004193 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004194 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004195 } else if (Op0I->getOpcode() == Instruction::Or) {
4196 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4197 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
4198 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4199 // Anything in both C1 and C2 is known to be zero, remove it from
4200 // NewRHS.
4201 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4202 NewRHS = ConstantExpr::getAnd(NewRHS,
4203 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004204 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004205 I.setOperand(0, Op0I->getOperand(0));
4206 I.setOperand(1, NewRHS);
4207 return &I;
4208 }
Chris Lattner97638592003-07-23 21:37:07 +00004209 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004210 }
Chris Lattner183b3362004-04-09 19:05:30 +00004211
4212 // Try to fold constant and into select arguments.
4213 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004214 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004215 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004216 if (isa<PHINode>(Op0))
4217 if (Instruction *NV = FoldOpIntoPhi(I))
4218 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004219 }
4220
Chris Lattnerbb74e222003-03-10 23:06:50 +00004221 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004222 if (X == Op1)
4223 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004224 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004225
Chris Lattnerbb74e222003-03-10 23:06:50 +00004226 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004227 if (X == Op0)
4228 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004229 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004230
Chris Lattnerdcd07922006-04-01 08:03:55 +00004231 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00004232 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004233 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004234 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004235 I.swapOperands();
4236 std::swap(Op0, Op1);
4237 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004238 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004239 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004240 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004241 } else if (Op1I->getOpcode() == Instruction::Xor) {
4242 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4243 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4244 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4245 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004246 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4247 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4248 Op1I->swapOperands();
4249 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4250 I.swapOperands(); // Simplified below.
4251 std::swap(Op0, Op1);
4252 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004253 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004254
Chris Lattnerdcd07922006-04-01 08:03:55 +00004255 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004256 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004257 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004258 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004259 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004260 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4261 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004262 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004263 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004264 } else if (Op0I->getOpcode() == Instruction::Xor) {
4265 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4266 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4267 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4268 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004269 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4270 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4271 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004272 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4273 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004274 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4275 InsertNewInstBefore(N, I);
4276 return BinaryOperator::createAnd(N, Op1);
4277 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004278 }
4279
Reid Spencer266e42b2006-12-23 06:05:41 +00004280 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4281 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4282 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004283 return R;
4284
Chris Lattner3af10532006-05-05 06:39:07 +00004285 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004286 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004287 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004288 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4289 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004290 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004291 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004292 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4293 I.getType(), TD) &&
4294 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4295 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004296 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4297 Op1C->getOperand(0),
4298 I.getName());
4299 InsertNewInstBefore(NewOp, I);
4300 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4301 }
Chris Lattner3af10532006-05-05 06:39:07 +00004302 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004303
4304 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004305 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4306 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4307 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004308 SI0->getOperand(1) == SI1->getOperand(1) &&
4309 (SI0->hasOneUse() || SI1->hasOneUse())) {
4310 Instruction *NewOp =
4311 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4312 SI1->getOperand(0),
4313 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004314 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4315 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004316 }
4317 }
Chris Lattner3af10532006-05-05 06:39:07 +00004318
Chris Lattner113f4f42002-06-25 16:13:24 +00004319 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004320}
4321
Chris Lattner6862fbd2004-09-29 17:40:11 +00004322static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004323 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004324}
4325
4326/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4327/// overflowed for this type.
4328static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4329 ConstantInt *In2) {
4330 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4331
Reid Spencerc635f472006-12-31 05:48:39 +00004332 return cast<ConstantInt>(Result)->getZExtValue() <
4333 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004334}
4335
Chris Lattner0798af32005-01-13 20:14:25 +00004336/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4337/// code necessary to compute the offset from the base pointer (without adding
4338/// in the base pointer). Return the result as a signed integer of intptr size.
4339static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4340 TargetData &TD = IC.getTargetData();
4341 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004342 const Type *IntPtrTy = TD.getIntPtrType();
4343 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004344
4345 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004346 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004347
Chris Lattner0798af32005-01-13 20:14:25 +00004348 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4349 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004350 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004351 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004352 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4353 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004354 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004355 Scale = ConstantExpr::getMul(OpC, Scale);
4356 if (Constant *RC = dyn_cast<Constant>(Result))
4357 Result = ConstantExpr::getAdd(RC, Scale);
4358 else {
4359 // Emit an add instruction.
4360 Result = IC.InsertNewInstBefore(
4361 BinaryOperator::createAdd(Result, Scale,
4362 GEP->getName()+".offs"), I);
4363 }
4364 }
4365 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004366 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004367 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004368 Op->getName()+".c"), I);
4369 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004370 // We'll let instcombine(mul) convert this to a shl if possible.
4371 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4372 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004373
4374 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004375 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004376 GEP->getName()+".offs"), I);
4377 }
4378 }
4379 return Result;
4380}
4381
Reid Spencer266e42b2006-12-23 06:05:41 +00004382/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004383/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004384Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4385 ICmpInst::Predicate Cond,
4386 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004387 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004388
4389 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4390 if (isa<PointerType>(CI->getOperand(0)->getType()))
4391 RHS = CI->getOperand(0);
4392
Chris Lattner0798af32005-01-13 20:14:25 +00004393 Value *PtrBase = GEPLHS->getOperand(0);
4394 if (PtrBase == RHS) {
4395 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004396 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4397 // each index is zero or not.
4398 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004399 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004400 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4401 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004402 bool EmitIt = true;
4403 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4404 if (isa<UndefValue>(C)) // undef index -> undef.
4405 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4406 if (C->isNullValue())
4407 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004408 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4409 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004410 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004411 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004412 ConstantInt::get(Type::Int1Ty,
4413 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004414 }
4415
4416 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004417 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004419 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4420 if (InVal == 0)
4421 InVal = Comp;
4422 else {
4423 InVal = InsertNewInstBefore(InVal, I);
4424 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004425 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004426 InVal = BinaryOperator::createOr(InVal, Comp);
4427 else // True if all are equal
4428 InVal = BinaryOperator::createAnd(InVal, Comp);
4429 }
4430 }
4431 }
4432
4433 if (InVal)
4434 return InVal;
4435 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004436 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004437 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4438 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004439 }
Chris Lattner0798af32005-01-13 20:14:25 +00004440
Reid Spencer266e42b2006-12-23 06:05:41 +00004441 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004442 // the result to fold to a constant!
4443 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4444 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4445 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004446 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4447 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004448 }
4449 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004450 // If the base pointers are different, but the indices are the same, just
4451 // compare the base pointer.
4452 if (PtrBase != GEPRHS->getOperand(0)) {
4453 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004454 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004455 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004456 if (IndicesTheSame)
4457 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4458 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4459 IndicesTheSame = false;
4460 break;
4461 }
4462
4463 // If all indices are the same, just compare the base pointers.
4464 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004465 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4466 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004467
4468 // Otherwise, the base pointers are different and the indices are
4469 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004470 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004471 }
Chris Lattner0798af32005-01-13 20:14:25 +00004472
Chris Lattner81e84172005-01-13 22:25:21 +00004473 // If one of the GEPs has all zero indices, recurse.
4474 bool AllZeros = true;
4475 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4476 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4477 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4478 AllZeros = false;
4479 break;
4480 }
4481 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004482 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4483 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004484
4485 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004486 AllZeros = true;
4487 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4488 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4489 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4490 AllZeros = false;
4491 break;
4492 }
4493 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004494 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004495
Chris Lattner4fa89822005-01-14 00:20:05 +00004496 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4497 // If the GEPs only differ by one index, compare it.
4498 unsigned NumDifferences = 0; // Keep track of # differences.
4499 unsigned DiffOperand = 0; // The operand that differs.
4500 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4501 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004502 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4503 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004504 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004505 NumDifferences = 2;
4506 break;
4507 } else {
4508 if (NumDifferences++) break;
4509 DiffOperand = i;
4510 }
4511 }
4512
4513 if (NumDifferences == 0) // SAME GEP?
4514 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004515 ConstantInt::get(Type::Int1Ty,
4516 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004517 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004518 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4519 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004520 // Make sure we do a signed comparison here.
4521 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004522 }
4523 }
4524
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004526 // the result to fold to a constant!
4527 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4528 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4529 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4530 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4531 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004532 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004533 }
4534 }
4535 return 0;
4536}
4537
Reid Spencer266e42b2006-12-23 06:05:41 +00004538Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4539 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004541
Chris Lattner6ee923f2007-01-14 19:42:17 +00004542 // Fold trivial predicates.
4543 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4544 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4545 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4546 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4547
4548 // Simplify 'fcmp pred X, X'
4549 if (Op0 == Op1) {
4550 switch (I.getPredicate()) {
4551 default: assert(0 && "Unknown predicate!");
4552 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4553 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4554 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4556 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4557 case FCmpInst::FCMP_OLT: // True if ordered and less than
4558 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4559 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4560
4561 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4562 case FCmpInst::FCMP_ULT: // True if unordered or less than
4563 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4564 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4565 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4566 I.setPredicate(FCmpInst::FCMP_UNO);
4567 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4568 return &I;
4569
4570 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4571 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4572 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4573 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4574 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4575 I.setPredicate(FCmpInst::FCMP_ORD);
4576 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4577 return &I;
4578 }
4579 }
4580
Reid Spencer266e42b2006-12-23 06:05:41 +00004581 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004582 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004583
Reid Spencer266e42b2006-12-23 06:05:41 +00004584 // Handle fcmp with constant RHS
4585 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4586 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4587 switch (LHSI->getOpcode()) {
4588 case Instruction::PHI:
4589 if (Instruction *NV = FoldOpIntoPhi(I))
4590 return NV;
4591 break;
4592 case Instruction::Select:
4593 // If either operand of the select is a constant, we can fold the
4594 // comparison into the select arms, which will cause one to be
4595 // constant folded and the select turned into a bitwise or.
4596 Value *Op1 = 0, *Op2 = 0;
4597 if (LHSI->hasOneUse()) {
4598 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4599 // Fold the known value into the constant operand.
4600 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4601 // Insert a new FCmp of the other select operand.
4602 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4603 LHSI->getOperand(2), RHSC,
4604 I.getName()), I);
4605 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4606 // Fold the known value into the constant operand.
4607 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4608 // Insert a new FCmp of the other select operand.
4609 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4610 LHSI->getOperand(1), RHSC,
4611 I.getName()), I);
4612 }
4613 }
4614
4615 if (Op1)
4616 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4617 break;
4618 }
4619 }
4620
4621 return Changed ? &I : 0;
4622}
4623
4624Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4625 bool Changed = SimplifyCompare(I);
4626 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4627 const Type *Ty = Op0->getType();
4628
4629 // icmp X, X
4630 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004631 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4632 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004633
4634 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004635 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004636
4637 // icmp of GlobalValues can never equal each other as long as they aren't
4638 // external weak linkage type.
4639 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4640 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4641 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004642 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4643 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004644
4645 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004646 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004647 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4648 isa<ConstantPointerNull>(Op0)) &&
4649 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004650 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004651 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4652 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004653
Reid Spencer266e42b2006-12-23 06:05:41 +00004654 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004655 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004656 switch (I.getPredicate()) {
4657 default: assert(0 && "Invalid icmp instruction!");
4658 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004659 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004660 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004661 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004662 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004663 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004664 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004665
Reid Spencer266e42b2006-12-23 06:05:41 +00004666 case ICmpInst::ICMP_UGT:
4667 case ICmpInst::ICMP_SGT:
4668 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004669 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004670 case ICmpInst::ICMP_ULT:
4671 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004672 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4673 InsertNewInstBefore(Not, I);
4674 return BinaryOperator::createAnd(Not, Op1);
4675 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004676 case ICmpInst::ICMP_UGE:
4677 case ICmpInst::ICMP_SGE:
4678 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004679 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004680 case ICmpInst::ICMP_ULE:
4681 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004682 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4683 InsertNewInstBefore(Not, I);
4684 return BinaryOperator::createOr(Not, Op1);
4685 }
4686 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004687 }
4688
Chris Lattner2dd01742004-06-09 04:24:29 +00004689 // See if we are doing a comparison between a constant and an instruction that
4690 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004691 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004692 switch (I.getPredicate()) {
4693 default: break;
4694 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4695 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004696 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004697 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4698 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4699 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4700 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4701 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004702
Reid Spencer266e42b2006-12-23 06:05:41 +00004703 case ICmpInst::ICMP_SLT:
4704 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004705 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004706 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4707 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4708 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4709 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4710 break;
4711
4712 case ICmpInst::ICMP_UGT:
4713 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004714 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004715 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4716 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4717 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4718 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4719 break;
4720
4721 case ICmpInst::ICMP_SGT:
4722 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004724 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4725 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4726 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4727 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4728 break;
4729
4730 case ICmpInst::ICMP_ULE:
4731 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004732 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004733 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4734 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4735 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4736 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4737 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004738
Reid Spencer266e42b2006-12-23 06:05:41 +00004739 case ICmpInst::ICMP_SLE:
4740 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004741 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004742 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4743 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4744 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4745 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4746 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004747
Reid Spencer266e42b2006-12-23 06:05:41 +00004748 case ICmpInst::ICMP_UGE:
4749 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004750 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004751 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4752 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4753 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4754 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4755 break;
4756
4757 case ICmpInst::ICMP_SGE:
4758 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004759 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004760 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4761 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4762 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4763 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4764 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004765 }
4766
Reid Spencer266e42b2006-12-23 06:05:41 +00004767 // If we still have a icmp le or icmp ge instruction, turn it into the
4768 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004769 // already been handled above, this requires little checking.
4770 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004771 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4772 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4773 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4774 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4775 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4776 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4777 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4778 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004779
4780 // See if we can fold the comparison based on bits known to be zero or one
4781 // in the input.
4782 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004783 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004784 KnownZero, KnownOne, 0))
4785 return &I;
4786
4787 // Given the known and unknown bits, compute a range that the LHS could be
4788 // in.
4789 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004790 // Compute the Min, Max and RHS values based on the known bits. For the
4791 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004792 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4793 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004794 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4795 SRHSVal = CI->getSExtValue();
4796 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4797 SMax);
4798 } else {
4799 URHSVal = CI->getZExtValue();
4800 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4801 UMax);
4802 }
4803 switch (I.getPredicate()) { // LE/GE have been folded already.
4804 default: assert(0 && "Unknown icmp opcode!");
4805 case ICmpInst::ICMP_EQ:
4806 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004807 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004808 break;
4809 case ICmpInst::ICMP_NE:
4810 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 break;
4813 case ICmpInst::ICMP_ULT:
4814 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004816 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004817 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004818 break;
4819 case ICmpInst::ICMP_UGT:
4820 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004821 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004822 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004823 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004824 break;
4825 case ICmpInst::ICMP_SLT:
4826 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004827 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004828 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004830 break;
4831 case ICmpInst::ICMP_SGT:
4832 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004833 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004834 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004835 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004836 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004837 }
4838 }
4839
Reid Spencer266e42b2006-12-23 06:05:41 +00004840 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004841 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004842 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004843 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004844 switch (LHSI->getOpcode()) {
4845 case Instruction::And:
4846 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4847 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004848 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4849
Reid Spencer266e42b2006-12-23 06:05:41 +00004850 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004851 // and/compare to be the input width without changing the value
4852 // produced, eliminating a cast.
4853 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4854 // We can do this transformation if either the AND constant does not
4855 // have its sign bit set or if it is an equality comparison.
4856 // Extending a relational comparison when we're checking the sign
4857 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004858 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004859 (I.isEquality() ||
4860 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4861 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4862 ConstantInt *NewCST;
4863 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004864 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4865 AndCST->getZExtValue());
4866 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4867 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004868 Instruction *NewAnd =
4869 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4870 LHSI->getName());
4871 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004873 }
4874 }
4875
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004876 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4877 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4878 // happens a LOT in code produced by the C front-end, for bitfield
4879 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004880 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4881 if (Shift && !Shift->isShift())
4882 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004883
Reid Spencere0fc4df2006-10-20 07:07:24 +00004884 ConstantInt *ShAmt;
4885 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004886 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4887 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004888
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004889 // We can fold this as long as we can't shift unknown bits
4890 // into the mask. This can only happen with signed shift
4891 // rights, as they sign-extend.
4892 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004893 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004894 if (!CanFold) {
4895 // To test for the bad case of the signed shr, see if any
4896 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004897 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004898 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4899
Reid Spencer2341c222007-02-02 02:16:23 +00004900 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004901 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004902 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4903 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004904 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4905 CanFold = true;
4906 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004907
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004908 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004909 Constant *NewCst;
4910 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004911 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004912 else
4913 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004914
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004915 // Check to see if we are shifting out any of the bits being
4916 // compared.
4917 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4918 // If we shifted bits out, the fold is not going to work out.
4919 // As a special case, check to see if this means that the
4920 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004922 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004923 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004925 } else {
4926 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004927 Constant *NewAndCST;
4928 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004929 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004930 else
4931 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4932 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004933 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004934 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004935 AddUsesToWorkList(I);
4936 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004937 }
4938 }
Chris Lattner35167c32004-06-09 07:59:58 +00004939 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004940
4941 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4942 // preferable because it allows the C<<Y expression to be hoisted out
4943 // of a loop if Y is invariant and X is not.
4944 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004945 I.isEquality() && !Shift->isArithmeticShift() &&
4946 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004947 // Compute C << Y.
4948 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004949 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004950 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004951 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004952 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004953 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004954 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004955 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004956 }
4957 InsertNewInstBefore(cast<Instruction>(NS), I);
4958
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004959 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004960 Instruction *NewAnd = BinaryOperator::createAnd(
4961 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004962 InsertNewInstBefore(NewAnd, I);
4963
4964 I.setOperand(0, NewAnd);
4965 return &I;
4966 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004967 }
4968 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004969
Reid Spencer266e42b2006-12-23 06:05:41 +00004970 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004971 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004972 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004973 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4974
4975 // Check that the shift amount is in range. If not, don't perform
4976 // undefined shifts. When the shift is visited it will be
4977 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004978 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004979 break;
4980
Chris Lattner272d5ca2004-09-28 18:22:15 +00004981 // If we are comparing against bits always shifted out, the
4982 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004983 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004984 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004985 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004986 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004987 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004988 return ReplaceInstUsesWith(I, Cst);
4989 }
4990
4991 if (LHSI->hasOneUse()) {
4992 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004993 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004994 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004995 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004996
Chris Lattner272d5ca2004-09-28 18:22:15 +00004997 Instruction *AndI =
4998 BinaryOperator::createAnd(LHSI->getOperand(0),
4999 Mask, LHSI->getName()+".mask");
5000 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005001 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00005002 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00005003 }
5004 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00005005 }
5006 break;
5007
Reid Spencer266e42b2006-12-23 06:05:41 +00005008 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00005009 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00005010 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005011 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005012 // Check that the shift amount is in range. If not, don't perform
5013 // undefined shifts. When the shift is visited it will be
5014 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00005015 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005016 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005017 break;
5018
Chris Lattner1023b872004-09-27 16:18:50 +00005019 // If we are comparing against bits always shifted out, the
5020 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00005021 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00005022 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00005023 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5024 ShAmt);
5025 else
5026 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5027 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005028
Chris Lattner1023b872004-09-27 16:18:50 +00005029 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005030 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005031 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00005032 return ReplaceInstUsesWith(I, Cst);
5033 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005034
Chris Lattner1023b872004-09-27 16:18:50 +00005035 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005036 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005037
Chris Lattner1023b872004-09-27 16:18:50 +00005038 // Otherwise strength reduce the shift into an and.
5039 uint64_t Val = ~0ULL; // All ones.
5040 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00005041 Val &= ~0ULL >> (64-TypeBits);
5042 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005043
Chris Lattner1023b872004-09-27 16:18:50 +00005044 Instruction *AndI =
5045 BinaryOperator::createAnd(LHSI->getOperand(0),
5046 Mask, LHSI->getName()+".mask");
5047 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00005049 ConstantExpr::getShl(CI, ShAmt));
5050 }
Chris Lattner1023b872004-09-27 16:18:50 +00005051 }
5052 }
5053 break;
Chris Lattner7e794272004-09-24 15:21:34 +00005054
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005055 case Instruction::SDiv:
5056 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005058 // Fold this div into the comparison, producing a range check.
5059 // Determine, based on the divide type, what the range is being
5060 // checked. If there is an overflow on the low or high side, remember
5061 // it, otherwise compute the range [low, hi) bounding the new value.
5062 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005063 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005064 // FIXME: If the operand types don't match the type of the divide
5065 // then don't attempt this transform. The code below doesn't have the
5066 // logic to deal with a signed divide and an unsigned compare (and
5067 // vice versa). This is because (x /s C1) <s C2 produces different
5068 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5069 // (x /u C1) <u C2. Simply casting the operands and result won't
5070 // work. :( The if statement below tests that condition and bails
5071 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00005072 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5073 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005074 break;
5075
5076 // Initialize the variables that will indicate the nature of the
5077 // range check.
5078 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005079 ConstantInt *LoBound = 0, *HiBound = 0;
5080
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005081 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5082 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5083 // C2 (CI). By solving for X we can turn this into a range check
5084 // instead of computing a divide.
5085 ConstantInt *Prod =
5086 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005087
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005088 // Determine if the product overflows by seeing if the product is
5089 // not equal to the divide. Make sure we do the same kind of divide
5090 // as in the LHS instruction that we're folding.
5091 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00005092 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005093 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
5094
Reid Spencer266e42b2006-12-23 06:05:41 +00005095 // Get the ICmp opcode
5096 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00005097
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005098 if (DivRHS->isNullValue()) {
5099 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00005100 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00005101 LoBound = Prod;
5102 LoOverflow = ProdOV;
5103 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005104 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005105 if (CI->isNullValue()) { // (X / pos) op 0
5106 // Can't overflow.
5107 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5108 HiBound = DivRHS;
5109 } else if (isPositive(CI)) { // (X / pos) op pos
5110 LoBound = Prod;
5111 LoOverflow = ProdOV;
5112 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
5113 } else { // (X / pos) op neg
5114 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5115 LoOverflow = AddWithOverflow(LoBound, Prod,
5116 cast<ConstantInt>(DivRHSH));
5117 HiBound = Prod;
5118 HiOverflow = ProdOV;
5119 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005120 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005121 if (CI->isNullValue()) { // (X / neg) op 0
5122 LoBound = AddOne(DivRHS);
5123 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005124 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005125 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00005126 } else if (isPositive(CI)) { // (X / neg) op pos
5127 HiOverflow = LoOverflow = ProdOV;
5128 if (!LoOverflow)
5129 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
5130 HiBound = AddOne(Prod);
5131 } else { // (X / neg) op neg
5132 LoBound = Prod;
5133 LoOverflow = HiOverflow = ProdOV;
5134 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5135 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005136
Chris Lattnera92af962004-10-11 19:40:04 +00005137 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005138 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005139 }
5140
5141 if (LoBound) {
5142 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005143 switch (predicate) {
5144 default: assert(0 && "Unhandled icmp opcode!");
5145 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005146 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005147 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005148 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005149 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5150 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005151 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005152 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5153 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005154 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005155 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5156 true, I);
5157 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005158 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005159 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005160 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005161 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5162 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005163 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005164 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5165 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005166 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005167 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5168 false, I);
5169 case ICmpInst::ICMP_ULT:
5170 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005171 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005172 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005173 return new ICmpInst(predicate, X, LoBound);
5174 case ICmpInst::ICMP_UGT:
5175 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005176 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005177 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005178 if (predicate == ICmpInst::ICMP_UGT)
5179 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5180 else
5181 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005182 }
5183 }
5184 }
5185 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005186 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005187
Reid Spencer266e42b2006-12-23 06:05:41 +00005188 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005189 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005190 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005191
Reid Spencere0fc4df2006-10-20 07:07:24 +00005192 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5193 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005194 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5195 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005196 case Instruction::SRem:
5197 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5198 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
5199 BO->hasOneUse()) {
5200 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
5201 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005202 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5203 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005204 return new ICmpInst(I.getPredicate(), NewRem,
5205 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005206 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005207 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005208 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005209 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005210 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5211 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005212 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005213 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5214 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005215 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005216 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5217 // efficiently invertible, or if the add has just this one use.
5218 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005219
Chris Lattnerc992add2003-08-13 05:33:12 +00005220 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005222 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005223 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005224 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005225 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005226 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005227 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005228 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005229 }
5230 }
5231 break;
5232 case Instruction::Xor:
5233 // For the xor case, we can xor two constants together, eliminating
5234 // the explicit xor.
5235 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005236 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5237 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005238
5239 // FALLTHROUGH
5240 case Instruction::Sub:
5241 // Replace (([sub|xor] A, B) != 0) with (A != B)
5242 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005243 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5244 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005245 break;
5246
5247 case Instruction::Or:
5248 // If bits are being or'd in that are not present in the constant we
5249 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005250 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005251 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005252 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005253 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5254 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005255 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005256 break;
5257
5258 case Instruction::And:
5259 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005260 // If bits are being compared against that are and'd out, then the
5261 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005262 if (!ConstantExpr::getAnd(CI,
5263 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005264 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5265 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005266
Chris Lattner35167c32004-06-09 07:59:58 +00005267 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005268 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005269 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5270 ICmpInst::ICMP_NE, Op0,
5271 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005272
Reid Spencer266e42b2006-12-23 06:05:41 +00005273 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005274 if (isSignBit(BOC)) {
5275 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005276 Constant *Zero = Constant::getNullValue(X->getType());
5277 ICmpInst::Predicate pred = isICMP_NE ?
5278 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5279 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005280 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005281
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005282 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005283 if (CI->isNullValue() && isHighOnes(BOC)) {
5284 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005285 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005286 ICmpInst::Predicate pred = isICMP_NE ?
5287 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5288 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005289 }
5290
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005291 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005292 default: break;
5293 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005294 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5295 // Handle set{eq|ne} <intrinsic>, intcst.
5296 switch (II->getIntrinsicID()) {
5297 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005298 case Intrinsic::bswap_i16:
5299 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005300 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005301 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005302 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005303 ByteSwap_16(CI->getZExtValue())));
5304 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005305 case Intrinsic::bswap_i32:
5306 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005307 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005308 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005309 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005310 ByteSwap_32(CI->getZExtValue())));
5311 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005312 case Intrinsic::bswap_i64:
5313 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005314 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005315 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005316 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005317 ByteSwap_64(CI->getZExtValue())));
5318 return &I;
5319 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005320 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005321 } else { // Not a ICMP_EQ/ICMP_NE
5322 // If the LHS is a cast from an integral value of the same size, then
5323 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005324 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5325 Value *CastOp = Cast->getOperand(0);
5326 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005327 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005328 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005329 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 // If this is an unsigned comparison, try to make the comparison use
5331 // smaller constant values.
5332 switch (I.getPredicate()) {
5333 default: break;
5334 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5335 ConstantInt *CUI = cast<ConstantInt>(CI);
5336 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5337 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005338 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005339 break;
5340 }
5341 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5342 ConstantInt *CUI = cast<ConstantInt>(CI);
5343 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5344 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5345 Constant::getNullValue(SrcTy));
5346 break;
5347 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005348 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005349
Chris Lattner2b55ea32004-02-23 07:16:20 +00005350 }
5351 }
Chris Lattnere967b342003-06-04 05:10:11 +00005352 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005353 }
5354
Reid Spencer266e42b2006-12-23 06:05:41 +00005355 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005356 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5357 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5358 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005359 case Instruction::GetElementPtr:
5360 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005361 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005362 bool isAllZeros = true;
5363 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5364 if (!isa<Constant>(LHSI->getOperand(i)) ||
5365 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5366 isAllZeros = false;
5367 break;
5368 }
5369 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005370 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005371 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5372 }
5373 break;
5374
Chris Lattner77c32c32005-04-23 15:31:55 +00005375 case Instruction::PHI:
5376 if (Instruction *NV = FoldOpIntoPhi(I))
5377 return NV;
5378 break;
5379 case Instruction::Select:
5380 // If either operand of the select is a constant, we can fold the
5381 // comparison into the select arms, which will cause one to be
5382 // constant folded and the select turned into a bitwise or.
5383 Value *Op1 = 0, *Op2 = 0;
5384 if (LHSI->hasOneUse()) {
5385 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5386 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005387 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5388 // Insert a new ICmp of the other select operand.
5389 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5390 LHSI->getOperand(2), RHSC,
5391 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005392 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5393 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005394 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5395 // Insert a new ICmp of the other select operand.
5396 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5397 LHSI->getOperand(1), RHSC,
5398 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005399 }
5400 }
Jeff Cohen82639852005-04-23 21:38:35 +00005401
Chris Lattner77c32c32005-04-23 15:31:55 +00005402 if (Op1)
5403 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5404 break;
5405 }
5406 }
5407
Reid Spencer266e42b2006-12-23 06:05:41 +00005408 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005409 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005410 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005411 return NI;
5412 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005413 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5414 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005415 return NI;
5416
Reid Spencer266e42b2006-12-23 06:05:41 +00005417 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005418 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5419 // now.
5420 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5421 if (isa<PointerType>(Op0->getType()) &&
5422 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005423 // We keep moving the cast from the left operand over to the right
5424 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005425 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005426
Chris Lattner64d87b02007-01-06 01:45:59 +00005427 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5428 // so eliminate it as well.
5429 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5430 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005431
Chris Lattner16930792003-11-03 04:25:02 +00005432 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005433 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005434 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005435 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005436 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005437 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005438 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005439 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005440 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005441 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005442 }
5443
5444 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005445 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005446 // This comes up when you have code like
5447 // int X = A < B;
5448 // if (X) ...
5449 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005450 // with a constant or another cast from the same type.
5451 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005452 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005453 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005454 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005455
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005456 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005457 Value *A, *B, *C, *D;
5458 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5459 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5460 Value *OtherVal = A == Op1 ? B : A;
5461 return new ICmpInst(I.getPredicate(), OtherVal,
5462 Constant::getNullValue(A->getType()));
5463 }
5464
5465 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5466 // A^c1 == C^c2 --> A == C^(c1^c2)
5467 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5468 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5469 if (Op1->hasOneUse()) {
5470 Constant *NC = ConstantExpr::getXor(C1, C2);
5471 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5472 return new ICmpInst(I.getPredicate(), A,
5473 InsertNewInstBefore(Xor, I));
5474 }
5475
5476 // A^B == A^D -> B == D
5477 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5478 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5479 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5480 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5481 }
5482 }
5483
5484 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5485 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005486 // A == (A^B) -> B == 0
5487 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005488 return new ICmpInst(I.getPredicate(), OtherVal,
5489 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005490 }
5491 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005492 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005493 return new ICmpInst(I.getPredicate(), B,
5494 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005495 }
5496 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005497 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005498 return new ICmpInst(I.getPredicate(), B,
5499 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005500 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005501
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005502 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5503 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5504 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5505 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5506 Value *X = 0, *Y = 0, *Z = 0;
5507
5508 if (A == C) {
5509 X = B; Y = D; Z = A;
5510 } else if (A == D) {
5511 X = B; Y = C; Z = A;
5512 } else if (B == C) {
5513 X = A; Y = D; Z = B;
5514 } else if (B == D) {
5515 X = A; Y = C; Z = B;
5516 }
5517
5518 if (X) { // Build (X^Y) & Z
5519 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5520 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5521 I.setOperand(0, Op1);
5522 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5523 return &I;
5524 }
5525 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005526 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005527 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005528}
5529
Reid Spencer266e42b2006-12-23 06:05:41 +00005530// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005531// We only handle extending casts so far.
5532//
Reid Spencer266e42b2006-12-23 06:05:41 +00005533Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5534 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005535 Value *LHSCIOp = LHSCI->getOperand(0);
5536 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005537 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005538 Value *RHSCIOp;
5539
Reid Spencer266e42b2006-12-23 06:05:41 +00005540 // We only handle extension cast instructions, so far. Enforce this.
5541 if (LHSCI->getOpcode() != Instruction::ZExt &&
5542 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005543 return 0;
5544
Reid Spencer266e42b2006-12-23 06:05:41 +00005545 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5546 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005547
Reid Spencer266e42b2006-12-23 06:05:41 +00005548 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005549 // Not an extension from the same type?
5550 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005551 if (RHSCIOp->getType() != LHSCIOp->getType())
5552 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005553
5554 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5555 // and the other is a zext), then we can't handle this.
5556 if (CI->getOpcode() != LHSCI->getOpcode())
5557 return 0;
5558
5559 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5560 // then we can't handle this.
5561 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5562 return 0;
5563
5564 // Okay, just insert a compare of the reduced operands now!
5565 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005566 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005567
Reid Spencer266e42b2006-12-23 06:05:41 +00005568 // If we aren't dealing with a constant on the RHS, exit early
5569 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5570 if (!CI)
5571 return 0;
5572
5573 // Compute the constant that would happen if we truncated to SrcTy then
5574 // reextended to DestTy.
5575 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5576 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5577
5578 // If the re-extended constant didn't change...
5579 if (Res2 == CI) {
5580 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5581 // For example, we might have:
5582 // %A = sext short %X to uint
5583 // %B = icmp ugt uint %A, 1330
5584 // It is incorrect to transform this into
5585 // %B = icmp ugt short %X, 1330
5586 // because %A may have negative value.
5587 //
5588 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5589 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005590 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005591 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5592 else
5593 return 0;
5594 }
5595
5596 // The re-extended constant changed so the constant cannot be represented
5597 // in the shorter type. Consequently, we cannot emit a simple comparison.
5598
5599 // First, handle some easy cases. We know the result cannot be equal at this
5600 // point so handle the ICI.isEquality() cases
5601 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005602 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005603 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005604 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005605
5606 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5607 // should have been folded away previously and not enter in here.
5608 Value *Result;
5609 if (isSignedCmp) {
5610 // We're performing a signed comparison.
5611 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005612 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005613 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005614 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005615 } else {
5616 // We're performing an unsigned comparison.
5617 if (isSignedExt) {
5618 // We're performing an unsigned comp with a sign extended value.
5619 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005620 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005621 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5622 NegOne, ICI.getName()), ICI);
5623 } else {
5624 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005625 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005626 }
5627 }
5628
5629 // Finally, return the value computed.
5630 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5631 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5632 return ReplaceInstUsesWith(ICI, Result);
5633 } else {
5634 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5635 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5636 "ICmp should be folded!");
5637 if (Constant *CI = dyn_cast<Constant>(Result))
5638 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5639 else
5640 return BinaryOperator::createNot(Result);
5641 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005642}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005643
Reid Spencer2341c222007-02-02 02:16:23 +00005644Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5645 return commonShiftTransforms(I);
5646}
5647
5648Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5649 return commonShiftTransforms(I);
5650}
5651
5652Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5653 return commonShiftTransforms(I);
5654}
5655
5656Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5657 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005659
5660 // shl X, 0 == X and shr X, 0 == X
5661 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005662 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005663 Op0 == Constant::getNullValue(Op0->getType()))
5664 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005665
Reid Spencer266e42b2006-12-23 06:05:41 +00005666 if (isa<UndefValue>(Op0)) {
5667 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005668 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005669 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005670 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5671 }
5672 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005673 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5674 return ReplaceInstUsesWith(I, Op0);
5675 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005676 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005677 }
5678
Chris Lattnerd4dee402006-11-10 23:38:52 +00005679 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5680 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005681 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005682 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005683 return ReplaceInstUsesWith(I, CSI);
5684
Chris Lattner183b3362004-04-09 19:05:30 +00005685 // Try to fold constant and into select arguments.
5686 if (isa<Constant>(Op0))
5687 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005688 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005689 return R;
5690
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005691 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005692 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005693 if (MaskedValueIsZero(Op0,
5694 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005695 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005696 }
5697 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005698
Reid Spencere0fc4df2006-10-20 07:07:24 +00005699 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005700 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5701 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005702 return 0;
5703}
5704
Reid Spencere0fc4df2006-10-20 07:07:24 +00005705Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005706 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005707 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005708
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005709 // See if we can simplify any instructions used by the instruction whose sole
5710 // purpose is to compute bits we don't care about.
5711 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005712 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005713 KnownZero, KnownOne))
5714 return &I;
5715
Chris Lattner14553932006-01-06 07:12:35 +00005716 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5717 // of a signed value.
5718 //
5719 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005720 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005721 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005722 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5723 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005724 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005725 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005726 }
Chris Lattner14553932006-01-06 07:12:35 +00005727 }
5728
5729 // ((X*C1) << C2) == (X * (C1 << C2))
5730 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5731 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5732 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5733 return BinaryOperator::createMul(BO->getOperand(0),
5734 ConstantExpr::getShl(BOOp, Op1));
5735
5736 // Try to fold constant and into select arguments.
5737 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5738 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5739 return R;
5740 if (isa<PHINode>(Op0))
5741 if (Instruction *NV = FoldOpIntoPhi(I))
5742 return NV;
5743
5744 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005745 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5746 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5747 Value *V1, *V2;
5748 ConstantInt *CC;
5749 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005750 default: break;
5751 case Instruction::Add:
5752 case Instruction::And:
5753 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005754 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005755 // These operators commute.
5756 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005757 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5758 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005759 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005760 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005761 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005762 Op0BO->getName());
5763 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005764 Instruction *X =
5765 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5766 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005767 InsertNewInstBefore(X, I); // (X + (Y << C))
5768 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005769 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005770 return BinaryOperator::createAnd(X, C2);
5771 }
Chris Lattner14553932006-01-06 07:12:35 +00005772
Chris Lattner797dee72005-09-18 06:30:59 +00005773 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005774 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005775 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005776 match(Op0BOOp1,
5777 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005778 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5779 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005780 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005781 Op0BO->getOperand(0), Op1,
5782 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005783 InsertNewInstBefore(YS, I); // (Y << C)
5784 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005785 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005786 V1->getName()+".mask");
5787 InsertNewInstBefore(XM, I); // X & (CC << C)
5788
5789 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5790 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005791 }
Chris Lattner14553932006-01-06 07:12:35 +00005792
Reid Spencer2f34b982007-02-02 14:41:37 +00005793 // FALL THROUGH.
5794 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005795 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005796 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5797 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005798 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005799 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005800 Op0BO->getOperand(1), Op1,
5801 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005802 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005803 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005804 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005805 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005806 InsertNewInstBefore(X, I); // (X + (Y << C))
5807 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005808 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005809 return BinaryOperator::createAnd(X, C2);
5810 }
Chris Lattner14553932006-01-06 07:12:35 +00005811
Chris Lattner1df0e982006-05-31 21:14:00 +00005812 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005813 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5814 match(Op0BO->getOperand(0),
5815 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005816 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005817 cast<BinaryOperator>(Op0BO->getOperand(0))
5818 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005819 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005820 Op0BO->getOperand(1), Op1,
5821 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005822 InsertNewInstBefore(YS, I); // (Y << C)
5823 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005824 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005825 V1->getName()+".mask");
5826 InsertNewInstBefore(XM, I); // X & (CC << C)
5827
Chris Lattner1df0e982006-05-31 21:14:00 +00005828 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005829 }
Chris Lattner14553932006-01-06 07:12:35 +00005830
Chris Lattner27cb9db2005-09-18 05:12:10 +00005831 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005832 }
Chris Lattner14553932006-01-06 07:12:35 +00005833 }
5834
5835
5836 // If the operand is an bitwise operator with a constant RHS, and the
5837 // shift is the only use, we can pull it out of the shift.
5838 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5839 bool isValid = true; // Valid only for And, Or, Xor
5840 bool highBitSet = false; // Transform if high bit of constant set?
5841
5842 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005843 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005844 case Instruction::Add:
5845 isValid = isLeftShift;
5846 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005847 case Instruction::Or:
5848 case Instruction::Xor:
5849 highBitSet = false;
5850 break;
5851 case Instruction::And:
5852 highBitSet = true;
5853 break;
Chris Lattner14553932006-01-06 07:12:35 +00005854 }
5855
5856 // If this is a signed shift right, and the high bit is modified
5857 // by the logical operation, do not perform the transformation.
5858 // The highBitSet boolean indicates the value of the high bit of
5859 // the constant which would cause it to be modified for this
5860 // operation.
5861 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005862 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005863 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005864 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5865 }
5866
5867 if (isValid) {
5868 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5869
5870 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005871 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005872 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005873 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005874
5875 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5876 NewRHS);
5877 }
5878 }
5879 }
5880 }
5881
Chris Lattnereb372a02006-01-06 07:52:12 +00005882 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005883 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5884 if (ShiftOp && !ShiftOp->isShift())
5885 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005886
Reid Spencere0fc4df2006-10-20 07:07:24 +00005887 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005888 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00005889 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5890 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005891 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5892 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5893 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005894
Chris Lattner3e009e82007-02-05 00:57:54 +00005895 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5896 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5897 AmtSum = I.getType()->getPrimitiveSizeInBits();
5898
5899 const IntegerType *Ty = cast<IntegerType>(I.getType());
5900
5901 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005902 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005903 return BinaryOperator::create(I.getOpcode(), X,
5904 ConstantInt::get(Ty, AmtSum));
5905 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5906 I.getOpcode() == Instruction::AShr) {
5907 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5908 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5909 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5910 I.getOpcode() == Instruction::LShr) {
5911 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5912 Instruction *Shift =
5913 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5914 InsertNewInstBefore(Shift, I);
5915
5916 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5917 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005918 }
5919
Chris Lattner3e009e82007-02-05 00:57:54 +00005920 // Okay, if we get here, one shift must be left, and the other shift must be
5921 // right. See if the amounts are equal.
5922 if (ShiftAmt1 == ShiftAmt2) {
5923 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5924 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005925 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005926 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5927 }
5928 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5929 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005930 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005931 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5932 }
5933 // We can simplify ((X << C) >>s C) into a trunc + sext.
5934 // NOTE: we could do this for any C, but that would make 'unusual' integer
5935 // types. For now, just stick to ones well-supported by the code
5936 // generators.
5937 const Type *SExtType = 0;
5938 switch (Ty->getBitWidth() - ShiftAmt1) {
5939 case 8 : SExtType = Type::Int8Ty; break;
5940 case 16: SExtType = Type::Int16Ty; break;
5941 case 32: SExtType = Type::Int32Ty; break;
5942 default: break;
5943 }
5944 if (SExtType) {
5945 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5946 InsertNewInstBefore(NewTrunc, I);
5947 return new SExtInst(NewTrunc, Ty);
5948 }
5949 // Otherwise, we can't handle it yet.
5950 } else if (ShiftAmt1 < ShiftAmt2) {
5951 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005952
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005953 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005954 if (I.getOpcode() == Instruction::Shl) {
5955 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5956 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005957 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005958 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005959 InsertNewInstBefore(Shift, I);
5960
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005961 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005962 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005963 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005964
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005965 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005966 if (I.getOpcode() == Instruction::LShr) {
5967 assert(ShiftOp->getOpcode() == Instruction::Shl);
5968 Instruction *Shift =
5969 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5970 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005971
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005972 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005973 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005974 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005975
5976 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5977 } else {
5978 assert(ShiftAmt2 < ShiftAmt1);
5979 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5980
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005981 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005982 if (I.getOpcode() == Instruction::Shl) {
5983 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5984 ShiftOp->getOpcode() == Instruction::AShr);
5985 Instruction *Shift =
5986 BinaryOperator::create(ShiftOp->getOpcode(), X,
5987 ConstantInt::get(Ty, ShiftDiff));
5988 InsertNewInstBefore(Shift, I);
5989
5990 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5991 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5992 }
5993
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005994 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005995 if (I.getOpcode() == Instruction::LShr) {
5996 assert(ShiftOp->getOpcode() == Instruction::Shl);
5997 Instruction *Shift =
5998 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5999 InsertNewInstBefore(Shift, I);
6000
6001 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
6002 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
6003 }
6004
6005 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006006 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006007 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006008 return 0;
6009}
6010
Chris Lattner48a44f72002-05-02 17:06:02 +00006011
Chris Lattner8f663e82005-10-29 04:36:15 +00006012/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6013/// expression. If so, decompose it, returning some value X, such that Val is
6014/// X*Scale+Offset.
6015///
6016static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6017 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006018 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006019 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006020 Offset = CI->getZExtValue();
6021 Scale = 1;
6022 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006023 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6024 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006025 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006026 if (I->getOpcode() == Instruction::Shl) {
6027 // This is a value scaled by '1 << the shift amt'.
6028 Scale = 1U << CUI->getZExtValue();
6029 Offset = 0;
6030 return I->getOperand(0);
6031 } else if (I->getOpcode() == Instruction::Mul) {
6032 // This value is scaled by 'CUI'.
6033 Scale = CUI->getZExtValue();
6034 Offset = 0;
6035 return I->getOperand(0);
6036 } else if (I->getOpcode() == Instruction::Add) {
6037 // We have X+C. Check to see if we really have (X*C2)+C1,
6038 // where C1 is divisible by C2.
6039 unsigned SubScale;
6040 Value *SubVal =
6041 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6042 Offset += CUI->getZExtValue();
6043 if (SubScale > 1 && (Offset % SubScale == 0)) {
6044 Scale = SubScale;
6045 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006046 }
6047 }
6048 }
6049 }
6050 }
6051
6052 // Otherwise, we can't look past this.
6053 Scale = 1;
6054 Offset = 0;
6055 return Val;
6056}
6057
6058
Chris Lattner216be912005-10-24 06:03:58 +00006059/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6060/// try to eliminate the cast by moving the type information into the alloc.
6061Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6062 AllocationInst &AI) {
6063 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006064 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006065
Chris Lattnerac87beb2005-10-24 06:22:12 +00006066 // Remove any uses of AI that are dead.
6067 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006068
Chris Lattnerac87beb2005-10-24 06:22:12 +00006069 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6070 Instruction *User = cast<Instruction>(*UI++);
6071 if (isInstructionTriviallyDead(User)) {
6072 while (UI != E && *UI == User)
6073 ++UI; // If this instruction uses AI more than once, don't break UI.
6074
Chris Lattnerac87beb2005-10-24 06:22:12 +00006075 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006076 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006077 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006078 }
6079 }
6080
Chris Lattner216be912005-10-24 06:03:58 +00006081 // Get the type really allocated and the type casted to.
6082 const Type *AllocElTy = AI.getAllocatedType();
6083 const Type *CastElTy = PTy->getElementType();
6084 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006085
Chris Lattner945e4372007-02-14 05:52:17 +00006086 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6087 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006088 if (CastElTyAlign < AllocElTyAlign) return 0;
6089
Chris Lattner46705b22005-10-24 06:35:18 +00006090 // If the allocation has multiple uses, only promote it if we are strictly
6091 // increasing the alignment of the resultant allocation. If we keep it the
6092 // same, we open the door to infinite loops of various kinds.
6093 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6094
Chris Lattner216be912005-10-24 06:03:58 +00006095 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6096 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006097 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006098
Chris Lattner8270c332005-10-29 03:19:53 +00006099 // See if we can satisfy the modulus by pulling a scale out of the array
6100 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006101 unsigned ArraySizeScale, ArrayOffset;
6102 Value *NumElements = // See if the array size is a decomposable linear expr.
6103 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6104
Chris Lattner8270c332005-10-29 03:19:53 +00006105 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6106 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006107 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6108 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006109
Chris Lattner8270c332005-10-29 03:19:53 +00006110 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6111 Value *Amt = 0;
6112 if (Scale == 1) {
6113 Amt = NumElements;
6114 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006115 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006116 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6117 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006118 Amt = ConstantExpr::getMul(
6119 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6120 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006121 else if (Scale != 1) {
6122 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6123 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006124 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006125 }
6126
Chris Lattner8f663e82005-10-29 04:36:15 +00006127 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006128 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006129 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6130 Amt = InsertNewInstBefore(Tmp, AI);
6131 }
6132
Chris Lattner216be912005-10-24 06:03:58 +00006133 AllocationInst *New;
6134 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006135 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006136 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006137 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006138 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006139 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006140
6141 // If the allocation has multiple uses, insert a cast and change all things
6142 // that used it to use the new cast. This will also hack on CI, but it will
6143 // die soon.
6144 if (!AI.hasOneUse()) {
6145 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006146 // New is the allocation instruction, pointer typed. AI is the original
6147 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6148 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006149 InsertNewInstBefore(NewCast, AI);
6150 AI.replaceAllUsesWith(NewCast);
6151 }
Chris Lattner216be912005-10-24 06:03:58 +00006152 return ReplaceInstUsesWith(CI, New);
6153}
6154
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006155/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006156/// and return it as type Ty without inserting any new casts and without
6157/// changing the computed value. This is used by code that tries to decide
6158/// whether promoting or shrinking integer operations to wider or smaller types
6159/// will allow us to eliminate a truncate or extend.
6160///
6161/// This is a truncation operation if Ty is smaller than V->getType(), or an
6162/// extension operation if Ty is larger.
6163static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006164 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006165 // We can always evaluate constants in another type.
6166 if (isa<ConstantInt>(V))
6167 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006168
6169 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006170 if (!I) return false;
6171
6172 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006173
6174 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006175 case Instruction::Add:
6176 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006177 case Instruction::And:
6178 case Instruction::Or:
6179 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006180 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006181 // These operators can all arbitrarily be extended or truncated.
6182 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6183 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006184
Chris Lattner960acb02006-11-29 07:18:39 +00006185 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006186 if (!I->hasOneUse()) return false;
6187 // If we are truncating the result of this SHL, and if it's a shift of a
6188 // constant amount, we can always perform a SHL in a smaller type.
6189 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6190 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6191 CI->getZExtValue() < Ty->getBitWidth())
6192 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6193 }
6194 break;
6195 case Instruction::LShr:
6196 if (!I->hasOneUse()) return false;
6197 // If this is a truncate of a logical shr, we can truncate it to a smaller
6198 // lshr iff we know that the bits we would otherwise be shifting in are
6199 // already zeros.
6200 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6201 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6202 MaskedValueIsZero(I->getOperand(0),
6203 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
6204 CI->getZExtValue() < Ty->getBitWidth()) {
6205 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6206 }
6207 }
Chris Lattner960acb02006-11-29 07:18:39 +00006208 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006209 case Instruction::Trunc:
6210 case Instruction::ZExt:
6211 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006212 // If this is a cast from the destination type, we can trivially eliminate
6213 // it, and this will remove a cast overall.
6214 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006215 // If the first operand is itself a cast, and is eliminable, do not count
6216 // this as an eliminable cast. We would prefer to eliminate those two
6217 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006218 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006219 return true;
6220
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006221 ++NumCastsRemoved;
6222 return true;
6223 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006224 break;
6225 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006226 // TODO: Can handle more cases here.
6227 break;
6228 }
6229
6230 return false;
6231}
6232
6233/// EvaluateInDifferentType - Given an expression that
6234/// CanEvaluateInDifferentType returns true for, actually insert the code to
6235/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006236Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006237 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006238 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006239 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006240
6241 // Otherwise, it must be an instruction.
6242 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006243 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006244 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006245 case Instruction::Add:
6246 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006247 case Instruction::And:
6248 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006249 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006250 case Instruction::AShr:
6251 case Instruction::LShr:
6252 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006253 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006254 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6255 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6256 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006257 break;
6258 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006259 case Instruction::Trunc:
6260 case Instruction::ZExt:
6261 case Instruction::SExt:
6262 case Instruction::BitCast:
6263 // If the source type of the cast is the type we're trying for then we can
6264 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006265 if (I->getOperand(0)->getType() == Ty)
6266 return I->getOperand(0);
6267
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006268 // Some other kind of cast, which shouldn't happen, so just ..
6269 // FALL THROUGH
6270 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006271 // TODO: Can handle more cases here.
6272 assert(0 && "Unreachable!");
6273 break;
6274 }
6275
6276 return InsertNewInstBefore(Res, *I);
6277}
6278
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006279/// @brief Implement the transforms common to all CastInst visitors.
6280Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006281 Value *Src = CI.getOperand(0);
6282
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006283 // Casting undef to anything results in undef so might as just replace it and
6284 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006285 if (isa<UndefValue>(Src)) // cast undef -> undef
6286 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6287
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006288 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6289 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006290 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006291 if (Instruction::CastOps opc =
6292 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6293 // The first cast (CSrc) is eliminable so we need to fix up or replace
6294 // the second cast (CI). CSrc will then have a good chance of being dead.
6295 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006296 }
6297 }
Chris Lattner03841652004-05-25 04:29:21 +00006298
Chris Lattnerd0d51602003-06-21 23:12:02 +00006299 // If casting the result of a getelementptr instruction with no offset, turn
6300 // this into a cast of the original pointer!
6301 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006302 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006303 bool AllZeroOperands = true;
6304 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6305 if (!isa<Constant>(GEP->getOperand(i)) ||
6306 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6307 AllZeroOperands = false;
6308 break;
6309 }
6310 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006311 // Changing the cast operand is usually not a good idea but it is safe
6312 // here because the pointer operand is being replaced with another
6313 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006314 CI.setOperand(0, GEP->getOperand(0));
6315 return &CI;
6316 }
6317 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006318
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006319 // If we are casting a malloc or alloca to a pointer to a type of the same
6320 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006321 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006322 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6323 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006324
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006325 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006326 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6327 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6328 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006329
6330 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006331 if (isa<PHINode>(Src))
6332 if (Instruction *NV = FoldOpIntoPhi(CI))
6333 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006334
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006335 return 0;
6336}
6337
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006338/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6339/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006340/// cases.
6341/// @brief Implement the transforms common to CastInst with integer operands
6342Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6343 if (Instruction *Result = commonCastTransforms(CI))
6344 return Result;
6345
6346 Value *Src = CI.getOperand(0);
6347 const Type *SrcTy = Src->getType();
6348 const Type *DestTy = CI.getType();
6349 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6350 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6351
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006352 // See if we can simplify any instructions used by the LHS whose sole
6353 // purpose is to compute bits we don't care about.
6354 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006355 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006356 KnownZero, KnownOne))
6357 return &CI;
6358
6359 // If the source isn't an instruction or has more than one use then we
6360 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006361 Instruction *SrcI = dyn_cast<Instruction>(Src);
6362 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006363 return 0;
6364
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006365 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006366 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006367 if (!isa<BitCastInst>(CI) &&
6368 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6369 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006370 // If this cast is a truncate, evaluting in a different type always
6371 // eliminates the cast, so it is always a win. If this is a noop-cast
6372 // this just removes a noop cast which isn't pointful, but simplifies
6373 // the code. If this is a zero-extension, we need to do an AND to
6374 // maintain the clear top-part of the computation, so we require that
6375 // the input have eliminated at least one cast. If this is a sign
6376 // extension, we insert two new casts (to do the extension) so we
6377 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006378 bool DoXForm;
6379 switch (CI.getOpcode()) {
6380 default:
6381 // All the others use floating point so we shouldn't actually
6382 // get here because of the check above.
6383 assert(0 && "Unknown cast type");
6384 case Instruction::Trunc:
6385 DoXForm = true;
6386 break;
6387 case Instruction::ZExt:
6388 DoXForm = NumCastsRemoved >= 1;
6389 break;
6390 case Instruction::SExt:
6391 DoXForm = NumCastsRemoved >= 2;
6392 break;
6393 case Instruction::BitCast:
6394 DoXForm = false;
6395 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006396 }
6397
6398 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006399 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6400 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006401 assert(Res->getType() == DestTy);
6402 switch (CI.getOpcode()) {
6403 default: assert(0 && "Unknown cast type!");
6404 case Instruction::Trunc:
6405 case Instruction::BitCast:
6406 // Just replace this cast with the result.
6407 return ReplaceInstUsesWith(CI, Res);
6408 case Instruction::ZExt: {
6409 // We need to emit an AND to clear the high bits.
6410 assert(SrcBitSize < DestBitSize && "Not a zext?");
6411 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006412 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006413 if (DestBitSize < 64)
6414 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006415 return BinaryOperator::createAnd(Res, C);
6416 }
6417 case Instruction::SExt:
6418 // We need to emit a cast to truncate, then a cast to sext.
6419 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006420 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6421 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006422 }
6423 }
6424 }
6425
6426 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6427 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6428
6429 switch (SrcI->getOpcode()) {
6430 case Instruction::Add:
6431 case Instruction::Mul:
6432 case Instruction::And:
6433 case Instruction::Or:
6434 case Instruction::Xor:
6435 // If we are discarding information, or just changing the sign,
6436 // rewrite.
6437 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6438 // Don't insert two casts if they cannot be eliminated. We allow
6439 // two casts to be inserted if the sizes are the same. This could
6440 // only be converting signedness, which is a noop.
6441 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006442 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6443 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006444 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006445 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6446 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6447 return BinaryOperator::create(
6448 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006449 }
6450 }
6451
6452 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6453 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6454 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006455 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006456 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006457 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006458 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6459 }
6460 break;
6461 case Instruction::SDiv:
6462 case Instruction::UDiv:
6463 case Instruction::SRem:
6464 case Instruction::URem:
6465 // If we are just changing the sign, rewrite.
6466 if (DestBitSize == SrcBitSize) {
6467 // Don't insert two casts if they cannot be eliminated. We allow
6468 // two casts to be inserted if the sizes are the same. This could
6469 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006470 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6471 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006472 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6473 Op0, DestTy, SrcI);
6474 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6475 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006476 return BinaryOperator::create(
6477 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6478 }
6479 }
6480 break;
6481
6482 case Instruction::Shl:
6483 // Allow changing the sign of the source operand. Do not allow
6484 // changing the size of the shift, UNLESS the shift amount is a
6485 // constant. We must not change variable sized shifts to a smaller
6486 // size, because it is undefined to shift more bits out than exist
6487 // in the value.
6488 if (DestBitSize == SrcBitSize ||
6489 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006490 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6491 Instruction::BitCast : Instruction::Trunc);
6492 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006493 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006494 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006495 }
6496 break;
6497 case Instruction::AShr:
6498 // If this is a signed shr, and if all bits shifted in are about to be
6499 // truncated off, turn it into an unsigned shr to allow greater
6500 // simplifications.
6501 if (DestBitSize < SrcBitSize &&
6502 isa<ConstantInt>(Op1)) {
6503 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6504 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6505 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006506 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006507 }
6508 }
6509 break;
6510
Reid Spencer266e42b2006-12-23 06:05:41 +00006511 case Instruction::ICmp:
6512 // If we are just checking for a icmp eq of a single bit and casting it
6513 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006514 // cast to integer to avoid the comparison.
6515 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6516 uint64_t Op1CV = Op1C->getZExtValue();
6517 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6518 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6519 // cast (X == 1) to int --> X iff X has only the low bit set.
6520 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6521 // cast (X != 0) to int --> X iff X has only the low bit set.
6522 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6523 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6524 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6525 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6526 // If Op1C some other power of two, convert:
6527 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006528 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006529 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006530
6531 // This only works for EQ and NE
6532 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6533 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6534 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006535
6536 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006537 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006538 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6539 // (X&4) == 2 --> false
6540 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006541 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006542 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006543 return ReplaceInstUsesWith(CI, Res);
6544 }
6545
6546 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6547 Value *In = Op0;
6548 if (ShiftAmt) {
6549 // Perform a logical shr by shiftamt.
6550 // Insert the shift to put the result in the low bit.
6551 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006552 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006553 ConstantInt::get(In->getType(), ShiftAmt),
6554 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006555 }
6556
Reid Spencer266e42b2006-12-23 06:05:41 +00006557 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006558 Constant *One = ConstantInt::get(In->getType(), 1);
6559 In = BinaryOperator::createXor(In, One, "tmp");
6560 InsertNewInstBefore(cast<Instruction>(In), CI);
6561 }
6562
6563 if (CI.getType() == In->getType())
6564 return ReplaceInstUsesWith(CI, In);
6565 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006566 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006567 }
6568 }
6569 }
6570 break;
6571 }
6572 return 0;
6573}
6574
6575Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006576 if (Instruction *Result = commonIntCastTransforms(CI))
6577 return Result;
6578
6579 Value *Src = CI.getOperand(0);
6580 const Type *Ty = CI.getType();
6581 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6582
6583 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6584 switch (SrcI->getOpcode()) {
6585 default: break;
6586 case Instruction::LShr:
6587 // We can shrink lshr to something smaller if we know the bits shifted in
6588 // are already zeros.
6589 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6590 unsigned ShAmt = ShAmtV->getZExtValue();
6591
6592 // Get a mask for the bits shifting in.
6593 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006594 Value* SrcIOp0 = SrcI->getOperand(0);
6595 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006596 if (ShAmt >= DestBitWidth) // All zeros.
6597 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6598
6599 // Okay, we can shrink this. Truncate the input, then return a new
6600 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006601 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6602 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6603 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006604 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006605 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006606 } else { // This is a variable shr.
6607
6608 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6609 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6610 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006611 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006612 Value *One = ConstantInt::get(SrcI->getType(), 1);
6613
Reid Spencer2341c222007-02-02 02:16:23 +00006614 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006615 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006616 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006617 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6618 SrcI->getOperand(0),
6619 "tmp"), CI);
6620 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006621 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006622 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006623 }
6624 break;
6625 }
6626 }
6627
6628 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006629}
6630
6631Instruction *InstCombiner::visitZExt(CastInst &CI) {
6632 // If one of the common conversion will work ..
6633 if (Instruction *Result = commonIntCastTransforms(CI))
6634 return Result;
6635
6636 Value *Src = CI.getOperand(0);
6637
6638 // If this is a cast of a cast
6639 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006640 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6641 // types and if the sizes are just right we can convert this into a logical
6642 // 'and' which will be much cheaper than the pair of casts.
6643 if (isa<TruncInst>(CSrc)) {
6644 // Get the sizes of the types involved
6645 Value *A = CSrc->getOperand(0);
6646 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6647 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6648 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6649 // If we're actually extending zero bits and the trunc is a no-op
6650 if (MidSize < DstSize && SrcSize == DstSize) {
6651 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006652 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006653 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6654 Instruction *And =
6655 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6656 // Unfortunately, if the type changed, we need to cast it back.
6657 if (And->getType() != CI.getType()) {
6658 And->setName(CSrc->getName()+".mask");
6659 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006660 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006661 }
6662 return And;
6663 }
6664 }
6665 }
6666
6667 return 0;
6668}
6669
6670Instruction *InstCombiner::visitSExt(CastInst &CI) {
6671 return commonIntCastTransforms(CI);
6672}
6673
6674Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6675 return commonCastTransforms(CI);
6676}
6677
6678Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6679 return commonCastTransforms(CI);
6680}
6681
6682Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006683 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006684}
6685
6686Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006687 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006688}
6689
6690Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6691 return commonCastTransforms(CI);
6692}
6693
6694Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6695 return commonCastTransforms(CI);
6696}
6697
6698Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006699 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006700}
6701
6702Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6703 return commonCastTransforms(CI);
6704}
6705
6706Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6707
6708 // If the operands are integer typed then apply the integer transforms,
6709 // otherwise just apply the common ones.
6710 Value *Src = CI.getOperand(0);
6711 const Type *SrcTy = Src->getType();
6712 const Type *DestTy = CI.getType();
6713
Chris Lattner03c49532007-01-15 02:27:26 +00006714 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006715 if (Instruction *Result = commonIntCastTransforms(CI))
6716 return Result;
6717 } else {
6718 if (Instruction *Result = commonCastTransforms(CI))
6719 return Result;
6720 }
6721
6722
6723 // Get rid of casts from one type to the same type. These are useless and can
6724 // be replaced by the operand.
6725 if (DestTy == Src->getType())
6726 return ReplaceInstUsesWith(CI, Src);
6727
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006728 // If the source and destination are pointers, and this cast is equivalent to
6729 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6730 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006731 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6732 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6733 const Type *DstElTy = DstPTy->getElementType();
6734 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006735
Reid Spencerc635f472006-12-31 05:48:39 +00006736 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006737 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006738 while (SrcElTy != DstElTy &&
6739 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6740 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6741 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006742 ++NumZeros;
6743 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006744
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006745 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006746 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006747 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6748 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006749 }
6750 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006751 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006752
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006753 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6754 if (SVI->hasOneUse()) {
6755 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6756 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006757 if (isa<VectorType>(DestTy) &&
6758 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006759 SVI->getType()->getNumElements()) {
6760 CastInst *Tmp;
6761 // If either of the operands is a cast from CI.getType(), then
6762 // evaluating the shuffle in the casted destination's type will allow
6763 // us to eliminate at least one cast.
6764 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6765 Tmp->getOperand(0)->getType() == DestTy) ||
6766 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6767 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006768 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6769 SVI->getOperand(0), DestTy, &CI);
6770 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6771 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006772 // Return a new shuffle vector. Use the same element ID's, as we
6773 // know the vector types match #elts.
6774 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006775 }
6776 }
6777 }
6778 }
Chris Lattner260ab202002-04-18 17:39:14 +00006779 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006780}
6781
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006782/// GetSelectFoldableOperands - We want to turn code that looks like this:
6783/// %C = or %A, %B
6784/// %D = select %cond, %C, %A
6785/// into:
6786/// %C = select %cond, %B, 0
6787/// %D = or %A, %C
6788///
6789/// Assuming that the specified instruction is an operand to the select, return
6790/// a bitmask indicating which operands of this instruction are foldable if they
6791/// equal the other incoming value of the select.
6792///
6793static unsigned GetSelectFoldableOperands(Instruction *I) {
6794 switch (I->getOpcode()) {
6795 case Instruction::Add:
6796 case Instruction::Mul:
6797 case Instruction::And:
6798 case Instruction::Or:
6799 case Instruction::Xor:
6800 return 3; // Can fold through either operand.
6801 case Instruction::Sub: // Can only fold on the amount subtracted.
6802 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006803 case Instruction::LShr:
6804 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006805 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006806 default:
6807 return 0; // Cannot fold
6808 }
6809}
6810
6811/// GetSelectFoldableConstant - For the same transformation as the previous
6812/// function, return the identity constant that goes into the select.
6813static Constant *GetSelectFoldableConstant(Instruction *I) {
6814 switch (I->getOpcode()) {
6815 default: assert(0 && "This cannot happen!"); abort();
6816 case Instruction::Add:
6817 case Instruction::Sub:
6818 case Instruction::Or:
6819 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006820 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006821 case Instruction::LShr:
6822 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006823 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006824 case Instruction::And:
6825 return ConstantInt::getAllOnesValue(I->getType());
6826 case Instruction::Mul:
6827 return ConstantInt::get(I->getType(), 1);
6828 }
6829}
6830
Chris Lattner411336f2005-01-19 21:50:18 +00006831/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6832/// have the same opcode and only one use each. Try to simplify this.
6833Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6834 Instruction *FI) {
6835 if (TI->getNumOperands() == 1) {
6836 // If this is a non-volatile load or a cast from the same type,
6837 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006838 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006839 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6840 return 0;
6841 } else {
6842 return 0; // unknown unary op.
6843 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006844
Chris Lattner411336f2005-01-19 21:50:18 +00006845 // Fold this by inserting a select from the input values.
6846 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6847 FI->getOperand(0), SI.getName()+".v");
6848 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006849 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6850 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006851 }
6852
Reid Spencer2341c222007-02-02 02:16:23 +00006853 // Only handle binary operators here.
6854 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006855 return 0;
6856
6857 // Figure out if the operations have any operands in common.
6858 Value *MatchOp, *OtherOpT, *OtherOpF;
6859 bool MatchIsOpZero;
6860 if (TI->getOperand(0) == FI->getOperand(0)) {
6861 MatchOp = TI->getOperand(0);
6862 OtherOpT = TI->getOperand(1);
6863 OtherOpF = FI->getOperand(1);
6864 MatchIsOpZero = true;
6865 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6866 MatchOp = TI->getOperand(1);
6867 OtherOpT = TI->getOperand(0);
6868 OtherOpF = FI->getOperand(0);
6869 MatchIsOpZero = false;
6870 } else if (!TI->isCommutative()) {
6871 return 0;
6872 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6873 MatchOp = TI->getOperand(0);
6874 OtherOpT = TI->getOperand(1);
6875 OtherOpF = FI->getOperand(0);
6876 MatchIsOpZero = true;
6877 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6878 MatchOp = TI->getOperand(1);
6879 OtherOpT = TI->getOperand(0);
6880 OtherOpF = FI->getOperand(1);
6881 MatchIsOpZero = true;
6882 } else {
6883 return 0;
6884 }
6885
6886 // If we reach here, they do have operations in common.
6887 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6888 OtherOpF, SI.getName()+".v");
6889 InsertNewInstBefore(NewSI, SI);
6890
6891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6892 if (MatchIsOpZero)
6893 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6894 else
6895 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006896 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006897 assert(0 && "Shouldn't get here");
6898 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006899}
6900
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006901Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006902 Value *CondVal = SI.getCondition();
6903 Value *TrueVal = SI.getTrueValue();
6904 Value *FalseVal = SI.getFalseValue();
6905
6906 // select true, X, Y -> X
6907 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006908 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006909 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006910
6911 // select C, X, X -> X
6912 if (TrueVal == FalseVal)
6913 return ReplaceInstUsesWith(SI, TrueVal);
6914
Chris Lattner81a7a232004-10-16 18:11:37 +00006915 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6916 return ReplaceInstUsesWith(SI, FalseVal);
6917 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6918 return ReplaceInstUsesWith(SI, TrueVal);
6919 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6920 if (isa<Constant>(TrueVal))
6921 return ReplaceInstUsesWith(SI, TrueVal);
6922 else
6923 return ReplaceInstUsesWith(SI, FalseVal);
6924 }
6925
Reid Spencer542964f2007-01-11 18:21:29 +00006926 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006927 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006928 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006929 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006930 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006931 } else {
6932 // Change: A = select B, false, C --> A = and !B, C
6933 Value *NotCond =
6934 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6935 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006936 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006937 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006938 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006939 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006940 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006941 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006942 } else {
6943 // Change: A = select B, C, true --> A = or !B, C
6944 Value *NotCond =
6945 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6946 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006947 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006948 }
6949 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006950 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006951
Chris Lattner183b3362004-04-09 19:05:30 +00006952 // Selecting between two integer constants?
6953 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6954 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6955 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006956 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006957 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006958 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006959 // select C, 0, 1 -> cast !C to int
6960 Value *NotCond =
6961 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006962 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006963 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006964 }
Chris Lattner35167c32004-06-09 07:59:58 +00006965
Reid Spencer266e42b2006-12-23 06:05:41 +00006966 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006967
Reid Spencer266e42b2006-12-23 06:05:41 +00006968 // (x <s 0) ? -1 : 0 -> ashr x, 31
6969 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006970 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6971 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6972 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006973 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006974 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006975 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006976 else {
6977 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006978 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006979 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006980 }
6981
6982 if (CanXForm) {
6983 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006984 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006985 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006986 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006987 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6988 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6989 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006990 InsertNewInstBefore(SRA, SI);
6991
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006992 // Finally, convert to the type of the select RHS. We figure out
6993 // if this requires a SExt, Trunc or BitCast based on the sizes.
6994 Instruction::CastOps opc = Instruction::BitCast;
6995 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6996 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6997 if (SRASize < SISize)
6998 opc = Instruction::SExt;
6999 else if (SRASize > SISize)
7000 opc = Instruction::Trunc;
7001 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007002 }
7003 }
7004
7005
7006 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00007007 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007008 // non-constant value, eliminate this whole mess. This corresponds to
7009 // cases like this: ((X & 27) ? 27 : 0)
7010 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007011 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007012 cast<Constant>(IC->getOperand(1))->isNullValue())
7013 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7014 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007015 isa<ConstantInt>(ICA->getOperand(1)) &&
7016 (ICA->getOperand(1) == TrueValC ||
7017 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007018 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7019 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007020 // know whether we have a icmp_ne or icmp_eq and whether the
7021 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00007022 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007023 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007024 Value *V = ICA;
7025 if (ShouldNotVal)
7026 V = InsertNewInstBefore(BinaryOperator::create(
7027 Instruction::Xor, V, ICA->getOperand(1)), SI);
7028 return ReplaceInstUsesWith(SI, V);
7029 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007030 }
Chris Lattner533bc492004-03-30 19:37:13 +00007031 }
Chris Lattner623fba12004-04-10 22:21:27 +00007032
7033 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007034 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7035 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007036 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007037 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007038 return ReplaceInstUsesWith(SI, FalseVal);
7039 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007040 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007041 return ReplaceInstUsesWith(SI, TrueVal);
7042 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7043
Reid Spencer266e42b2006-12-23 06:05:41 +00007044 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007045 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007046 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007047 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007048 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007049 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7050 return ReplaceInstUsesWith(SI, TrueVal);
7051 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7052 }
7053 }
7054
7055 // See if we are selecting two values based on a comparison of the two values.
7056 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7057 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7058 // Transform (X == Y) ? X : Y -> Y
7059 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7060 return ReplaceInstUsesWith(SI, FalseVal);
7061 // Transform (X != Y) ? X : Y -> X
7062 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7063 return ReplaceInstUsesWith(SI, TrueVal);
7064 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7065
7066 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7067 // Transform (X == Y) ? Y : X -> X
7068 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7069 return ReplaceInstUsesWith(SI, FalseVal);
7070 // Transform (X != Y) ? Y : X -> Y
7071 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007072 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007073 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7074 }
7075 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007076
Chris Lattnera04c9042005-01-13 22:52:24 +00007077 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7078 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7079 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007080 Instruction *AddOp = 0, *SubOp = 0;
7081
Chris Lattner411336f2005-01-19 21:50:18 +00007082 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7083 if (TI->getOpcode() == FI->getOpcode())
7084 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7085 return IV;
7086
7087 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7088 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007089 if (TI->getOpcode() == Instruction::Sub &&
7090 FI->getOpcode() == Instruction::Add) {
7091 AddOp = FI; SubOp = TI;
7092 } else if (FI->getOpcode() == Instruction::Sub &&
7093 TI->getOpcode() == Instruction::Add) {
7094 AddOp = TI; SubOp = FI;
7095 }
7096
7097 if (AddOp) {
7098 Value *OtherAddOp = 0;
7099 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7100 OtherAddOp = AddOp->getOperand(1);
7101 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7102 OtherAddOp = AddOp->getOperand(0);
7103 }
7104
7105 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007106 // So at this point we know we have (Y -> OtherAddOp):
7107 // select C, (add X, Y), (sub X, Z)
7108 Value *NegVal; // Compute -Z
7109 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7110 NegVal = ConstantExpr::getNeg(C);
7111 } else {
7112 NegVal = InsertNewInstBefore(
7113 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007114 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007115
7116 Value *NewTrueOp = OtherAddOp;
7117 Value *NewFalseOp = NegVal;
7118 if (AddOp != TI)
7119 std::swap(NewTrueOp, NewFalseOp);
7120 Instruction *NewSel =
7121 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7122
7123 NewSel = InsertNewInstBefore(NewSel, SI);
7124 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007125 }
7126 }
7127 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007128
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007129 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007130 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007131 // See the comment above GetSelectFoldableOperands for a description of the
7132 // transformation we are doing here.
7133 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7134 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7135 !isa<Constant>(FalseVal))
7136 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7137 unsigned OpToFold = 0;
7138 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7139 OpToFold = 1;
7140 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7141 OpToFold = 2;
7142 }
7143
7144 if (OpToFold) {
7145 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007146 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007147 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007148 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007149 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7151 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007152 else {
7153 assert(0 && "Unknown instruction!!");
7154 }
7155 }
7156 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007157
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007158 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7159 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7160 !isa<Constant>(TrueVal))
7161 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7162 unsigned OpToFold = 0;
7163 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7164 OpToFold = 1;
7165 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7166 OpToFold = 2;
7167 }
7168
7169 if (OpToFold) {
7170 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007171 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007172 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007173 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007174 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007175 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7176 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007177 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007178 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007179 }
7180 }
7181 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007182
7183 if (BinaryOperator::isNot(CondVal)) {
7184 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7185 SI.setOperand(1, FalseVal);
7186 SI.setOperand(2, TrueVal);
7187 return &SI;
7188 }
7189
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007190 return 0;
7191}
7192
Chris Lattner82f2ef22006-03-06 20:18:44 +00007193/// GetKnownAlignment - If the specified pointer has an alignment that we can
7194/// determine, return it, otherwise return 0.
7195static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7197 unsigned Align = GV->getAlignment();
7198 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007199 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007200 return Align;
7201 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7202 unsigned Align = AI->getAlignment();
7203 if (Align == 0 && TD) {
7204 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007205 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007206 else if (isa<MallocInst>(AI)) {
7207 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007208 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007209 Align =
7210 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007211 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007212 Align =
7213 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007214 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007215 }
7216 }
7217 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007218 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007219 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007220 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007221 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007222 if (isa<PointerType>(CI->getOperand(0)->getType()))
7223 return GetKnownAlignment(CI->getOperand(0), TD);
7224 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007225 } else if (isa<GetElementPtrInst>(V) ||
7226 (isa<ConstantExpr>(V) &&
7227 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7228 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007229 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7230 if (BaseAlignment == 0) return 0;
7231
7232 // If all indexes are zero, it is just the alignment of the base pointer.
7233 bool AllZeroOperands = true;
7234 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7235 if (!isa<Constant>(GEPI->getOperand(i)) ||
7236 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7237 AllZeroOperands = false;
7238 break;
7239 }
7240 if (AllZeroOperands)
7241 return BaseAlignment;
7242
7243 // Otherwise, if the base alignment is >= the alignment we expect for the
7244 // base pointer type, then we know that the resultant pointer is aligned at
7245 // least as much as its type requires.
7246 if (!TD) return 0;
7247
7248 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007249 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007250 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007251 <= BaseAlignment) {
7252 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007253 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007254 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007255 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007256 return 0;
7257 }
7258 return 0;
7259}
7260
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007261
Chris Lattnerc66b2232006-01-13 20:11:04 +00007262/// visitCallInst - CallInst simplification. This mostly only handles folding
7263/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7264/// the heavy lifting.
7265///
Chris Lattner970c33a2003-06-19 17:00:31 +00007266Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007267 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7268 if (!II) return visitCallSite(&CI);
7269
Chris Lattner51ea1272004-02-28 05:22:00 +00007270 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7271 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007272 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007273 bool Changed = false;
7274
7275 // memmove/cpy/set of zero bytes is a noop.
7276 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7277 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7278
Chris Lattner00648e12004-10-12 04:52:52 +00007279 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007280 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007281 // Replace the instruction with just byte operations. We would
7282 // transform other cases to loads/stores, but we don't know if
7283 // alignment is sufficient.
7284 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007285 }
7286
Chris Lattner00648e12004-10-12 04:52:52 +00007287 // If we have a memmove and the source operation is a constant global,
7288 // then the source and dest pointers can't alias, so we can change this
7289 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007290 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007291 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7292 if (GVSrc->isConstant()) {
7293 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007294 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007295 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007296 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007297 Name = "llvm.memcpy.i32";
7298 else
7299 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007300 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007301 CI.getCalledFunction()->getFunctionType());
7302 CI.setOperand(0, MemCpy);
7303 Changed = true;
7304 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007305 }
Chris Lattner00648e12004-10-12 04:52:52 +00007306
Chris Lattner82f2ef22006-03-06 20:18:44 +00007307 // If we can determine a pointer alignment that is bigger than currently
7308 // set, update the alignment.
7309 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7310 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7311 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7312 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007313 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007314 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007315 Changed = true;
7316 }
7317 } else if (isa<MemSetInst>(MI)) {
7318 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007319 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007320 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007321 Changed = true;
7322 }
7323 }
7324
Chris Lattnerc66b2232006-01-13 20:11:04 +00007325 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007326 } else {
7327 switch (II->getIntrinsicID()) {
7328 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007329 case Intrinsic::ppc_altivec_lvx:
7330 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007331 case Intrinsic::x86_sse_loadu_ps:
7332 case Intrinsic::x86_sse2_loadu_pd:
7333 case Intrinsic::x86_sse2_loadu_dq:
7334 // Turn PPC lvx -> load if the pointer is known aligned.
7335 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007336 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007337 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007338 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007339 return new LoadInst(Ptr);
7340 }
7341 break;
7342 case Intrinsic::ppc_altivec_stvx:
7343 case Intrinsic::ppc_altivec_stvxl:
7344 // Turn stvx -> store if the pointer is known aligned.
7345 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007346 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007347 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7348 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007349 return new StoreInst(II->getOperand(1), Ptr);
7350 }
7351 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007352 case Intrinsic::x86_sse_storeu_ps:
7353 case Intrinsic::x86_sse2_storeu_pd:
7354 case Intrinsic::x86_sse2_storeu_dq:
7355 case Intrinsic::x86_sse2_storel_dq:
7356 // Turn X86 storeu -> store if the pointer is known aligned.
7357 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7358 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007359 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7360 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007361 return new StoreInst(II->getOperand(2), Ptr);
7362 }
7363 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007364
7365 case Intrinsic::x86_sse_cvttss2si: {
7366 // These intrinsics only demands the 0th element of its input vector. If
7367 // we can simplify the input based on that, do so now.
7368 uint64_t UndefElts;
7369 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7370 UndefElts)) {
7371 II->setOperand(1, V);
7372 return II;
7373 }
7374 break;
7375 }
7376
Chris Lattnere79d2492006-04-06 19:19:17 +00007377 case Intrinsic::ppc_altivec_vperm:
7378 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007379 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007380 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7381
7382 // Check that all of the elements are integer constants or undefs.
7383 bool AllEltsOk = true;
7384 for (unsigned i = 0; i != 16; ++i) {
7385 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7386 !isa<UndefValue>(Mask->getOperand(i))) {
7387 AllEltsOk = false;
7388 break;
7389 }
7390 }
7391
7392 if (AllEltsOk) {
7393 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007394 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7395 II->getOperand(1), Mask->getType(), CI);
7396 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7397 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007398 Value *Result = UndefValue::get(Op0->getType());
7399
7400 // Only extract each element once.
7401 Value *ExtractedElts[32];
7402 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7403
7404 for (unsigned i = 0; i != 16; ++i) {
7405 if (isa<UndefValue>(Mask->getOperand(i)))
7406 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007407 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007408 Idx &= 31; // Match the hardware behavior.
7409
7410 if (ExtractedElts[Idx] == 0) {
7411 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007412 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007413 InsertNewInstBefore(Elt, CI);
7414 ExtractedElts[Idx] = Elt;
7415 }
7416
7417 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007418 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007419 InsertNewInstBefore(cast<Instruction>(Result), CI);
7420 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007421 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007422 }
7423 }
7424 break;
7425
Chris Lattner503221f2006-01-13 21:28:09 +00007426 case Intrinsic::stackrestore: {
7427 // If the save is right next to the restore, remove the restore. This can
7428 // happen when variable allocas are DCE'd.
7429 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7430 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7431 BasicBlock::iterator BI = SS;
7432 if (&*++BI == II)
7433 return EraseInstFromFunction(CI);
7434 }
7435 }
7436
7437 // If the stack restore is in a return/unwind block and if there are no
7438 // allocas or calls between the restore and the return, nuke the restore.
7439 TerminatorInst *TI = II->getParent()->getTerminator();
7440 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7441 BasicBlock::iterator BI = II;
7442 bool CannotRemove = false;
7443 for (++BI; &*BI != TI; ++BI) {
7444 if (isa<AllocaInst>(BI) ||
7445 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7446 CannotRemove = true;
7447 break;
7448 }
7449 }
7450 if (!CannotRemove)
7451 return EraseInstFromFunction(CI);
7452 }
7453 break;
7454 }
7455 }
Chris Lattner00648e12004-10-12 04:52:52 +00007456 }
7457
Chris Lattnerc66b2232006-01-13 20:11:04 +00007458 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007459}
7460
7461// InvokeInst simplification
7462//
7463Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007464 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007465}
7466
Chris Lattneraec3d942003-10-07 22:32:43 +00007467// visitCallSite - Improvements for call and invoke instructions.
7468//
7469Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007470 bool Changed = false;
7471
7472 // If the callee is a constexpr cast of a function, attempt to move the cast
7473 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007474 if (transformConstExprCastCall(CS)) return 0;
7475
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007476 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007477
Chris Lattner61d9d812005-05-13 07:09:09 +00007478 if (Function *CalleeF = dyn_cast<Function>(Callee))
7479 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7480 Instruction *OldCall = CS.getInstruction();
7481 // If the call and callee calling conventions don't match, this call must
7482 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007483 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007484 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007485 if (!OldCall->use_empty())
7486 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7487 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7488 return EraseInstFromFunction(*OldCall);
7489 return 0;
7490 }
7491
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007492 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7493 // This instruction is not reachable, just remove it. We insert a store to
7494 // undef so that we know that this code is not reachable, despite the fact
7495 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007496 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007497 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007498 CS.getInstruction());
7499
7500 if (!CS.getInstruction()->use_empty())
7501 CS.getInstruction()->
7502 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7503
7504 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7505 // Don't break the CFG, insert a dummy cond branch.
7506 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007507 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007508 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007509 return EraseInstFromFunction(*CS.getInstruction());
7510 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007511
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007512 const PointerType *PTy = cast<PointerType>(Callee->getType());
7513 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7514 if (FTy->isVarArg()) {
7515 // See if we can optimize any arguments passed through the varargs area of
7516 // the call.
7517 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7518 E = CS.arg_end(); I != E; ++I)
7519 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7520 // If this cast does not effect the value passed through the varargs
7521 // area, we can eliminate the use of the cast.
7522 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007523 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007524 *I = Op;
7525 Changed = true;
7526 }
7527 }
7528 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007529
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007530 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007531}
7532
Chris Lattner970c33a2003-06-19 17:00:31 +00007533// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7534// attempt to move the cast to the arguments of the call/invoke.
7535//
7536bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7537 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7538 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007539 if (CE->getOpcode() != Instruction::BitCast ||
7540 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007541 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007542 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007543 Instruction *Caller = CS.getInstruction();
7544
7545 // Okay, this is a cast from a function to a different type. Unless doing so
7546 // would cause a type conversion of one of our arguments, change this call to
7547 // be a direct call with arguments casted to the appropriate types.
7548 //
7549 const FunctionType *FT = Callee->getFunctionType();
7550 const Type *OldRetTy = Caller->getType();
7551
Chris Lattner1f7942f2004-01-14 06:06:08 +00007552 // Check to see if we are changing the return type...
7553 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007554 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007555 OldRetTy != FT->getReturnType() &&
7556 // Conversion is ok if changing from pointer to int of same size.
7557 !(isa<PointerType>(FT->getReturnType()) &&
7558 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007559 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007560
7561 // If the callsite is an invoke instruction, and the return value is used by
7562 // a PHI node in a successor, we cannot change the return type of the call
7563 // because there is no place to put the cast instruction (without breaking
7564 // the critical edge). Bail out in this case.
7565 if (!Caller->use_empty())
7566 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7567 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7568 UI != E; ++UI)
7569 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7570 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007571 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007572 return false;
7573 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007574
7575 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7576 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007577
Chris Lattner970c33a2003-06-19 17:00:31 +00007578 CallSite::arg_iterator AI = CS.arg_begin();
7579 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7580 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007581 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007582 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007583 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007584 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007585 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007586 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007587 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7588 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7589 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007590 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007591 }
7592
7593 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007594 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007595 return false; // Do not delete arguments unless we have a function body...
7596
7597 // Okay, we decided that this is a safe thing to do: go ahead and start
7598 // inserting cast instructions as necessary...
7599 std::vector<Value*> Args;
7600 Args.reserve(NumActualArgs);
7601
7602 AI = CS.arg_begin();
7603 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7604 const Type *ParamTy = FT->getParamType(i);
7605 if ((*AI)->getType() == ParamTy) {
7606 Args.push_back(*AI);
7607 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007608 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007609 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007610 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007611 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007612 }
7613 }
7614
7615 // If the function takes more arguments than the call was taking, add them
7616 // now...
7617 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7618 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7619
7620 // If we are removing arguments to the function, emit an obnoxious warning...
7621 if (FT->getNumParams() < NumActualArgs)
7622 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007623 cerr << "WARNING: While resolving call to function '"
7624 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007625 } else {
7626 // Add all of the arguments in their promoted form to the arg list...
7627 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7628 const Type *PTy = getPromotedType((*AI)->getType());
7629 if (PTy != (*AI)->getType()) {
7630 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007631 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7632 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007633 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007634 InsertNewInstBefore(Cast, *Caller);
7635 Args.push_back(Cast);
7636 } else {
7637 Args.push_back(*AI);
7638 }
7639 }
7640 }
7641
7642 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007643 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007644
7645 Instruction *NC;
7646 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007647 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007648 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007649 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007650 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007651 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007652 if (cast<CallInst>(Caller)->isTailCall())
7653 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007654 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007655 }
7656
Chris Lattner6e0123b2007-02-11 01:23:03 +00007657 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007658 Value *NV = NC;
7659 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7660 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007661 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007662 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7663 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007664 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007665
7666 // If this is an invoke instruction, we should insert it after the first
7667 // non-phi, instruction in the normal successor block.
7668 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7669 BasicBlock::iterator I = II->getNormalDest()->begin();
7670 while (isa<PHINode>(I)) ++I;
7671 InsertNewInstBefore(NC, *I);
7672 } else {
7673 // Otherwise, it's a call, just insert cast right after the call instr
7674 InsertNewInstBefore(NC, *Caller);
7675 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007676 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007677 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007678 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007679 }
7680 }
7681
7682 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7683 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007684 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007685 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007686 return true;
7687}
7688
Chris Lattnercadac0c2006-11-01 04:51:18 +00007689/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7690/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7691/// and a single binop.
7692Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7693 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007694 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7695 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007696 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007697 Value *LHSVal = FirstInst->getOperand(0);
7698 Value *RHSVal = FirstInst->getOperand(1);
7699
7700 const Type *LHSType = LHSVal->getType();
7701 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007702
7703 // Scan to see if all operands are the same opcode, all have one use, and all
7704 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007705 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007706 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007707 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007708 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007709 // types or GEP's with different index types.
7710 I->getOperand(0)->getType() != LHSType ||
7711 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007712 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007713
7714 // If they are CmpInst instructions, check their predicates
7715 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7716 if (cast<CmpInst>(I)->getPredicate() !=
7717 cast<CmpInst>(FirstInst)->getPredicate())
7718 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007719
7720 // Keep track of which operand needs a phi node.
7721 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7722 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007723 }
7724
Chris Lattner4f218d52006-11-08 19:42:28 +00007725 // Otherwise, this is safe to transform, determine if it is profitable.
7726
7727 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7728 // Indexes are often folded into load/store instructions, so we don't want to
7729 // hide them behind a phi.
7730 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7731 return 0;
7732
Chris Lattnercadac0c2006-11-01 04:51:18 +00007733 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007734 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007735 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007736 if (LHSVal == 0) {
7737 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7738 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7739 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007740 InsertNewInstBefore(NewLHS, PN);
7741 LHSVal = NewLHS;
7742 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007743
7744 if (RHSVal == 0) {
7745 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7746 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7747 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007748 InsertNewInstBefore(NewRHS, PN);
7749 RHSVal = NewRHS;
7750 }
7751
Chris Lattnercd62f112006-11-08 19:29:23 +00007752 // Add all operands to the new PHIs.
7753 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7754 if (NewLHS) {
7755 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7756 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7757 }
7758 if (NewRHS) {
7759 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7760 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7761 }
7762 }
7763
Chris Lattnercadac0c2006-11-01 04:51:18 +00007764 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007765 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007766 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7767 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7768 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007769 else {
7770 assert(isa<GetElementPtrInst>(FirstInst));
7771 return new GetElementPtrInst(LHSVal, RHSVal);
7772 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007773}
7774
Chris Lattner14f82c72006-11-01 07:13:54 +00007775/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7776/// of the block that defines it. This means that it must be obvious the value
7777/// of the load is not changed from the point of the load to the end of the
7778/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007779///
7780/// Finally, it is safe, but not profitable, to sink a load targetting a
7781/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7782/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007783static bool isSafeToSinkLoad(LoadInst *L) {
7784 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7785
7786 for (++BBI; BBI != E; ++BBI)
7787 if (BBI->mayWriteToMemory())
7788 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007789
7790 // Check for non-address taken alloca. If not address-taken already, it isn't
7791 // profitable to do this xform.
7792 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7793 bool isAddressTaken = false;
7794 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7795 UI != E; ++UI) {
7796 if (isa<LoadInst>(UI)) continue;
7797 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7798 // If storing TO the alloca, then the address isn't taken.
7799 if (SI->getOperand(1) == AI) continue;
7800 }
7801 isAddressTaken = true;
7802 break;
7803 }
7804
7805 if (!isAddressTaken)
7806 return false;
7807 }
7808
Chris Lattner14f82c72006-11-01 07:13:54 +00007809 return true;
7810}
7811
Chris Lattner970c33a2003-06-19 17:00:31 +00007812
Chris Lattner7515cab2004-11-14 19:13:23 +00007813// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7814// operator and they all are only used by the PHI, PHI together their
7815// inputs, and do the operation once, to the result of the PHI.
7816Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7817 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7818
7819 // Scan the instruction, looking for input operations that can be folded away.
7820 // If all input operands to the phi are the same instruction (e.g. a cast from
7821 // the same type or "+42") we can pull the operation through the PHI, reducing
7822 // code size and simplifying code.
7823 Constant *ConstantOp = 0;
7824 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007825 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007826 if (isa<CastInst>(FirstInst)) {
7827 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007828 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007829 // Can fold binop, compare or shift here if the RHS is a constant,
7830 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007831 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007832 if (ConstantOp == 0)
7833 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007834 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7835 isVolatile = LI->isVolatile();
7836 // We can't sink the load if the loaded value could be modified between the
7837 // load and the PHI.
7838 if (LI->getParent() != PN.getIncomingBlock(0) ||
7839 !isSafeToSinkLoad(LI))
7840 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007841 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007842 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007843 return FoldPHIArgBinOpIntoPHI(PN);
7844 // Can't handle general GEPs yet.
7845 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007846 } else {
7847 return 0; // Cannot fold this operation.
7848 }
7849
7850 // Check to see if all arguments are the same operation.
7851 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7852 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7853 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007854 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007855 return 0;
7856 if (CastSrcTy) {
7857 if (I->getOperand(0)->getType() != CastSrcTy)
7858 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007859 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007860 // We can't sink the load if the loaded value could be modified between
7861 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007862 if (LI->isVolatile() != isVolatile ||
7863 LI->getParent() != PN.getIncomingBlock(i) ||
7864 !isSafeToSinkLoad(LI))
7865 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007866 } else if (I->getOperand(1) != ConstantOp) {
7867 return 0;
7868 }
7869 }
7870
7871 // Okay, they are all the same operation. Create a new PHI node of the
7872 // correct type, and PHI together all of the LHS's of the instructions.
7873 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7874 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007875 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007876
7877 Value *InVal = FirstInst->getOperand(0);
7878 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007879
7880 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007881 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7882 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7883 if (NewInVal != InVal)
7884 InVal = 0;
7885 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7886 }
7887
7888 Value *PhiVal;
7889 if (InVal) {
7890 // The new PHI unions all of the same values together. This is really
7891 // common, so we handle it intelligently here for compile-time speed.
7892 PhiVal = InVal;
7893 delete NewPN;
7894 } else {
7895 InsertNewInstBefore(NewPN, PN);
7896 PhiVal = NewPN;
7897 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007898
Chris Lattner7515cab2004-11-14 19:13:23 +00007899 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007900 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7901 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007902 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007903 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007904 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007905 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007906 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7907 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7908 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007909 else
Reid Spencer2341c222007-02-02 02:16:23 +00007910 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007911 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007912}
Chris Lattner48a44f72002-05-02 17:06:02 +00007913
Chris Lattner71536432005-01-17 05:10:15 +00007914/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7915/// that is dead.
7916static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7917 if (PN->use_empty()) return true;
7918 if (!PN->hasOneUse()) return false;
7919
7920 // Remember this node, and if we find the cycle, return.
7921 if (!PotentiallyDeadPHIs.insert(PN).second)
7922 return true;
7923
7924 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7925 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007926
Chris Lattner71536432005-01-17 05:10:15 +00007927 return false;
7928}
7929
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007930// PHINode simplification
7931//
Chris Lattner113f4f42002-06-25 16:13:24 +00007932Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007933 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007934 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007935
Owen Andersonae8aa642006-07-10 22:03:18 +00007936 if (Value *V = PN.hasConstantValue())
7937 return ReplaceInstUsesWith(PN, V);
7938
Owen Andersonae8aa642006-07-10 22:03:18 +00007939 // If all PHI operands are the same operation, pull them through the PHI,
7940 // reducing code size.
7941 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7942 PN.getIncomingValue(0)->hasOneUse())
7943 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7944 return Result;
7945
7946 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7947 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7948 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007949 if (PN.hasOneUse()) {
7950 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7951 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007952 std::set<PHINode*> PotentiallyDeadPHIs;
7953 PotentiallyDeadPHIs.insert(&PN);
7954 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7955 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7956 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007957
7958 // If this phi has a single use, and if that use just computes a value for
7959 // the next iteration of a loop, delete the phi. This occurs with unused
7960 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7961 // common case here is good because the only other things that catch this
7962 // are induction variable analysis (sometimes) and ADCE, which is only run
7963 // late.
7964 if (PHIUser->hasOneUse() &&
7965 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7966 PHIUser->use_back() == &PN) {
7967 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7968 }
7969 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007970
Chris Lattner91daeb52003-12-19 05:58:40 +00007971 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007972}
7973
Reid Spencer13bc5d72006-12-12 09:18:51 +00007974static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7975 Instruction *InsertPoint,
7976 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007977 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7978 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007979 // We must cast correctly to the pointer type. Ensure that we
7980 // sign extend the integer value if it is smaller as this is
7981 // used for address computation.
7982 Instruction::CastOps opcode =
7983 (VTySize < PtrSize ? Instruction::SExt :
7984 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7985 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007986}
7987
Chris Lattner48a44f72002-05-02 17:06:02 +00007988
Chris Lattner113f4f42002-06-25 16:13:24 +00007989Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007990 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007991 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007992 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007993 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007994 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007995
Chris Lattner81a7a232004-10-16 18:11:37 +00007996 if (isa<UndefValue>(GEP.getOperand(0)))
7997 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7998
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007999 bool HasZeroPointerIndex = false;
8000 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8001 HasZeroPointerIndex = C->isNullValue();
8002
8003 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008004 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008005
Chris Lattner69193f92004-04-05 01:30:19 +00008006 // Eliminate unneeded casts for indices.
8007 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00008008 gep_type_iterator GTI = gep_type_begin(GEP);
8009 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8010 if (isa<SequentialType>(*GTI)) {
8011 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008012 if (CI->getOpcode() == Instruction::ZExt ||
8013 CI->getOpcode() == Instruction::SExt) {
8014 const Type *SrcTy = CI->getOperand(0)->getType();
8015 // We can eliminate a cast from i32 to i64 iff the target
8016 // is a 32-bit pointer target.
8017 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8018 MadeChange = true;
8019 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008020 }
8021 }
8022 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008023 // If we are using a wider index than needed for this platform, shrink it
8024 // to what we need. If the incoming value needs a cast instruction,
8025 // insert it. This explicit cast can make subsequent optimizations more
8026 // obvious.
8027 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008028 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008029 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008030 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008031 MadeChange = true;
8032 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008033 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8034 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008035 GEP.setOperand(i, Op);
8036 MadeChange = true;
8037 }
Chris Lattner69193f92004-04-05 01:30:19 +00008038 }
8039 if (MadeChange) return &GEP;
8040
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008041 // Combine Indices - If the source pointer to this getelementptr instruction
8042 // is a getelementptr instruction, combine the indices of the two
8043 // getelementptr instructions into a single instruction.
8044 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008045 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008046 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008047 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008048
8049 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008050 // Note that if our source is a gep chain itself that we wait for that
8051 // chain to be resolved before we perform this transformation. This
8052 // avoids us creating a TON of code in some cases.
8053 //
8054 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8055 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8056 return 0; // Wait until our source is folded to completion.
8057
Chris Lattneraf6094f2007-02-15 22:48:32 +00008058 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008059
8060 // Find out whether the last index in the source GEP is a sequential idx.
8061 bool EndsWithSequential = false;
8062 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8063 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008064 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008065
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008066 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008067 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008068 // Replace: gep (gep %P, long B), long A, ...
8069 // With: T = long A+B; gep %P, T, ...
8070 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008071 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008072 if (SO1 == Constant::getNullValue(SO1->getType())) {
8073 Sum = GO1;
8074 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8075 Sum = SO1;
8076 } else {
8077 // If they aren't the same type, convert both to an integer of the
8078 // target's pointer size.
8079 if (SO1->getType() != GO1->getType()) {
8080 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008081 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008082 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008083 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008084 } else {
8085 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008086 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008087 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008088 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008089
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008090 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008091 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008092 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008093 } else {
8094 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008095 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8096 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008097 }
8098 }
8099 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008100 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8101 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8102 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008103 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8104 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008105 }
Chris Lattner69193f92004-04-05 01:30:19 +00008106 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008107
8108 // Recycle the GEP we already have if possible.
8109 if (SrcGEPOperands.size() == 2) {
8110 GEP.setOperand(0, SrcGEPOperands[0]);
8111 GEP.setOperand(1, Sum);
8112 return &GEP;
8113 } else {
8114 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8115 SrcGEPOperands.end()-1);
8116 Indices.push_back(Sum);
8117 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8118 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008119 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008120 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008121 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008122 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008123 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8124 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008125 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8126 }
8127
8128 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008129 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8130 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008131
Chris Lattner5f667a62004-05-07 22:09:22 +00008132 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008133 // GEP of global variable. If all of the indices for this GEP are
8134 // constants, we can promote this to a constexpr instead of an instruction.
8135
8136 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008137 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008138 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8139 for (; I != E && isa<Constant>(*I); ++I)
8140 Indices.push_back(cast<Constant>(*I));
8141
8142 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008143 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8144 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008145
8146 // Replace all uses of the GEP with the new constexpr...
8147 return ReplaceInstUsesWith(GEP, CE);
8148 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008149 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008150 if (!isa<PointerType>(X->getType())) {
8151 // Not interesting. Source pointer must be a cast from pointer.
8152 } else if (HasZeroPointerIndex) {
8153 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8154 // into : GEP [10 x ubyte]* X, long 0, ...
8155 //
8156 // This occurs when the program declares an array extern like "int X[];"
8157 //
8158 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8159 const PointerType *XTy = cast<PointerType>(X->getType());
8160 if (const ArrayType *XATy =
8161 dyn_cast<ArrayType>(XTy->getElementType()))
8162 if (const ArrayType *CATy =
8163 dyn_cast<ArrayType>(CPTy->getElementType()))
8164 if (CATy->getElementType() == XATy->getElementType()) {
8165 // At this point, we know that the cast source type is a pointer
8166 // to an array of the same type as the destination pointer
8167 // array. Because the array type is never stepped over (there
8168 // is a leading zero) we can fold the cast into this GEP.
8169 GEP.setOperand(0, X);
8170 return &GEP;
8171 }
8172 } else if (GEP.getNumOperands() == 2) {
8173 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008174 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8175 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008176 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8177 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8178 if (isa<ArrayType>(SrcElTy) &&
8179 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8180 TD->getTypeSize(ResElTy)) {
8181 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008182 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008183 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008184 // V and GEP are both pointer types --> BitCast
8185 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008186 }
Chris Lattner2a893292005-09-13 18:36:04 +00008187
8188 // Transform things like:
8189 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8190 // (where tmp = 8*tmp2) into:
8191 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8192
8193 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008194 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008195 uint64_t ArrayEltSize =
8196 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8197
8198 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8199 // allow either a mul, shift, or constant here.
8200 Value *NewIdx = 0;
8201 ConstantInt *Scale = 0;
8202 if (ArrayEltSize == 1) {
8203 NewIdx = GEP.getOperand(1);
8204 Scale = ConstantInt::get(NewIdx->getType(), 1);
8205 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008206 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008207 Scale = CI;
8208 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8209 if (Inst->getOpcode() == Instruction::Shl &&
8210 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008211 unsigned ShAmt =
8212 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008213 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008214 NewIdx = Inst->getOperand(0);
8215 } else if (Inst->getOpcode() == Instruction::Mul &&
8216 isa<ConstantInt>(Inst->getOperand(1))) {
8217 Scale = cast<ConstantInt>(Inst->getOperand(1));
8218 NewIdx = Inst->getOperand(0);
8219 }
8220 }
8221
8222 // If the index will be to exactly the right offset with the scale taken
8223 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008224 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008225 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008226 Scale = ConstantInt::get(Scale->getType(),
8227 Scale->getZExtValue() / ArrayEltSize);
8228 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008229 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8230 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008231 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8232 NewIdx = InsertNewInstBefore(Sc, GEP);
8233 }
8234
8235 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008236 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008237 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008238 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008239 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8240 // The NewGEP must be pointer typed, so must the old one -> BitCast
8241 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008242 }
8243 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008244 }
Chris Lattnerca081252001-12-14 16:52:21 +00008245 }
8246
Chris Lattnerca081252001-12-14 16:52:21 +00008247 return 0;
8248}
8249
Chris Lattner1085bdf2002-11-04 16:18:53 +00008250Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8251 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8252 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008253 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8254 const Type *NewTy =
8255 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008256 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008257
8258 // Create and insert the replacement instruction...
8259 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008260 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008261 else {
8262 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008263 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008264 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008265
8266 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008267
Chris Lattner1085bdf2002-11-04 16:18:53 +00008268 // Scan to the end of the allocation instructions, to skip over a block of
8269 // allocas if possible...
8270 //
8271 BasicBlock::iterator It = New;
8272 while (isa<AllocationInst>(*It)) ++It;
8273
8274 // Now that I is pointing to the first non-allocation-inst in the block,
8275 // insert our getelementptr instruction...
8276 //
Reid Spencerc635f472006-12-31 05:48:39 +00008277 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008278 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8279 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008280
8281 // Now make everything use the getelementptr instead of the original
8282 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008283 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008284 } else if (isa<UndefValue>(AI.getArraySize())) {
8285 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008286 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008287
8288 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8289 // Note that we only do this for alloca's, because malloc should allocate and
8290 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008291 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008292 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008293 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8294
Chris Lattner1085bdf2002-11-04 16:18:53 +00008295 return 0;
8296}
8297
Chris Lattner8427bff2003-12-07 01:24:23 +00008298Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8299 Value *Op = FI.getOperand(0);
8300
8301 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8302 if (CastInst *CI = dyn_cast<CastInst>(Op))
8303 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8304 FI.setOperand(0, CI->getOperand(0));
8305 return &FI;
8306 }
8307
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008308 // free undef -> unreachable.
8309 if (isa<UndefValue>(Op)) {
8310 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008311 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008312 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008313 return EraseInstFromFunction(FI);
8314 }
8315
Chris Lattnerf3a36602004-02-28 04:57:37 +00008316 // If we have 'free null' delete the instruction. This can happen in stl code
8317 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008318 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008319 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008320
Chris Lattner8427bff2003-12-07 01:24:23 +00008321 return 0;
8322}
8323
8324
Chris Lattner72684fe2005-01-31 05:51:45 +00008325/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008326static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8327 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008328 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008329
8330 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008331 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008332 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008333
Reid Spencer31a4ef42007-01-22 05:51:25 +00008334 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008335 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008336 // If the source is an array, the code below will not succeed. Check to
8337 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8338 // constants.
8339 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8340 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8341 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008342 Value *Idxs[2];
8343 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8344 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008345 SrcTy = cast<PointerType>(CastOp->getType());
8346 SrcPTy = SrcTy->getElementType();
8347 }
8348
Reid Spencer31a4ef42007-01-22 05:51:25 +00008349 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008350 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008351 // Do not allow turning this into a load of an integer, which is then
8352 // casted to a pointer, this pessimizes pointer analysis a lot.
8353 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008354 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8355 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008356
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008357 // Okay, we are casting from one integer or pointer type to another of
8358 // the same size. Instead of casting the pointer before the load, cast
8359 // the result of the loaded value.
8360 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8361 CI->getName(),
8362 LI.isVolatile()),LI);
8363 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008364 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008365 }
Chris Lattner35e24772004-07-13 01:49:43 +00008366 }
8367 }
8368 return 0;
8369}
8370
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008371/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008372/// from this value cannot trap. If it is not obviously safe to load from the
8373/// specified pointer, we do a quick local scan of the basic block containing
8374/// ScanFrom, to determine if the address is already accessed.
8375static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8376 // If it is an alloca or global variable, it is always safe to load from.
8377 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8378
8379 // Otherwise, be a little bit agressive by scanning the local block where we
8380 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008381 // from/to. If so, the previous load or store would have already trapped,
8382 // so there is no harm doing an extra load (also, CSE will later eliminate
8383 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008384 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8385
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008386 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008387 --BBI;
8388
8389 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8390 if (LI->getOperand(0) == V) return true;
8391 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8392 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008393
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008394 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008395 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008396}
8397
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008398Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8399 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008400
Chris Lattnera9d84e32005-05-01 04:24:53 +00008401 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008402 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008403 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8404 return Res;
8405
8406 // None of the following transforms are legal for volatile loads.
8407 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008408
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008409 if (&LI.getParent()->front() != &LI) {
8410 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008411 // If the instruction immediately before this is a store to the same
8412 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008413 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8414 if (SI->getOperand(1) == LI.getOperand(0))
8415 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008416 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8417 if (LIB->getOperand(0) == LI.getOperand(0))
8418 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008419 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008420
8421 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8422 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8423 isa<UndefValue>(GEPI->getOperand(0))) {
8424 // Insert a new store to null instruction before the load to indicate
8425 // that this code is not reachable. We do this instead of inserting
8426 // an unreachable instruction directly because we cannot modify the
8427 // CFG.
8428 new StoreInst(UndefValue::get(LI.getType()),
8429 Constant::getNullValue(Op->getType()), &LI);
8430 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8431 }
8432
Chris Lattner81a7a232004-10-16 18:11:37 +00008433 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008434 // load null/undef -> undef
8435 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008436 // Insert a new store to null instruction before the load to indicate that
8437 // this code is not reachable. We do this instead of inserting an
8438 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008439 new StoreInst(UndefValue::get(LI.getType()),
8440 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008441 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008442 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008443
Chris Lattner81a7a232004-10-16 18:11:37 +00008444 // Instcombine load (constant global) into the value loaded.
8445 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008446 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008447 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008448
Chris Lattner81a7a232004-10-16 18:11:37 +00008449 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8451 if (CE->getOpcode() == Instruction::GetElementPtr) {
8452 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008453 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008454 if (Constant *V =
8455 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008456 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008457 if (CE->getOperand(0)->isNullValue()) {
8458 // Insert a new store to null instruction before the load to indicate
8459 // that this code is not reachable. We do this instead of inserting
8460 // an unreachable instruction directly because we cannot modify the
8461 // CFG.
8462 new StoreInst(UndefValue::get(LI.getType()),
8463 Constant::getNullValue(Op->getType()), &LI);
8464 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8465 }
8466
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008467 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008468 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8469 return Res;
8470 }
8471 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008472
Chris Lattnera9d84e32005-05-01 04:24:53 +00008473 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008474 // Change select and PHI nodes to select values instead of addresses: this
8475 // helps alias analysis out a lot, allows many others simplifications, and
8476 // exposes redundancy in the code.
8477 //
8478 // Note that we cannot do the transformation unless we know that the
8479 // introduced loads cannot trap! Something like this is valid as long as
8480 // the condition is always false: load (select bool %C, int* null, int* %G),
8481 // but it would not be valid if we transformed it to load from null
8482 // unconditionally.
8483 //
8484 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8485 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008486 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8487 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008488 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008489 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008490 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008491 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008492 return new SelectInst(SI->getCondition(), V1, V2);
8493 }
8494
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008495 // load (select (cond, null, P)) -> load P
8496 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8497 if (C->isNullValue()) {
8498 LI.setOperand(0, SI->getOperand(2));
8499 return &LI;
8500 }
8501
8502 // load (select (cond, P, null)) -> load P
8503 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8504 if (C->isNullValue()) {
8505 LI.setOperand(0, SI->getOperand(1));
8506 return &LI;
8507 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008508 }
8509 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008510 return 0;
8511}
8512
Reid Spencere928a152007-01-19 21:20:31 +00008513/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008514/// when possible.
8515static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8516 User *CI = cast<User>(SI.getOperand(1));
8517 Value *CastOp = CI->getOperand(0);
8518
8519 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8520 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8521 const Type *SrcPTy = SrcTy->getElementType();
8522
Reid Spencer31a4ef42007-01-22 05:51:25 +00008523 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008524 // If the source is an array, the code below will not succeed. Check to
8525 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8526 // constants.
8527 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8528 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8529 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008530 Value* Idxs[2];
8531 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8532 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008533 SrcTy = cast<PointerType>(CastOp->getType());
8534 SrcPTy = SrcTy->getElementType();
8535 }
8536
Reid Spencer9a4bed02007-01-20 23:35:48 +00008537 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8538 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8539 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008540
8541 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008542 // the same size. Instead of casting the pointer before
8543 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008544 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008545 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008546 Instruction::CastOps opcode = Instruction::BitCast;
8547 const Type* CastSrcTy = SIOp0->getType();
8548 const Type* CastDstTy = SrcPTy;
8549 if (isa<PointerType>(CastDstTy)) {
8550 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008551 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008552 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008553 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008554 opcode = Instruction::PtrToInt;
8555 }
8556 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008557 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008558 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008559 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008560 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8561 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008562 return new StoreInst(NewCast, CastOp);
8563 }
8564 }
8565 }
8566 return 0;
8567}
8568
Chris Lattner31f486c2005-01-31 05:36:43 +00008569Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8570 Value *Val = SI.getOperand(0);
8571 Value *Ptr = SI.getOperand(1);
8572
8573 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008574 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008575 ++NumCombined;
8576 return 0;
8577 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008578
8579 // If the RHS is an alloca with a single use, zapify the store, making the
8580 // alloca dead.
8581 if (Ptr->hasOneUse()) {
8582 if (isa<AllocaInst>(Ptr)) {
8583 EraseInstFromFunction(SI);
8584 ++NumCombined;
8585 return 0;
8586 }
8587
8588 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8589 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8590 GEP->getOperand(0)->hasOneUse()) {
8591 EraseInstFromFunction(SI);
8592 ++NumCombined;
8593 return 0;
8594 }
8595 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008596
Chris Lattner5997cf92006-02-08 03:25:32 +00008597 // Do really simple DSE, to catch cases where there are several consequtive
8598 // stores to the same location, separated by a few arithmetic operations. This
8599 // situation often occurs with bitfield accesses.
8600 BasicBlock::iterator BBI = &SI;
8601 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8602 --ScanInsts) {
8603 --BBI;
8604
8605 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8606 // Prev store isn't volatile, and stores to the same location?
8607 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8608 ++NumDeadStore;
8609 ++BBI;
8610 EraseInstFromFunction(*PrevSI);
8611 continue;
8612 }
8613 break;
8614 }
8615
Chris Lattnerdab43b22006-05-26 19:19:20 +00008616 // If this is a load, we have to stop. However, if the loaded value is from
8617 // the pointer we're loading and is producing the pointer we're storing,
8618 // then *this* store is dead (X = load P; store X -> P).
8619 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8620 if (LI == Val && LI->getOperand(0) == Ptr) {
8621 EraseInstFromFunction(SI);
8622 ++NumCombined;
8623 return 0;
8624 }
8625 // Otherwise, this is a load from some other location. Stores before it
8626 // may not be dead.
8627 break;
8628 }
8629
Chris Lattner5997cf92006-02-08 03:25:32 +00008630 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008631 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008632 break;
8633 }
8634
8635
8636 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008637
8638 // store X, null -> turns into 'unreachable' in SimplifyCFG
8639 if (isa<ConstantPointerNull>(Ptr)) {
8640 if (!isa<UndefValue>(Val)) {
8641 SI.setOperand(0, UndefValue::get(Val->getType()));
8642 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008643 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008644 ++NumCombined;
8645 }
8646 return 0; // Do not modify these!
8647 }
8648
8649 // store undef, Ptr -> noop
8650 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008651 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008652 ++NumCombined;
8653 return 0;
8654 }
8655
Chris Lattner72684fe2005-01-31 05:51:45 +00008656 // If the pointer destination is a cast, see if we can fold the cast into the
8657 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008658 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008659 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8660 return Res;
8661 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008662 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008663 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8664 return Res;
8665
Chris Lattner219175c2005-09-12 23:23:25 +00008666
8667 // If this store is the last instruction in the basic block, and if the block
8668 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008669 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008670 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8671 if (BI->isUnconditional()) {
8672 // Check to see if the successor block has exactly two incoming edges. If
8673 // so, see if the other predecessor contains a store to the same location.
8674 // if so, insert a PHI node (if needed) and move the stores down.
8675 BasicBlock *Dest = BI->getSuccessor(0);
8676
8677 pred_iterator PI = pred_begin(Dest);
8678 BasicBlock *Other = 0;
8679 if (*PI != BI->getParent())
8680 Other = *PI;
8681 ++PI;
8682 if (PI != pred_end(Dest)) {
8683 if (*PI != BI->getParent())
8684 if (Other)
8685 Other = 0;
8686 else
8687 Other = *PI;
8688 if (++PI != pred_end(Dest))
8689 Other = 0;
8690 }
8691 if (Other) { // If only one other pred...
8692 BBI = Other->getTerminator();
8693 // Make sure this other block ends in an unconditional branch and that
8694 // there is an instruction before the branch.
8695 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8696 BBI != Other->begin()) {
8697 --BBI;
8698 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8699
8700 // If this instruction is a store to the same location.
8701 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8702 // Okay, we know we can perform this transformation. Insert a PHI
8703 // node now if we need it.
8704 Value *MergedVal = OtherStore->getOperand(0);
8705 if (MergedVal != SI.getOperand(0)) {
8706 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8707 PN->reserveOperandSpace(2);
8708 PN->addIncoming(SI.getOperand(0), SI.getParent());
8709 PN->addIncoming(OtherStore->getOperand(0), Other);
8710 MergedVal = InsertNewInstBefore(PN, Dest->front());
8711 }
8712
8713 // Advance to a place where it is safe to insert the new store and
8714 // insert it.
8715 BBI = Dest->begin();
8716 while (isa<PHINode>(BBI)) ++BBI;
8717 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8718 OtherStore->isVolatile()), *BBI);
8719
8720 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008721 EraseInstFromFunction(SI);
8722 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008723 ++NumCombined;
8724 return 0;
8725 }
8726 }
8727 }
8728 }
8729
Chris Lattner31f486c2005-01-31 05:36:43 +00008730 return 0;
8731}
8732
8733
Chris Lattner9eef8a72003-06-04 04:46:00 +00008734Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8735 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008736 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008737 BasicBlock *TrueDest;
8738 BasicBlock *FalseDest;
8739 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8740 !isa<Constant>(X)) {
8741 // Swap Destinations and condition...
8742 BI.setCondition(X);
8743 BI.setSuccessor(0, FalseDest);
8744 BI.setSuccessor(1, TrueDest);
8745 return &BI;
8746 }
8747
Reid Spencer266e42b2006-12-23 06:05:41 +00008748 // Cannonicalize fcmp_one -> fcmp_oeq
8749 FCmpInst::Predicate FPred; Value *Y;
8750 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8751 TrueDest, FalseDest)))
8752 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8753 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8754 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008755 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008756 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8757 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008758 // Swap Destinations and condition...
8759 BI.setCondition(NewSCC);
8760 BI.setSuccessor(0, FalseDest);
8761 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008762 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008763 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008764 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008765 return &BI;
8766 }
8767
8768 // Cannonicalize icmp_ne -> icmp_eq
8769 ICmpInst::Predicate IPred;
8770 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8771 TrueDest, FalseDest)))
8772 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8773 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8774 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8775 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008776 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008777 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8778 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008779 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008780 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008781 BI.setSuccessor(0, FalseDest);
8782 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008783 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008784 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008785 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008786 return &BI;
8787 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008788
Chris Lattner9eef8a72003-06-04 04:46:00 +00008789 return 0;
8790}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008791
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008792Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8793 Value *Cond = SI.getCondition();
8794 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8795 if (I->getOpcode() == Instruction::Add)
8796 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8797 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8798 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008799 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008800 AddRHS));
8801 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008802 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008803 return &SI;
8804 }
8805 }
8806 return 0;
8807}
8808
Chris Lattner6bc98652006-03-05 00:22:33 +00008809/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8810/// is to leave as a vector operation.
8811static bool CheapToScalarize(Value *V, bool isConstant) {
8812 if (isa<ConstantAggregateZero>(V))
8813 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008814 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008815 if (isConstant) return true;
8816 // If all elts are the same, we can extract.
8817 Constant *Op0 = C->getOperand(0);
8818 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8819 if (C->getOperand(i) != Op0)
8820 return false;
8821 return true;
8822 }
8823 Instruction *I = dyn_cast<Instruction>(V);
8824 if (!I) return false;
8825
8826 // Insert element gets simplified to the inserted element or is deleted if
8827 // this is constant idx extract element and its a constant idx insertelt.
8828 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8829 isa<ConstantInt>(I->getOperand(2)))
8830 return true;
8831 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8832 return true;
8833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8834 if (BO->hasOneUse() &&
8835 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8836 CheapToScalarize(BO->getOperand(1), isConstant)))
8837 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008838 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8839 if (CI->hasOneUse() &&
8840 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8841 CheapToScalarize(CI->getOperand(1), isConstant)))
8842 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008843
8844 return false;
8845}
8846
Chris Lattner945e4372007-02-14 05:52:17 +00008847/// Read and decode a shufflevector mask.
8848///
8849/// It turns undef elements into values that are larger than the number of
8850/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008851static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8852 unsigned NElts = SVI->getType()->getNumElements();
8853 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8854 return std::vector<unsigned>(NElts, 0);
8855 if (isa<UndefValue>(SVI->getOperand(2)))
8856 return std::vector<unsigned>(NElts, 2*NElts);
8857
8858 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008859 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008860 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8861 if (isa<UndefValue>(CP->getOperand(i)))
8862 Result.push_back(NElts*2); // undef -> 8
8863 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008864 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008865 return Result;
8866}
8867
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008868/// FindScalarElement - Given a vector and an element number, see if the scalar
8869/// value is already around as a register, for example if it were inserted then
8870/// extracted from the vector.
8871static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008872 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8873 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008874 unsigned Width = PTy->getNumElements();
8875 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008876 return UndefValue::get(PTy->getElementType());
8877
8878 if (isa<UndefValue>(V))
8879 return UndefValue::get(PTy->getElementType());
8880 else if (isa<ConstantAggregateZero>(V))
8881 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008882 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008883 return CP->getOperand(EltNo);
8884 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8885 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008886 if (!isa<ConstantInt>(III->getOperand(2)))
8887 return 0;
8888 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008889
8890 // If this is an insert to the element we are looking for, return the
8891 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008892 if (EltNo == IIElt)
8893 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008894
8895 // Otherwise, the insertelement doesn't modify the value, recurse on its
8896 // vector input.
8897 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008898 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008899 unsigned InEl = getShuffleMask(SVI)[EltNo];
8900 if (InEl < Width)
8901 return FindScalarElement(SVI->getOperand(0), InEl);
8902 else if (InEl < Width*2)
8903 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8904 else
8905 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008906 }
8907
8908 // Otherwise, we don't know.
8909 return 0;
8910}
8911
Robert Bocchinoa8352962006-01-13 22:48:06 +00008912Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008913
Chris Lattner92346c32006-03-31 18:25:14 +00008914 // If packed val is undef, replace extract with scalar undef.
8915 if (isa<UndefValue>(EI.getOperand(0)))
8916 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8917
8918 // If packed val is constant 0, replace extract with scalar 0.
8919 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8920 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8921
Reid Spencerd84d35b2007-02-15 02:26:10 +00008922 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008923 // If packed val is constant with uniform operands, replace EI
8924 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008925 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008926 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008927 if (C->getOperand(i) != op0) {
8928 op0 = 0;
8929 break;
8930 }
8931 if (op0)
8932 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008933 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008934
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008935 // If extracting a specified index from the vector, see if we can recursively
8936 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008937 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008938 // This instruction only demands the single element from the input vector.
8939 // If the input vector has a single use, simplify it based on this use
8940 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008941 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008942 if (EI.getOperand(0)->hasOneUse()) {
8943 uint64_t UndefElts;
8944 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008945 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008946 UndefElts)) {
8947 EI.setOperand(0, V);
8948 return &EI;
8949 }
8950 }
8951
Reid Spencere0fc4df2006-10-20 07:07:24 +00008952 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008953 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008954 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008955
Chris Lattner83f65782006-05-25 22:53:38 +00008956 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008957 if (I->hasOneUse()) {
8958 // Push extractelement into predecessor operation if legal and
8959 // profitable to do so
8960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008961 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8962 if (CheapToScalarize(BO, isConstantElt)) {
8963 ExtractElementInst *newEI0 =
8964 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8965 EI.getName()+".lhs");
8966 ExtractElementInst *newEI1 =
8967 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8968 EI.getName()+".rhs");
8969 InsertNewInstBefore(newEI0, EI);
8970 InsertNewInstBefore(newEI1, EI);
8971 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8972 }
Reid Spencerde46e482006-11-02 20:25:50 +00008973 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008974 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008975 PointerType::get(EI.getType()), EI);
8976 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008977 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008978 InsertNewInstBefore(GEP, EI);
8979 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008980 }
8981 }
8982 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8983 // Extracting the inserted element?
8984 if (IE->getOperand(2) == EI.getOperand(1))
8985 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8986 // If the inserted and extracted elements are constants, they must not
8987 // be the same value, extract from the pre-inserted value instead.
8988 if (isa<Constant>(IE->getOperand(2)) &&
8989 isa<Constant>(EI.getOperand(1))) {
8990 AddUsesToWorkList(EI);
8991 EI.setOperand(0, IE->getOperand(0));
8992 return &EI;
8993 }
8994 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8995 // If this is extracting an element from a shufflevector, figure out where
8996 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008997 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8998 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008999 Value *Src;
9000 if (SrcIdx < SVI->getType()->getNumElements())
9001 Src = SVI->getOperand(0);
9002 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9003 SrcIdx -= SVI->getType()->getNumElements();
9004 Src = SVI->getOperand(1);
9005 } else {
9006 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009007 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009008 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009009 }
9010 }
Chris Lattner83f65782006-05-25 22:53:38 +00009011 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009012 return 0;
9013}
9014
Chris Lattner90951862006-04-16 00:51:47 +00009015/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9016/// elements from either LHS or RHS, return the shuffle mask and true.
9017/// Otherwise, return false.
9018static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9019 std::vector<Constant*> &Mask) {
9020 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9021 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009022 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009023
9024 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009025 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009026 return true;
9027 } else if (V == LHS) {
9028 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009029 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009030 return true;
9031 } else if (V == RHS) {
9032 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009033 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009034 return true;
9035 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9036 // If this is an insert of an extract from some other vector, include it.
9037 Value *VecOp = IEI->getOperand(0);
9038 Value *ScalarOp = IEI->getOperand(1);
9039 Value *IdxOp = IEI->getOperand(2);
9040
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009041 if (!isa<ConstantInt>(IdxOp))
9042 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009043 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009044
9045 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9046 // Okay, we can handle this if the vector we are insertinting into is
9047 // transitively ok.
9048 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9049 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009050 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009051 return true;
9052 }
9053 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9054 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009055 EI->getOperand(0)->getType() == V->getType()) {
9056 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009057 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009058
9059 // This must be extracting from either LHS or RHS.
9060 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9061 // Okay, we can handle this if the vector we are insertinting into is
9062 // transitively ok.
9063 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9064 // If so, update the mask to reflect the inserted value.
9065 if (EI->getOperand(0) == LHS) {
9066 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009067 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009068 } else {
9069 assert(EI->getOperand(0) == RHS);
9070 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009071 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009072
9073 }
9074 return true;
9075 }
9076 }
9077 }
9078 }
9079 }
9080 // TODO: Handle shufflevector here!
9081
9082 return false;
9083}
9084
9085/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9086/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9087/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009088static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009089 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009090 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009091 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009092 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009093 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009094
9095 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009096 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009097 return V;
9098 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009099 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009100 return V;
9101 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9102 // If this is an insert of an extract from some other vector, include it.
9103 Value *VecOp = IEI->getOperand(0);
9104 Value *ScalarOp = IEI->getOperand(1);
9105 Value *IdxOp = IEI->getOperand(2);
9106
9107 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9108 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9109 EI->getOperand(0)->getType() == V->getType()) {
9110 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009111 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9112 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009113
9114 // Either the extracted from or inserted into vector must be RHSVec,
9115 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009116 if (EI->getOperand(0) == RHS || RHS == 0) {
9117 RHS = EI->getOperand(0);
9118 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009119 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009120 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009121 return V;
9122 }
9123
Chris Lattner90951862006-04-16 00:51:47 +00009124 if (VecOp == RHS) {
9125 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009126 // Everything but the extracted element is replaced with the RHS.
9127 for (unsigned i = 0; i != NumElts; ++i) {
9128 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009129 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009130 }
9131 return V;
9132 }
Chris Lattner90951862006-04-16 00:51:47 +00009133
9134 // If this insertelement is a chain that comes from exactly these two
9135 // vectors, return the vector and the effective shuffle.
9136 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9137 return EI->getOperand(0);
9138
Chris Lattner39fac442006-04-15 01:39:45 +00009139 }
9140 }
9141 }
Chris Lattner90951862006-04-16 00:51:47 +00009142 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009143
9144 // Otherwise, can't do anything fancy. Return an identity vector.
9145 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009146 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009147 return V;
9148}
9149
9150Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9151 Value *VecOp = IE.getOperand(0);
9152 Value *ScalarOp = IE.getOperand(1);
9153 Value *IdxOp = IE.getOperand(2);
9154
9155 // If the inserted element was extracted from some other vector, and if the
9156 // indexes are constant, try to turn this into a shufflevector operation.
9157 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9158 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9159 EI->getOperand(0)->getType() == IE.getType()) {
9160 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009161 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9162 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009163
9164 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9165 return ReplaceInstUsesWith(IE, VecOp);
9166
9167 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9168 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9169
9170 // If we are extracting a value from a vector, then inserting it right
9171 // back into the same place, just use the input vector.
9172 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9173 return ReplaceInstUsesWith(IE, VecOp);
9174
9175 // We could theoretically do this for ANY input. However, doing so could
9176 // turn chains of insertelement instructions into a chain of shufflevector
9177 // instructions, and right now we do not merge shufflevectors. As such,
9178 // only do this in a situation where it is clear that there is benefit.
9179 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9180 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9181 // the values of VecOp, except then one read from EIOp0.
9182 // Build a new shuffle mask.
9183 std::vector<Constant*> Mask;
9184 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009185 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009186 else {
9187 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009188 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009189 NumVectorElts));
9190 }
Reid Spencerc635f472006-12-31 05:48:39 +00009191 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009192 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009193 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009194 }
9195
9196 // If this insertelement isn't used by some other insertelement, turn it
9197 // (and any insertelements it points to), into one big shuffle.
9198 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9199 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009200 Value *RHS = 0;
9201 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9202 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9203 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009204 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009205 }
9206 }
9207 }
9208
9209 return 0;
9210}
9211
9212
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009213Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9214 Value *LHS = SVI.getOperand(0);
9215 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009216 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009217
9218 bool MadeChange = false;
9219
Chris Lattner2deeaea2006-10-05 06:55:50 +00009220 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009221 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009222 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9223
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009224 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009225 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009226 if (isa<UndefValue>(SVI.getOperand(1))) {
9227 // Scan to see if there are any references to the RHS. If so, replace them
9228 // with undef element refs and set MadeChange to true.
9229 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9230 if (Mask[i] >= e && Mask[i] != 2*e) {
9231 Mask[i] = 2*e;
9232 MadeChange = true;
9233 }
9234 }
9235
9236 if (MadeChange) {
9237 // Remap any references to RHS to use LHS.
9238 std::vector<Constant*> Elts;
9239 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9240 if (Mask[i] == 2*e)
9241 Elts.push_back(UndefValue::get(Type::Int32Ty));
9242 else
9243 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9244 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009245 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009246 }
9247 }
Chris Lattner39fac442006-04-15 01:39:45 +00009248
Chris Lattner12249be2006-05-25 23:48:38 +00009249 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9250 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9251 if (LHS == RHS || isa<UndefValue>(LHS)) {
9252 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009253 // shuffle(undef,undef,mask) -> undef.
9254 return ReplaceInstUsesWith(SVI, LHS);
9255 }
9256
Chris Lattner12249be2006-05-25 23:48:38 +00009257 // Remap any references to RHS to use LHS.
9258 std::vector<Constant*> Elts;
9259 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009260 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009261 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009262 else {
9263 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9264 (Mask[i] < e && isa<UndefValue>(LHS)))
9265 Mask[i] = 2*e; // Turn into undef.
9266 else
9267 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009268 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009269 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009270 }
Chris Lattner12249be2006-05-25 23:48:38 +00009271 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009272 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009273 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009274 LHS = SVI.getOperand(0);
9275 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009276 MadeChange = true;
9277 }
9278
Chris Lattner0e477162006-05-26 00:29:06 +00009279 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009280 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009281
Chris Lattner12249be2006-05-25 23:48:38 +00009282 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9283 if (Mask[i] >= e*2) continue; // Ignore undef values.
9284 // Is this an identity shuffle of the LHS value?
9285 isLHSID &= (Mask[i] == i);
9286
9287 // Is this an identity shuffle of the RHS value?
9288 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009289 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009290
Chris Lattner12249be2006-05-25 23:48:38 +00009291 // Eliminate identity shuffles.
9292 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9293 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009294
Chris Lattner0e477162006-05-26 00:29:06 +00009295 // If the LHS is a shufflevector itself, see if we can combine it with this
9296 // one without producing an unusual shuffle. Here we are really conservative:
9297 // we are absolutely afraid of producing a shuffle mask not in the input
9298 // program, because the code gen may not be smart enough to turn a merged
9299 // shuffle into two specific shuffles: it may produce worse code. As such,
9300 // we only merge two shuffles if the result is one of the two input shuffle
9301 // masks. In this case, merging the shuffles just removes one instruction,
9302 // which we know is safe. This is good for things like turning:
9303 // (splat(splat)) -> splat.
9304 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9305 if (isa<UndefValue>(RHS)) {
9306 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9307
9308 std::vector<unsigned> NewMask;
9309 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9310 if (Mask[i] >= 2*e)
9311 NewMask.push_back(2*e);
9312 else
9313 NewMask.push_back(LHSMask[Mask[i]]);
9314
9315 // If the result mask is equal to the src shuffle or this shuffle mask, do
9316 // the replacement.
9317 if (NewMask == LHSMask || NewMask == Mask) {
9318 std::vector<Constant*> Elts;
9319 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9320 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009321 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009322 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009323 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009324 }
9325 }
9326 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9327 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009328 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009329 }
9330 }
9331 }
Chris Lattner4284f642007-01-30 22:32:46 +00009332
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009333 return MadeChange ? &SVI : 0;
9334}
9335
9336
Robert Bocchinoa8352962006-01-13 22:48:06 +00009337
Chris Lattner39c98bb2004-12-08 23:43:58 +00009338
9339/// TryToSinkInstruction - Try to move the specified instruction from its
9340/// current block into the beginning of DestBlock, which can only happen if it's
9341/// safe to move the instruction past all of the instructions between it and the
9342/// end of its block.
9343static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9344 assert(I->hasOneUse() && "Invariants didn't hold!");
9345
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009346 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9347 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009348
Chris Lattner39c98bb2004-12-08 23:43:58 +00009349 // Do not sink alloca instructions out of the entry block.
9350 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9351 return false;
9352
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009353 // We can only sink load instructions if there is nothing between the load and
9354 // the end of block that could change the value.
9355 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009356 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9357 Scan != E; ++Scan)
9358 if (Scan->mayWriteToMemory())
9359 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009360 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009361
9362 BasicBlock::iterator InsertPos = DestBlock->begin();
9363 while (isa<PHINode>(InsertPos)) ++InsertPos;
9364
Chris Lattner9f269e42005-08-08 19:11:57 +00009365 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009366 ++NumSunkInst;
9367 return true;
9368}
9369
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009370
9371/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9372/// all reachable code to the worklist.
9373///
9374/// This has a couple of tricks to make the code faster and more powerful. In
9375/// particular, we constant fold and DCE instructions as we go, to avoid adding
9376/// them to the worklist (this significantly speeds up instcombine on code where
9377/// many instructions are dead or constant). Additionally, if we find a branch
9378/// whose condition is a known constant, we only visit the reachable successors.
9379///
9380static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009381 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009382 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009383 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009384 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009385 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009386
9387 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9388 Instruction *Inst = BBI++;
9389
9390 // DCE instruction if trivially dead.
9391 if (isInstructionTriviallyDead(Inst)) {
9392 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009393 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009394 Inst->eraseFromParent();
9395 continue;
9396 }
9397
9398 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009399 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009400 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009401 Inst->replaceAllUsesWith(C);
9402 ++NumConstProp;
9403 Inst->eraseFromParent();
9404 continue;
9405 }
9406
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009407 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009408 }
9409
9410 // Recursively visit successors. If this is a branch or switch on a constant,
9411 // only visit the reachable successor.
9412 TerminatorInst *TI = BB->getTerminator();
9413 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009414 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009415 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009416 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009417 return;
9418 }
9419 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9420 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9421 // See if this is an explicit destination.
9422 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9423 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009424 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009425 return;
9426 }
9427
9428 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009429 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009430 return;
9431 }
9432 }
9433
9434 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009435 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009436}
9437
Chris Lattner960a5432007-03-03 02:04:50 +00009438bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009439 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009440 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009441
9442 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9443 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009444
Chris Lattner4ed40f72005-07-07 20:40:38 +00009445 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009446 // Do a depth-first traversal of the function, populate the worklist with
9447 // the reachable instructions. Ignore blocks that are not reachable. Keep
9448 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009449 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009450 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009451
Chris Lattner4ed40f72005-07-07 20:40:38 +00009452 // Do a quick scan over the function. If we find any blocks that are
9453 // unreachable, remove any instructions inside of them. This prevents
9454 // the instcombine code from having to deal with some bad special cases.
9455 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9456 if (!Visited.count(BB)) {
9457 Instruction *Term = BB->getTerminator();
9458 while (Term != BB->begin()) { // Remove instrs bottom-up
9459 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009460
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009461 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009462 ++NumDeadInst;
9463
9464 if (!I->use_empty())
9465 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9466 I->eraseFromParent();
9467 }
9468 }
9469 }
Chris Lattnerca081252001-12-14 16:52:21 +00009470
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009471 while (!Worklist.empty()) {
9472 Instruction *I = RemoveOneFromWorkList();
9473 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009474
Chris Lattner1443bc52006-05-11 17:11:52 +00009475 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009476 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009477 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009478 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009479 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009480 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009481
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009482 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009483
9484 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009485 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009486 continue;
9487 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009488
Chris Lattner1443bc52006-05-11 17:11:52 +00009489 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009490 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009491 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009492
Chris Lattner1443bc52006-05-11 17:11:52 +00009493 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009494 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009495 ReplaceInstUsesWith(*I, C);
9496
Chris Lattner99f48c62002-09-02 04:59:56 +00009497 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009498 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009499 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009500 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009501 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009502
Chris Lattner39c98bb2004-12-08 23:43:58 +00009503 // See if we can trivially sink this instruction to a successor basic block.
9504 if (I->hasOneUse()) {
9505 BasicBlock *BB = I->getParent();
9506 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9507 if (UserParent != BB) {
9508 bool UserIsSuccessor = false;
9509 // See if the user is one of our successors.
9510 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9511 if (*SI == UserParent) {
9512 UserIsSuccessor = true;
9513 break;
9514 }
9515
9516 // If the user is one of our immediate successors, and if that successor
9517 // only has us as a predecessors (we'd have to split the critical edge
9518 // otherwise), we can keep going.
9519 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9520 next(pred_begin(UserParent)) == pred_end(UserParent))
9521 // Okay, the CFG is simple enough, try to sink this instruction.
9522 Changed |= TryToSinkInstruction(I, UserParent);
9523 }
9524 }
9525
Chris Lattnerca081252001-12-14 16:52:21 +00009526 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009527 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009528 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009529 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009530 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009531 DOUT << "IC: Old = " << *I
9532 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009533
Chris Lattner396dbfe2004-06-09 05:08:07 +00009534 // Everything uses the new instruction now.
9535 I->replaceAllUsesWith(Result);
9536
9537 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009538 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009539 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009540
Chris Lattner6e0123b2007-02-11 01:23:03 +00009541 // Move the name to the new instruction first.
9542 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009543
9544 // Insert the new instruction into the basic block...
9545 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009546 BasicBlock::iterator InsertPos = I;
9547
9548 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9549 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9550 ++InsertPos;
9551
9552 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009553
Chris Lattner63d75af2004-05-01 23:27:23 +00009554 // Make sure that we reprocess all operands now that we reduced their
9555 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009556 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009557
Chris Lattner396dbfe2004-06-09 05:08:07 +00009558 // Instructions can end up on the worklist more than once. Make sure
9559 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009560 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009561
9562 // Erase the old instruction.
9563 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009564 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009565 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009566
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009567 // If the instruction was modified, it's possible that it is now dead.
9568 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009569 if (isInstructionTriviallyDead(I)) {
9570 // Make sure we process all operands now that we are reducing their
9571 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009572 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009573
Chris Lattner63d75af2004-05-01 23:27:23 +00009574 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009575 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009576 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009577 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009578 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009579 AddToWorkList(I);
9580 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009581 }
Chris Lattner053c0932002-05-14 15:24:07 +00009582 }
Chris Lattner260ab202002-04-18 17:39:14 +00009583 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009584 }
9585 }
9586
Chris Lattner960a5432007-03-03 02:04:50 +00009587 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009588 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009589}
9590
Chris Lattner960a5432007-03-03 02:04:50 +00009591
9592bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009593 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9594
Chris Lattner960a5432007-03-03 02:04:50 +00009595 bool EverMadeChange = false;
9596
9597 // Iterate while there is work to do.
9598 unsigned Iteration = 0;
9599 while (DoOneIteration(F, Iteration++))
9600 EverMadeChange = true;
9601 return EverMadeChange;
9602}
9603
Brian Gaeke38b79e82004-07-27 17:43:21 +00009604FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009605 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009606}
Brian Gaeke960707c2003-11-11 22:41:34 +00009607