blob: 4208e9685628d63292564b6abf10b0c947eaf062 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid 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
Reid Spencer1791f232007-03-12 17:25:59 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000325
Reid Spencer1791f232007-03-12 17:25:59 +0000326 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
327 APInt& KnownZero, APInt& KnownOne,
328 unsigned Depth = 0);
329
Chris Lattner2deeaea2006-10-05 06:55:50 +0000330 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
331 uint64_t &UndefElts, unsigned Depth = 0);
332
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000333 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
334 // PHI node as operand #0, see if we can fold the instruction into the PHI
335 // (which is only possible if all operands to the PHI are constants).
336 Instruction *FoldOpIntoPhi(Instruction &I);
337
Chris Lattner7515cab2004-11-14 19:13:23 +0000338 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
339 // operator and they all are only used by the PHI, PHI together their
340 // inputs, and do the operation once, to the result of the PHI.
341 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000342 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
343
344
Zhou Sheng75b871f2007-01-11 12:24:14 +0000345 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
346 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000347
Zhou Sheng75b871f2007-01-11 12:24:14 +0000348 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000349 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000350 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000351 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000352 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000353 Instruction *MatchBSwap(BinaryOperator &I);
354
Reid Spencer74a528b2006-12-13 18:21:21 +0000355 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000356 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000357
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000358 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000359}
360
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000361// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000362// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000363static unsigned getComplexity(Value *V) {
364 if (isa<Instruction>(V)) {
365 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000366 return 3;
367 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000368 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000369 if (isa<Argument>(V)) return 3;
370 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000371}
Chris Lattner260ab202002-04-18 17:39:14 +0000372
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373// isOnlyUse - Return true if this instruction will be deleted if we stop using
374// it.
375static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000376 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000377}
378
Chris Lattnere79e8542004-02-23 06:38:22 +0000379// getPromotedType - Return the specified type promoted as it would be to pass
380// though a va_arg area...
381static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000382 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
383 if (ITy->getBitWidth() < 32)
384 return Type::Int32Ty;
385 } else if (Ty == Type::FloatTy)
386 return Type::DoubleTy;
387 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000388}
389
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000390/// getBitCastOperand - If the specified operand is a CastInst or a constant
391/// expression bitcast, return the operand value, otherwise return null.
392static Value *getBitCastOperand(Value *V) {
393 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000394 return I->getOperand(0);
395 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000396 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000397 return CE->getOperand(0);
398 return 0;
399}
400
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000401/// This function is a wrapper around CastInst::isEliminableCastPair. It
402/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000403static Instruction::CastOps
404isEliminableCastPair(
405 const CastInst *CI, ///< The first cast instruction
406 unsigned opcode, ///< The opcode of the second cast instruction
407 const Type *DstTy, ///< The target type for the second cast instruction
408 TargetData *TD ///< The target data for pointer size
409) {
410
411 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
412 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000414 // Get the opcodes of the two Cast instructions
415 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
416 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000417
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000418 return Instruction::CastOps(
419 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
420 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421}
422
423/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
424/// in any code being generated. It does not require codegen if V is simple
425/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000426static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
427 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000428 if (V->getType() == Ty || isa<Constant>(V)) return false;
429
Chris Lattner99155be2006-05-25 23:24:33 +0000430 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000431 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000432 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000433 return false;
434 return true;
435}
436
437/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
438/// InsertBefore instruction. This is specialized a bit to avoid inserting
439/// casts that are known to not do anything...
440///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000441Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
442 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443 Instruction *InsertBefore) {
444 if (V->getType() == DestTy) return V;
445 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000446 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000447
Reid Spencer13bc5d72006-12-12 09:18:51 +0000448 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000449}
450
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000451// SimplifyCommutative - This performs a few simplifications for commutative
452// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000453//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454// 1. Order operands such that they are listed from right (least complex) to
455// left (most complex). This puts constants before unary operators before
456// binary operators.
457//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000458// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
459// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000461bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462 bool Changed = false;
463 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
464 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000465
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000466 if (!I.isAssociative()) return Changed;
467 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000468 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
469 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
470 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000471 Constant *Folded = ConstantExpr::get(I.getOpcode(),
472 cast<Constant>(I.getOperand(1)),
473 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000474 I.setOperand(0, Op->getOperand(0));
475 I.setOperand(1, Folded);
476 return true;
477 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
478 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
479 isOnlyUse(Op) && isOnlyUse(Op1)) {
480 Constant *C1 = cast<Constant>(Op->getOperand(1));
481 Constant *C2 = cast<Constant>(Op1->getOperand(1));
482
483 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000484 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000485 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
486 Op1->getOperand(0),
487 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000488 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000489 I.setOperand(0, New);
490 I.setOperand(1, Folded);
491 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000492 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000493 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000494 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000495}
Chris Lattnerca081252001-12-14 16:52:21 +0000496
Reid Spencer266e42b2006-12-23 06:05:41 +0000497/// SimplifyCompare - For a CmpInst this function just orders the operands
498/// so that theyare listed from right (least complex) to left (most complex).
499/// This puts constants before unary operators before binary operators.
500bool InstCombiner::SimplifyCompare(CmpInst &I) {
501 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
502 return false;
503 I.swapOperands();
504 // Compare instructions are not associative so there's nothing else we can do.
505 return true;
506}
507
Chris Lattnerbb74e222003-03-10 23:06:50 +0000508// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
509// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000510//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000511static inline Value *dyn_castNegVal(Value *V) {
512 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000513 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514
Chris Lattner9ad0d552004-12-14 20:08:06 +0000515 // Constants can be considered to be negated values if they can be folded.
516 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
517 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000518 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000519}
520
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521static inline Value *dyn_castNotVal(Value *V) {
522 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000523 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524
525 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000526 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000527 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000528 return 0;
529}
530
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531// dyn_castFoldableMul - If this value is a multiply that can be folded into
532// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000533// non-constant operand of the multiply, and set CST to point to the multiplier.
534// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000535//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000537 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000539 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000540 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000541 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000542 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000544 // The multiplier is really 1 << CST.
545 Constant *One = ConstantInt::get(V->getType(), 1);
546 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
547 return I->getOperand(0);
548 }
549 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000550 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000551}
Chris Lattner31ae8632002-08-14 17:51:49 +0000552
Chris Lattner0798af32005-01-13 20:14:25 +0000553/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
554/// expression, return it.
555static User *dyn_castGetElementPtr(Value *V) {
556 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
558 if (CE->getOpcode() == Instruction::GetElementPtr)
559 return cast<User>(V);
560 return false;
561}
562
Chris Lattner623826c2004-09-28 21:48:02 +0000563// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *AddOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getAdd(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000568static ConstantInt *SubOne(ConstantInt *C) {
569 return cast<ConstantInt>(ConstantExpr::getSub(C,
570 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000571}
572
Chris Lattner4534dd592006-02-09 07:38:58 +0000573/// ComputeMaskedBits - Determine which of the bits specified in Mask are
574/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000575/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
576/// processing.
577/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
578/// we cannot optimize based on the assumption that it is zero without changing
579/// it to be an explicit zero. If we don't change it to zero, other code could
580/// optimized based on the contradictory assumption that it is non-zero.
581/// Because instcombine aggressively folds operations with undef args anyway,
582/// this won't lose us code quality.
583static void ComputeMaskedBits(Value *V, APInt Mask, APInt& KnownZero,
584 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000585 assert(V && "No Value?");
586 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000587 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaf4341d2007-03-13 02:23:10 +0000588 const IntegerType *VTy = cast<IntegerType>(V->getType());
589 assert(VTy->getBitWidth() == BitWidth &&
590 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000591 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000592 "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000593 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
594 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000595 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000596 KnownZero = ~KnownOne & Mask;
597 return;
598 }
599
Reid Spenceraa696402007-03-08 01:46:38 +0000600 if (Depth == 6 || Mask == 0)
601 return; // Limit search depth.
602
603 Instruction *I = dyn_cast<Instruction>(V);
604 if (!I) return;
605
Zhou Shengaf4341d2007-03-13 02:23:10 +0000606 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000607 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000608 Mask &= APInt::getAllOnesValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000609
610 switch (I->getOpcode()) {
611 case Instruction::And:
612 // If either the LHS or the RHS are Zero, the result is zero.
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownZero;
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618
619 // Output known-1 bits are only known if set in both the LHS & RHS.
620 KnownOne &= KnownOne2;
621 // Output known-0 are known to be clear if zero in either the LHS | RHS.
622 KnownZero |= KnownZero2;
623 return;
624 case Instruction::Or:
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 Mask &= ~KnownOne;
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
628 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
629 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
630
631 // Output known-0 bits are only known if clear in both the LHS & RHS.
632 KnownZero &= KnownZero2;
633 // Output known-1 are known to be set if set in either the LHS | RHS.
634 KnownOne |= KnownOne2;
635 return;
636 case Instruction::Xor: {
637 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Output known-0 bits are known if clear or set in both the LHS & RHS.
643 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
644 // Output known-1 are known to be set if set in only one of the LHS, RHS.
645 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
646 KnownZero = KnownZeroOut;
647 return;
648 }
649 case Instruction::Select:
650 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
654
655 // Only known if known in both the LHS and RHS.
656 KnownOne &= KnownOne2;
657 KnownZero &= KnownZero2;
658 return;
659 case Instruction::FPTrunc:
660 case Instruction::FPExt:
661 case Instruction::FPToUI:
662 case Instruction::FPToSI:
663 case Instruction::SIToFP:
664 case Instruction::PtrToInt:
665 case Instruction::UIToFP:
666 case Instruction::IntToPtr:
667 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000668 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000669 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000670 uint32_t SrcBitWidth =
671 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
672 ComputeMaskedBits(I->getOperand(0), Mask.zext(SrcBitWidth),
673 KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
674 KnownZero.trunc(BitWidth);
675 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000676 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000677 }
Reid Spenceraa696402007-03-08 01:46:38 +0000678 case Instruction::BitCast: {
679 const Type *SrcTy = I->getOperand(0)->getType();
680 if (SrcTy->isInteger()) {
681 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
682 return;
683 }
684 break;
685 }
686 case Instruction::ZExt: {
687 // Compute the bits in the result that are not present in the input.
688 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000689 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000690
Zhou Shengaf4341d2007-03-13 02:23:10 +0000691 uint32_t SrcBitWidth = SrcTy->getBitWidth();
692 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
693 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
695 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000696 KnownZero.zext(BitWidth);
697 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000698 KnownZero |= NewBits;
699 return;
700 }
701 case Instruction::SExt: {
702 // Compute the bits in the result that are not present in the input.
703 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng387d7b12007-03-08 05:42:00 +0000704 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
Reid Spenceraa696402007-03-08 01:46:38 +0000705
Zhou Shengaf4341d2007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth = SrcTy->getBitWidth();
707 ComputeMaskedBits(I->getOperand(0), Mask.trunc(SrcBitWidth),
708 KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000709 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000710 KnownZero.zext(BitWidth);
711 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000712
713 // If the sign bit of the input is known set or clear, then we know the
714 // top bits of the result.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000715 APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
Zhou Shengaf4341d2007-03-13 02:23:10 +0000716 InSignBit.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000717 if ((KnownZero & InSignBit) != 0) { // Input sign bit known zero
718 KnownZero |= NewBits;
719 KnownOne &= ~NewBits;
720 } else if ((KnownOne & InSignBit) != 0) { // Input sign bit known set
721 KnownOne |= NewBits;
722 KnownZero &= ~NewBits;
723 } else { // Input sign bit unknown
724 KnownZero &= ~NewBits;
725 KnownOne &= ~NewBits;
726 }
727 return;
728 }
729 case Instruction::Shl:
730 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
731 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
732 uint64_t ShiftAmt = SA->getZExtValue();
733 Mask = APIntOps::lshr(Mask, ShiftAmt);
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000736 KnownZero <<= ShiftAmt;
737 KnownOne <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000738 KnownZero |= APInt(BitWidth, 1ULL).shl(ShiftAmt)-1; // low bits known zero.
739 return;
740 }
741 break;
742 case Instruction::LShr:
743 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
744 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
745 // Compute the new bits that are at the top now.
746 uint64_t ShiftAmt = SA->getZExtValue();
747 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
748
749 // Unsigned shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000750 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000751 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
753 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
754 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
755 KnownZero |= HighBits; // high bits known zero.
756 return;
757 }
758 break;
759 case Instruction::AShr:
760 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
761 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
762 // Compute the new bits that are at the top now.
763 uint64_t ShiftAmt = SA->getZExtValue();
764 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth-ShiftAmt));
765
766 // Signed shift right.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000767 Mask <<= ShiftAmt;
Reid Spenceraa696402007-03-08 01:46:38 +0000768 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
772
773 // Handle the sign bits and adjust to where it is now in the mask.
Zhou Shengb3e00c42007-03-12 05:44:52 +0000774 APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
Reid Spenceraa696402007-03-08 01:46:38 +0000775
776 if ((KnownZero & SignBit) != 0) { // New bits are known zero.
777 KnownZero |= HighBits;
778 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
779 KnownOne |= HighBits;
780 }
781 return;
782 }
783 break;
784 }
785}
786
787/// ComputeMaskedBits - Determine which of the bits specified in Mask are
788/// known to be either zero or one and return them in the KnownZero/KnownOne
Chris Lattner4534dd592006-02-09 07:38:58 +0000789/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
790/// processing.
Reid Spenceraa696402007-03-08 01:46:38 +0000791static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
Chris Lattner4534dd592006-02-09 07:38:58 +0000792 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000793 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
794 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000795 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000796 // optimized based on the contradictory assumption that it is non-zero.
797 // Because instcombine aggressively folds operations with undef args anyway,
798 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000800 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000801 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000802 KnownZero = ~KnownOne & Mask;
803 return;
804 }
805
806 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000807 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000808 return; // Limit search depth.
809
810 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811 Instruction *I = dyn_cast<Instruction>(V);
812 if (!I) return;
813
Reid Spencera94d3942007-01-19 21:13:56 +0000814 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000815
Chris Lattner0157e7f2006-02-11 09:31:47 +0000816 switch (I->getOpcode()) {
817 case Instruction::And:
818 // If either the LHS or the RHS are Zero, the result is zero.
819 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
820 Mask &= ~KnownZero;
821 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
822 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
823 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
824
825 // Output known-1 bits are only known if set in both the LHS & RHS.
826 KnownOne &= KnownOne2;
827 // Output known-0 are known to be clear if zero in either the LHS | RHS.
828 KnownZero |= KnownZero2;
829 return;
830 case Instruction::Or:
831 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
832 Mask &= ~KnownOne;
833 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
834 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
835 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
836
837 // Output known-0 bits are only known if clear in both the LHS & RHS.
838 KnownZero &= KnownZero2;
839 // Output known-1 are known to be set if set in either the LHS | RHS.
840 KnownOne |= KnownOne2;
841 return;
842 case Instruction::Xor: {
843 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), 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 // Output known-0 bits are known if clear or set in both the LHS & RHS.
849 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
850 // Output known-1 are known to be set if set in only one of the LHS, RHS.
851 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
852 KnownZero = KnownZeroOut;
853 return;
854 }
855 case Instruction::Select:
856 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
857 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
860
861 // Only known if known in both the LHS and RHS.
862 KnownOne &= KnownOne2;
863 KnownZero &= KnownZero2;
864 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000865 case Instruction::FPTrunc:
866 case Instruction::FPExt:
867 case Instruction::FPToUI:
868 case Instruction::FPToSI:
869 case Instruction::SIToFP:
870 case Instruction::PtrToInt:
871 case Instruction::UIToFP:
872 case Instruction::IntToPtr:
873 return; // Can't work with floating point or pointers
874 case Instruction::Trunc:
875 // All these have integer operands
876 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
877 return;
878 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000880 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000881 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000882 return;
883 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000884 break;
885 }
886 case Instruction::ZExt: {
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;
Chris Lattner62010c42005-10-09 06:36:35 +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?");
895 // The top bits are known to be zero.
896 KnownZero |= NewBits;
897 return;
898 }
899 case Instruction::SExt: {
900 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000901 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
902 uint64_t NotIn = ~SrcTy->getBitMask();
903 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000904
Reid Spencera94d3942007-01-19 21:13:56 +0000905 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000908
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
911 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
912 if (KnownZero & InSignBit) { // Input sign bit known zero
913 KnownZero |= NewBits;
914 KnownOne &= ~NewBits;
915 } else if (KnownOne & InSignBit) { // Input sign bit known set
916 KnownOne |= NewBits;
917 KnownZero &= ~NewBits;
918 } else { // Input sign bit unknown
919 KnownZero &= ~NewBits;
920 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000921 }
922 return;
923 }
924 case Instruction::Shl:
925 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000926 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
927 uint64_t ShiftAmt = SA->getZExtValue();
928 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000929 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000931 KnownZero <<= ShiftAmt;
932 KnownOne <<= ShiftAmt;
933 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return;
935 }
936 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000937 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000938 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000939 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000941 uint64_t ShiftAmt = SA->getZExtValue();
942 uint64_t HighBits = (1ULL << ShiftAmt)-1;
943 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000944
Reid Spencerfdff9382006-11-08 06:47:33 +0000945 // Unsigned shift right.
946 Mask <<= ShiftAmt;
947 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
948 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
949 KnownZero >>= ShiftAmt;
950 KnownOne >>= ShiftAmt;
951 KnownZero |= HighBits; // high bits known zero.
952 return;
953 }
954 break;
955 case Instruction::AShr:
956 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
957 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
958 // Compute the new bits that are at the top now.
959 uint64_t ShiftAmt = SA->getZExtValue();
960 uint64_t HighBits = (1ULL << ShiftAmt)-1;
961 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
962
963 // Signed shift right.
964 Mask <<= ShiftAmt;
965 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
966 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
967 KnownZero >>= ShiftAmt;
968 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000969
Reid Spencerfdff9382006-11-08 06:47:33 +0000970 // Handle the sign bits.
971 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
972 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000973
Reid Spencerfdff9382006-11-08 06:47:33 +0000974 if (KnownZero & SignBit) { // New bits are known zero.
975 KnownZero |= HighBits;
976 } else if (KnownOne & SignBit) { // New bits are known one.
977 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000978 }
979 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000980 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000982 }
Chris Lattner92a68652006-02-07 08:05:22 +0000983}
984
985/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
986/// this predicate to simplify operations downstream. Mask is known to be zero
987/// for bits that V cannot have.
988static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000989 uint64_t KnownZero, KnownOne;
990 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
992 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000993}
994
Reid Spencerbb5741f2007-03-08 01:52:58 +0000995/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
996/// this predicate to simplify operations downstream. Mask is known to be zero
997/// for bits that V cannot have.
998static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000999 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +00001000 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1002 return (KnownZero & Mask) == Mask;
1003}
1004
Chris Lattner0157e7f2006-02-11 09:31:47 +00001005/// ShrinkDemandedConstant - Check to see if the specified operand of the
1006/// specified instruction is a constant integer. If so, check to see if there
1007/// are any bits set in the constant that are not demanded. If so, shrink the
1008/// constant and return true.
1009static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1010 uint64_t Demanded) {
1011 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1012 if (!OpC) return false;
1013
1014 // If there are no bits set that aren't demanded, nothing to do.
1015 if ((~Demanded & OpC->getZExtValue()) == 0)
1016 return false;
1017
1018 // This is producing any bits that are not needed, shrink the RHS.
1019 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +00001020 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001021 return true;
1022}
1023
Reid Spencerd9281782007-03-12 17:15:10 +00001024/// ShrinkDemandedConstant - Check to see if the specified operand of the
1025/// specified instruction is a constant integer. If so, check to see if there
1026/// are any bits set in the constant that are not demanded. If so, shrink the
1027/// constant and return true.
1028static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1029 APInt Demanded) {
1030 assert(I && "No instruction?");
1031 assert(OpNo < I->getNumOperands() && "Operand index too large");
1032
1033 // If the operand is not a constant integer, nothing to do.
1034 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1035 if (!OpC) return false;
1036
1037 // If there are no bits set that aren't demanded, nothing to do.
1038 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1039 if ((~Demanded & OpC->getValue()) == 0)
1040 return false;
1041
1042 // This instruction is producing bits that are not demanded. Shrink the RHS.
1043 Demanded &= OpC->getValue();
1044 I->setOperand(OpNo, ConstantInt::get(Demanded));
1045 return true;
1046}
1047
Chris Lattneree0f2802006-02-12 02:07:56 +00001048// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1049// set of known zero and one bits, compute the maximum and minimum values that
1050// could have the specified known zero and known one bits, returning them in
1051// min/max.
1052static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001053 const APInt& KnownZero,
1054 const APInt& KnownOne,
1055 APInt& Min, APInt& Max) {
1056 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1057 assert(KnownZero.getBitWidth() == BitWidth &&
1058 KnownOne.getBitWidth() == BitWidth &&
1059 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1060 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1061 APInt TypeBits(APInt::getAllOnesValue(BitWidth));
1062 APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
Chris Lattneree0f2802006-02-12 02:07:56 +00001063
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001064 APInt SignBit(APInt::getSignBit(BitWidth));
Chris Lattneree0f2802006-02-12 02:07:56 +00001065
1066 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1067 // bit if it is unknown.
1068 Min = KnownOne;
1069 Max = KnownOne|UnknownBits;
1070
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001071 if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
Chris Lattneree0f2802006-02-12 02:07:56 +00001072 Min |= SignBit;
1073 Max &= ~SignBit;
1074 }
Chris Lattneree0f2802006-02-12 02:07:56 +00001075}
1076
1077// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1078// a set of known zero and one bits, compute the maximum and minimum values that
1079// could have the specified known zero and known one bits, returning them in
1080// min/max.
1081static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00001082 const APInt& KnownZero,
1083 const APInt& KnownOne,
1084 APInt& Min,
1085 APInt& Max) {
1086 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1087 assert(KnownZero.getBitWidth() == BitWidth &&
1088 KnownOne.getBitWidth() == BitWidth &&
1089 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1090 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1091 APInt TypeBits(APInt::getAllOnesValue(BitWidth));
1092 APInt UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
Chris Lattneree0f2802006-02-12 02:07:56 +00001093
1094 // The minimum value is when the unknown bits are all zeros.
1095 Min = KnownOne;
1096 // The maximum value is when the unknown bits are all ones.
1097 Max = KnownOne|UnknownBits;
1098}
Chris Lattner0157e7f2006-02-11 09:31:47 +00001099
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100/// SimplifyDemandedBits - Look at V. At this point, we know that only the
1101/// DemandedMask bits of the result of V are ever used downstream. If we can
1102/// use this information to simplify V, do so and return true. Otherwise,
1103/// analyze the expression and return a mask of KnownOne and KnownZero bits for
1104/// the expression (used to simplify the caller). The KnownZero/One bits may
1105/// only be accurate for those bits in the DemandedMask.
1106bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
1107 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +00001108 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001109 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +00001110 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +00001111 // We know all of the bits for a constant!
1112 KnownOne = CI->getZExtValue() & DemandedMask;
1113 KnownZero = ~KnownOne & DemandedMask;
1114 return false;
1115 }
1116
1117 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001118 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001119 if (Depth != 0) { // Not at the root.
1120 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1121 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +00001122 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001123 }
Chris Lattner2590e512006-02-07 06:56:34 +00001124 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001125 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001126 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001127 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001128 if (V != UndefValue::get(VTy))
1129 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +00001130 return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001131 } else if (Depth == 6) { // Limit search depth.
1132 return false;
1133 }
1134
1135 Instruction *I = dyn_cast<Instruction>(V);
1136 if (!I) return false; // Only analyze instructions.
1137
Chris Lattnerab2f9132007-03-04 23:16:36 +00001138 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +00001139
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001140 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +00001141 switch (I->getOpcode()) {
1142 default: break;
1143 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001144 // If either the LHS or the RHS are Zero, the result is zero.
1145 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1146 KnownZero, KnownOne, Depth+1))
1147 return true;
1148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1149
1150 // If something is known zero on the RHS, the bits aren't demanded on the
1151 // LHS.
1152 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
1153 KnownZero2, KnownOne2, Depth+1))
1154 return true;
1155 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1156
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001157 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001158 // These bits cannot contribute to the result of the 'and'.
1159 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
1160 return UpdateValueUsesWith(I, I->getOperand(0));
1161 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
1162 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001163
1164 // If all of the demanded bits in the inputs are known zeros, return zero.
1165 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001166 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001167
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001169 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001170 return UpdateValueUsesWith(I, I);
1171
1172 // Output known-1 bits are only known if set in both the LHS & RHS.
1173 KnownOne &= KnownOne2;
1174 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1175 KnownZero |= KnownZero2;
1176 break;
1177 case Instruction::Or:
1178 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1179 KnownZero, KnownOne, Depth+1))
1180 return true;
1181 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
1183 KnownZero2, KnownOne2, Depth+1))
1184 return true;
1185 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1186
1187 // If all of the demanded bits are known zero on one side, return the other.
1188 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +00001189 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001190 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +00001191 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +00001192 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +00001193
1194 // If all of the potentially set bits on one side are known to be set on
1195 // the other side, just use the 'other' side.
1196 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
1197 (DemandedMask & (~KnownZero)))
1198 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +00001199 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
1200 (DemandedMask & (~KnownZero2)))
1201 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +00001202
1203 // If the RHS is a constant, see if we can simplify it.
1204 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205 return UpdateValueUsesWith(I, I);
1206
1207 // Output known-0 bits are only known if clear in both the LHS & RHS.
1208 KnownZero &= KnownZero2;
1209 // Output known-1 are known to be set if set in either the LHS | RHS.
1210 KnownOne |= KnownOne2;
1211 break;
1212 case Instruction::Xor: {
1213 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1214 KnownZero, KnownOne, Depth+1))
1215 return true;
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1218 KnownZero2, KnownOne2, Depth+1))
1219 return true;
1220 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1221
1222 // If all of the demanded bits are known zero on one side, return the other.
1223 // These bits cannot contribute to the result of the 'xor'.
1224 if ((DemandedMask & KnownZero) == DemandedMask)
1225 return UpdateValueUsesWith(I, I->getOperand(0));
1226 if ((DemandedMask & KnownZero2) == DemandedMask)
1227 return UpdateValueUsesWith(I, I->getOperand(1));
1228
1229 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1230 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1231 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1232 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1233
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001234 // If all of the demanded bits are known to be zero on one side or the
1235 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +00001236 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +00001237 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
1238 Instruction *Or =
1239 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1240 I->getName());
1241 InsertNewInstBefore(Or, *I);
1242 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +00001243 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001244
Chris Lattner5b2edb12006-02-12 08:02:11 +00001245 // If all of the demanded bits on one side are known, and all of the set
1246 // bits on that side are also known to be set on the other side, turn this
1247 // into an AND, as we know the bits will be cleared.
1248 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1249 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1250 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +00001251 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +00001252 Instruction *And =
1253 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1254 InsertNewInstBefore(And, *I);
1255 return UpdateValueUsesWith(I, And);
1256 }
1257 }
1258
Chris Lattner0157e7f2006-02-11 09:31:47 +00001259 // If the RHS is a constant, see if we can simplify it.
1260 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1261 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1262 return UpdateValueUsesWith(I, I);
1263
1264 KnownZero = KnownZeroOut;
1265 KnownOne = KnownOneOut;
1266 break;
1267 }
1268 case Instruction::Select:
1269 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1270 KnownZero, KnownOne, Depth+1))
1271 return true;
1272 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1273 KnownZero2, KnownOne2, Depth+1))
1274 return true;
1275 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1276 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1277
1278 // If the operands are constants, see if we can simplify them.
1279 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1280 return UpdateValueUsesWith(I, I);
1281 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1282 return UpdateValueUsesWith(I, I);
1283
1284 // Only known if known in both the LHS and RHS.
1285 KnownOne &= KnownOne2;
1286 KnownZero &= KnownZero2;
1287 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001288 case Instruction::Trunc:
1289 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1290 KnownZero, KnownOne, Depth+1))
1291 return true;
1292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1293 break;
1294 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001295 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001296 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001297
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001298 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1299 KnownZero, KnownOne, Depth+1))
1300 return true;
1301 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1302 break;
1303 case Instruction::ZExt: {
1304 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001305 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1306 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001307 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001308
Reid Spencera94d3942007-01-19 21:13:56 +00001309 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001310 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1311 KnownZero, KnownOne, Depth+1))
1312 return true;
1313 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1314 // The top bits are known to be zero.
1315 KnownZero |= NewBits;
1316 break;
1317 }
1318 case Instruction::SExt: {
1319 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001320 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1321 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001322 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001323
1324 // Get the sign bit for the source type
1325 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001326 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001327
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001328 // If any of the sign extended bits are demanded, we know that the sign
1329 // bit is demanded.
1330 if (NewBits & DemandedMask)
1331 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001332
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001333 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1334 KnownZero, KnownOne, Depth+1))
1335 return true;
1336 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001337
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001338 // If the sign bit of the input is known set or clear, then we know the
1339 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001340
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001341 // If the input sign bit is known zero, or if the NewBits are not demanded
1342 // convert this into a zero extension.
1343 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1344 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001345 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001346 return UpdateValueUsesWith(I, NewCast);
1347 } else if (KnownOne & InSignBit) { // Input sign bit known set
1348 KnownOne |= NewBits;
1349 KnownZero &= ~NewBits;
1350 } else { // Input sign bit unknown
1351 KnownZero &= ~NewBits;
1352 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001353 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001354 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001355 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001356 case Instruction::Add:
1357 // If there is a constant on the RHS, there are a variety of xformations
1358 // we can do.
1359 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1360 // If null, this should be simplified elsewhere. Some of the xforms here
1361 // won't work if the RHS is zero.
1362 if (RHS->isNullValue())
1363 break;
1364
1365 // Figure out what the input bits are. If the top bits of the and result
1366 // are not demanded, then the add doesn't demand them from its input
1367 // either.
1368
1369 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001370 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001371 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1372
1373 // If the top bit of the output is demanded, demand everything from the
1374 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001375 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001376
1377 // Find information about known zero/one bits in the input.
1378 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1379 KnownZero2, KnownOne2, Depth+1))
1380 return true;
1381
1382 // If the RHS of the add has bits set that can't affect the input, reduce
1383 // the constant.
1384 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1385 return UpdateValueUsesWith(I, I);
1386
1387 // Avoid excess work.
1388 if (KnownZero2 == 0 && KnownOne2 == 0)
1389 break;
1390
1391 // Turn it into OR if input bits are zero.
1392 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1393 Instruction *Or =
1394 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1395 I->getName());
1396 InsertNewInstBefore(Or, *I);
1397 return UpdateValueUsesWith(I, Or);
1398 }
1399
1400 // We can say something about the output known-zero and known-one bits,
1401 // depending on potential carries from the input constant and the
1402 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1403 // bits set and the RHS constant is 0x01001, then we know we have a known
1404 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1405
1406 // To compute this, we first compute the potential carry bits. These are
1407 // the bits which may be modified. I'm not aware of a better way to do
1408 // this scan.
1409 uint64_t RHSVal = RHS->getZExtValue();
1410
1411 bool CarryIn = false;
1412 uint64_t CarryBits = 0;
1413 uint64_t CurBit = 1;
1414 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1415 // Record the current carry in.
1416 if (CarryIn) CarryBits |= CurBit;
1417
1418 bool CarryOut;
1419
1420 // This bit has a carry out unless it is "zero + zero" or
1421 // "zero + anything" with no carry in.
1422 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1423 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1424 } else if (!CarryIn &&
1425 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1426 CarryOut = false; // 0 + anything has no carry out if no carry in.
1427 } else {
1428 // Otherwise, we have to assume we have a carry out.
1429 CarryOut = true;
1430 }
1431
1432 // This stage's carry out becomes the next stage's carry-in.
1433 CarryIn = CarryOut;
1434 }
1435
1436 // Now that we know which bits have carries, compute the known-1/0 sets.
1437
1438 // Bits are known one if they are known zero in one operand and one in the
1439 // other, and there is no input carry.
1440 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1441
1442 // Bits are known zero if they are known zero in both operands and there
1443 // is no input carry.
1444 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
Chris Lattner5fdded12007-03-05 00:02:29 +00001445 } else {
1446 // If the high-bits of this ADD are not demanded, then it does not demand
1447 // the high bits of its LHS or RHS.
1448 if ((DemandedMask & VTy->getSignBit()) == 0) {
1449 // Right fill the mask of bits for this ADD to demand the most
1450 // significant bit and all those below it.
1451 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1452 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1453 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1454 KnownZero2, KnownOne2, Depth+1))
1455 return true;
1456 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1457 KnownZero2, KnownOne2, Depth+1))
1458 return true;
1459 }
1460 }
1461 break;
1462 case Instruction::Sub:
1463 // If the high-bits of this SUB are not demanded, then it does not demand
1464 // the high bits of its LHS or RHS.
1465 if ((DemandedMask & VTy->getSignBit()) == 0) {
1466 // Right fill the mask of bits for this SUB to demand the most
1467 // significant bit and all those below it.
1468 unsigned NLZ = CountLeadingZeros_64(DemandedMask);
1469 uint64_t DemandedFromOps = ~0ULL >> NLZ;
1470 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1471 KnownZero2, KnownOne2, Depth+1))
1472 return true;
1473 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1474 KnownZero2, KnownOne2, Depth+1))
1475 return true;
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001476 }
1477 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001478 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001479 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1480 uint64_t ShiftAmt = SA->getZExtValue();
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001482 KnownZero, KnownOne, Depth+1))
1483 return true;
1484 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001485 KnownZero <<= ShiftAmt;
1486 KnownOne <<= ShiftAmt;
1487 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001488 }
Chris Lattner2590e512006-02-07 06:56:34 +00001489 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001490 case Instruction::LShr:
1491 // For a logical shift right
1492 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1493 unsigned ShiftAmt = SA->getZExtValue();
1494
1495 // Compute the new bits that are at the top now.
1496 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001497 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1498 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001499 // Unsigned shift right.
1500 if (SimplifyDemandedBits(I->getOperand(0),
1501 (DemandedMask << ShiftAmt) & TypeMask,
1502 KnownZero, KnownOne, Depth+1))
1503 return true;
1504 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1505 KnownZero &= TypeMask;
1506 KnownOne &= TypeMask;
1507 KnownZero >>= ShiftAmt;
1508 KnownOne >>= ShiftAmt;
1509 KnownZero |= HighBits; // high bits known zero.
1510 }
1511 break;
1512 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001513 // If this is an arithmetic shift right and only the low-bit is set, we can
1514 // always convert this into a logical shr, even if the shift amount is
1515 // variable. The low bit of the shift cannot be an input sign bit unless
1516 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001517 if (DemandedMask == 1) {
1518 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001519 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001520 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001521 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001522 return UpdateValueUsesWith(I, NewVal);
1523 }
1524
Reid Spencere0fc4df2006-10-20 07:07:24 +00001525 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1526 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001527
1528 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001529 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001530 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1531 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001532 // Signed shift right.
1533 if (SimplifyDemandedBits(I->getOperand(0),
1534 (DemandedMask << ShiftAmt) & TypeMask,
1535 KnownZero, KnownOne, Depth+1))
1536 return true;
1537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1538 KnownZero &= TypeMask;
1539 KnownOne &= TypeMask;
1540 KnownZero >>= ShiftAmt;
1541 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001542
Reid Spencerfdff9382006-11-08 06:47:33 +00001543 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001544 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001545 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001546
Reid Spencerfdff9382006-11-08 06:47:33 +00001547 // If the input sign bit is known to be zero, or if none of the top bits
1548 // are demanded, turn this into an unsigned shift right.
1549 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1550 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001551 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001552 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001553 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1554 return UpdateValueUsesWith(I, NewVal);
1555 } else if (KnownOne & SignBit) { // New bits are known one.
1556 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001557 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001558 }
Chris Lattner2590e512006-02-07 06:56:34 +00001559 break;
1560 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001561
1562 // If the client is only demanding bits that we know, return the known
1563 // constant.
1564 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001565 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001566 return false;
1567}
1568
Reid Spencer1791f232007-03-12 17:25:59 +00001569/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1570/// value based on the demanded bits. When this function is called, it is known
1571/// that only the bits set in DemandedMask of the result of V are ever used
1572/// downstream. Consequently, depending on the mask and V, it may be possible
1573/// to replace V with a constant or one of its operands. In such cases, this
1574/// function does the replacement and returns true. In all other cases, it
1575/// returns false after analyzing the expression and setting KnownOne and known
1576/// to be one in the expression. KnownZero contains all the bits that are known
1577/// to be zero in the expression. These are provided to potentially allow the
1578/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1579/// the expression. KnownOne and KnownZero always follow the invariant that
1580/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1581/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1582/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1583/// and KnownOne must all be the same.
1584bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1585 APInt& KnownZero, APInt& KnownOne,
1586 unsigned Depth) {
1587 assert(V != 0 && "Null pointer of Value???");
1588 assert(Depth <= 6 && "Limit Search Depth");
1589 uint32_t BitWidth = DemandedMask.getBitWidth();
1590 const IntegerType *VTy = cast<IntegerType>(V->getType());
1591 assert(VTy->getBitWidth() == BitWidth &&
1592 KnownZero.getBitWidth() == BitWidth &&
1593 KnownOne.getBitWidth() == BitWidth &&
1594 "Value *V, DemandedMask, KnownZero and KnownOne \
1595 must have same BitWidth");
1596 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1597 // We know all of the bits for a constant!
1598 KnownOne = CI->getValue() & DemandedMask;
1599 KnownZero = ~KnownOne & DemandedMask;
1600 return false;
1601 }
1602
Zhou Shengb9128442007-03-14 03:21:24 +00001603 KnownZero.clear();
1604 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +00001605 if (!V->hasOneUse()) { // Other users may use these bits.
1606 if (Depth != 0) { // Not at the root.
1607 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1608 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1609 return false;
1610 }
1611 // If this is the root being simplified, allow it to have multiple uses,
1612 // just set the DemandedMask to all bits.
1613 DemandedMask = APInt::getAllOnesValue(BitWidth);
1614 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1615 if (V != UndefValue::get(VTy))
1616 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1617 return false;
1618 } else if (Depth == 6) { // Limit search depth.
1619 return false;
1620 }
1621
1622 Instruction *I = dyn_cast<Instruction>(V);
1623 if (!I) return false; // Only analyze instructions.
1624
1625 DemandedMask &= APInt::getAllOnesValue(BitWidth);
1626
1627 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1628 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1629 switch (I->getOpcode()) {
1630 default: break;
1631 case Instruction::And:
1632 // If either the LHS or the RHS are Zero, the result is zero.
1633 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1634 RHSKnownZero, RHSKnownOne, Depth+1))
1635 return true;
1636 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1637 "Bits known to be one AND zero?");
1638
1639 // If something is known zero on the RHS, the bits aren't demanded on the
1640 // LHS.
1641 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1642 LHSKnownZero, LHSKnownOne, Depth+1))
1643 return true;
1644 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1645 "Bits known to be one AND zero?");
1646
1647 // If all of the demanded bits are known 1 on one side, return the other.
1648 // These bits cannot contribute to the result of the 'and'.
1649 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1650 (DemandedMask & ~LHSKnownZero))
1651 return UpdateValueUsesWith(I, I->getOperand(0));
1652 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1653 (DemandedMask & ~RHSKnownZero))
1654 return UpdateValueUsesWith(I, I->getOperand(1));
1655
1656 // If all of the demanded bits in the inputs are known zeros, return zero.
1657 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1658 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1659
1660 // If the RHS is a constant, see if we can simplify it.
1661 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1662 return UpdateValueUsesWith(I, I);
1663
1664 // Output known-1 bits are only known if set in both the LHS & RHS.
1665 RHSKnownOne &= LHSKnownOne;
1666 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1667 RHSKnownZero |= LHSKnownZero;
1668 break;
1669 case Instruction::Or:
1670 // If either the LHS or the RHS are One, the result is One.
1671 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1672 RHSKnownZero, RHSKnownOne, Depth+1))
1673 return true;
1674 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1675 "Bits known to be one AND zero?");
1676 // If something is known one on the RHS, the bits aren't demanded on the
1677 // LHS.
1678 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1679 LHSKnownZero, LHSKnownOne, Depth+1))
1680 return true;
1681 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1682 "Bits known to be one AND zero?");
1683
1684 // If all of the demanded bits are known zero on one side, return the other.
1685 // These bits cannot contribute to the result of the 'or'.
1686 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1687 (DemandedMask & ~LHSKnownOne))
1688 return UpdateValueUsesWith(I, I->getOperand(0));
1689 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1690 (DemandedMask & ~RHSKnownOne))
1691 return UpdateValueUsesWith(I, I->getOperand(1));
1692
1693 // If all of the potentially set bits on one side are known to be set on
1694 // the other side, just use the 'other' side.
1695 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1696 (DemandedMask & (~RHSKnownZero)))
1697 return UpdateValueUsesWith(I, I->getOperand(0));
1698 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1699 (DemandedMask & (~LHSKnownZero)))
1700 return UpdateValueUsesWith(I, I->getOperand(1));
1701
1702 // If the RHS is a constant, see if we can simplify it.
1703 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1704 return UpdateValueUsesWith(I, I);
1705
1706 // Output known-0 bits are only known if clear in both the LHS & RHS.
1707 RHSKnownZero &= LHSKnownZero;
1708 // Output known-1 are known to be set if set in either the LHS | RHS.
1709 RHSKnownOne |= LHSKnownOne;
1710 break;
1711 case Instruction::Xor: {
1712 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1718 LHSKnownZero, LHSKnownOne, Depth+1))
1719 return true;
1720 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1721 "Bits known to be one AND zero?");
1722
1723 // If all of the demanded bits are known zero on one side, return the other.
1724 // These bits cannot contribute to the result of the 'xor'.
1725 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1726 return UpdateValueUsesWith(I, I->getOperand(0));
1727 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1728 return UpdateValueUsesWith(I, I->getOperand(1));
1729
1730 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1731 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1732 (RHSKnownOne & LHSKnownOne);
1733 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1734 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1735 (RHSKnownOne & LHSKnownZero);
1736
1737 // If all of the demanded bits are known to be zero on one side or the
1738 // other, turn this into an *inclusive* or.
1739 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1740 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1741 Instruction *Or =
1742 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1743 I->getName());
1744 InsertNewInstBefore(Or, *I);
1745 return UpdateValueUsesWith(I, Or);
1746 }
1747
1748 // If all of the demanded bits on one side are known, and all of the set
1749 // bits on that side are also known to be set on the other side, turn this
1750 // into an AND, as we know the bits will be cleared.
1751 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1752 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1753 // all known
1754 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1755 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1756 Instruction *And =
1757 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1758 InsertNewInstBefore(And, *I);
1759 return UpdateValueUsesWith(I, And);
1760 }
1761 }
1762
1763 // If the RHS is a constant, see if we can simplify it.
1764 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1765 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1766 return UpdateValueUsesWith(I, I);
1767
1768 RHSKnownZero = KnownZeroOut;
1769 RHSKnownOne = KnownOneOut;
1770 break;
1771 }
1772 case Instruction::Select:
1773 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1774 RHSKnownZero, RHSKnownOne, Depth+1))
1775 return true;
1776 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1777 LHSKnownZero, LHSKnownOne, Depth+1))
1778 return true;
1779 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1780 "Bits known to be one AND zero?");
1781 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1782 "Bits known to be one AND zero?");
1783
1784 // If the operands are constants, see if we can simplify them.
1785 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1786 return UpdateValueUsesWith(I, I);
1787 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1788 return UpdateValueUsesWith(I, I);
1789
1790 // Only known if known in both the LHS and RHS.
1791 RHSKnownOne &= LHSKnownOne;
1792 RHSKnownZero &= LHSKnownZero;
1793 break;
1794 case Instruction::Trunc: {
1795 uint32_t truncBf =
1796 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1797 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1798 RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1799 return true;
1800 DemandedMask.trunc(BitWidth);
1801 RHSKnownZero.trunc(BitWidth);
1802 RHSKnownOne.trunc(BitWidth);
1803 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1804 "Bits known to be one AND zero?");
1805 break;
1806 }
1807 case Instruction::BitCast:
1808 if (!I->getOperand(0)->getType()->isInteger())
1809 return false;
1810
1811 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1812 RHSKnownZero, RHSKnownOne, Depth+1))
1813 return true;
1814 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1815 "Bits known to be one AND zero?");
1816 break;
1817 case Instruction::ZExt: {
1818 // Compute the bits in the result that are not present in the input.
1819 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1820 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1821
1822 DemandedMask &= SrcTy->getMask().zext(BitWidth);
1823 uint32_t zextBf = SrcTy->getBitWidth();
1824 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1825 RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1826 return true;
1827 DemandedMask.zext(BitWidth);
1828 RHSKnownZero.zext(BitWidth);
1829 RHSKnownOne.zext(BitWidth);
1830 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1831 "Bits known to be one AND zero?");
1832 // The top bits are known to be zero.
1833 RHSKnownZero |= NewBits;
1834 break;
1835 }
1836 case Instruction::SExt: {
1837 // Compute the bits in the result that are not present in the input.
1838 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1839 APInt NewBits(APInt::getAllOnesValue(BitWidth).shl(SrcTy->getBitWidth()));
1840
1841 // Get the sign bit for the source type
1842 APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1843 InSignBit.zext(BitWidth);
1844 APInt InputDemandedBits = DemandedMask &
1845 SrcTy->getMask().zext(BitWidth);
1846
1847 // If any of the sign extended bits are demanded, we know that the sign
1848 // bit is demanded.
1849 if ((NewBits & DemandedMask) != 0)
1850 InputDemandedBits |= InSignBit;
1851
1852 uint32_t sextBf = SrcTy->getBitWidth();
1853 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1854 RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), Depth+1))
1855 return true;
1856 InputDemandedBits.zext(BitWidth);
1857 RHSKnownZero.zext(BitWidth);
1858 RHSKnownOne.zext(BitWidth);
1859 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1860 "Bits known to be one AND zero?");
1861
1862 // If the sign bit of the input is known set or clear, then we know the
1863 // top bits of the result.
1864
1865 // If the input sign bit is known zero, or if the NewBits are not demanded
1866 // convert this into a zero extension.
1867 if ((RHSKnownZero & InSignBit) != 0 || (NewBits & ~DemandedMask) == NewBits)
1868 {
1869 // Convert to ZExt cast
1870 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1871 return UpdateValueUsesWith(I, NewCast);
1872 } else if ((RHSKnownOne & InSignBit) != 0) { // Input sign bit known set
1873 RHSKnownOne |= NewBits;
1874 RHSKnownZero &= ~NewBits;
1875 } else { // Input sign bit unknown
1876 RHSKnownZero &= ~NewBits;
1877 RHSKnownOne &= ~NewBits;
1878 }
1879 break;
1880 }
1881 case Instruction::Add: {
1882 // Figure out what the input bits are. If the top bits of the and result
1883 // are not demanded, then the add doesn't demand them from its input
1884 // either.
1885 unsigned NLZ = DemandedMask.countLeadingZeros();
1886
1887 // If there is a constant on the RHS, there are a variety of xformations
1888 // we can do.
1889 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1890 // If null, this should be simplified elsewhere. Some of the xforms here
1891 // won't work if the RHS is zero.
1892 if (RHS->isZero())
1893 break;
1894
1895 // If the top bit of the output is demanded, demand everything from the
1896 // input. Otherwise, we demand all the input bits except NLZ top bits.
1897 APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1898
1899 // Find information about known zero/one bits in the input.
1900 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1901 LHSKnownZero, LHSKnownOne, Depth+1))
1902 return true;
1903
1904 // If the RHS of the add has bits set that can't affect the input, reduce
1905 // the constant.
1906 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1907 return UpdateValueUsesWith(I, I);
1908
1909 // Avoid excess work.
1910 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1911 break;
1912
1913 // Turn it into OR if input bits are zero.
1914 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1915 Instruction *Or =
1916 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1917 I->getName());
1918 InsertNewInstBefore(Or, *I);
1919 return UpdateValueUsesWith(I, Or);
1920 }
1921
1922 // We can say something about the output known-zero and known-one bits,
1923 // depending on potential carries from the input constant and the
1924 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1925 // bits set and the RHS constant is 0x01001, then we know we have a known
1926 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1927
1928 // To compute this, we first compute the potential carry bits. These are
1929 // the bits which may be modified. I'm not aware of a better way to do
1930 // this scan.
1931 APInt RHSVal(RHS->getValue());
1932
1933 bool CarryIn = false;
1934 APInt CarryBits(BitWidth, 0);
1935 const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1936 *RHSRawVal = RHSVal.getRawData();
1937 for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1938 uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1939 XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1940 uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1941 if (AddVal < RHSRawVal[i])
1942 CarryIn = true;
1943 else
1944 CarryIn = false;
1945 CarryBits.setWordToValue(i, WordCarryBits);
1946 }
1947
1948 // Now that we know which bits have carries, compute the known-1/0 sets.
1949
1950 // Bits are known one if they are known zero in one operand and one in the
1951 // other, and there is no input carry.
1952 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1953 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1954
1955 // Bits are known zero if they are known zero in both operands and there
1956 // is no input carry.
1957 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1958 } else {
1959 // If the high-bits of this ADD are not demanded, then it does not demand
1960 // the high bits of its LHS or RHS.
1961 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1962 // Right fill the mask of bits for this ADD to demand the most
1963 // significant bit and all those below it.
1964 APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(NLZ);
1965 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1966 LHSKnownZero, LHSKnownOne, Depth+1))
1967 return true;
1968 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1969 LHSKnownZero, LHSKnownOne, Depth+1))
1970 return true;
1971 }
1972 }
1973 break;
1974 }
1975 case Instruction::Sub:
1976 // If the high-bits of this SUB are not demanded, then it does not demand
1977 // the high bits of its LHS or RHS.
1978 if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1979 // Right fill the mask of bits for this SUB to demand the most
1980 // significant bit and all those below it.
1981 unsigned NLZ = DemandedMask.countLeadingZeros();
1982 APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1983 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1984 LHSKnownZero, LHSKnownOne, Depth+1))
1985 return true;
1986 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1987 LHSKnownZero, LHSKnownOne, Depth+1))
1988 return true;
1989 }
1990 break;
1991 case Instruction::Shl:
1992 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1993 uint64_t ShiftAmt = SA->getZExtValue();
1994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt),
1995 RHSKnownZero, RHSKnownOne, Depth+1))
1996 return true;
1997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1998 "Bits known to be one AND zero?");
1999 RHSKnownZero <<= ShiftAmt;
2000 RHSKnownOne <<= ShiftAmt;
2001 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00002002 if (ShiftAmt)
2003 RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00002004 }
2005 break;
2006 case Instruction::LShr:
2007 // For a logical shift right
2008 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2009 unsigned ShiftAmt = SA->getZExtValue();
2010
2011 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2012 // Unsigned shift right.
2013 if (SimplifyDemandedBits(I->getOperand(0),
2014 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2015 RHSKnownZero, RHSKnownOne, Depth+1))
2016 return true;
2017 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2018 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00002019 RHSKnownZero &= TypeMask;
2020 RHSKnownOne &= TypeMask;
2021 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2022 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00002023 if (ShiftAmt) {
2024 // Compute the new bits that are at the top now.
2025 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
2026 BitWidth - ShiftAmt));
2027 RHSKnownZero |= HighBits; // high bits known zero.
2028 }
Reid Spencer1791f232007-03-12 17:25:59 +00002029 }
2030 break;
2031 case Instruction::AShr:
2032 // If this is an arithmetic shift right and only the low-bit is set, we can
2033 // always convert this into a logical shr, even if the shift amount is
2034 // variable. The low bit of the shift cannot be an input sign bit unless
2035 // the shift amount is >= the size of the datatype, which is undefined.
2036 if (DemandedMask == 1) {
2037 // Perform the logical shift right.
2038 Value *NewVal = BinaryOperator::createLShr(
2039 I->getOperand(0), I->getOperand(1), I->getName());
2040 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2041 return UpdateValueUsesWith(I, NewVal);
2042 }
2043
2044 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
2045 unsigned ShiftAmt = SA->getZExtValue();
2046
2047 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
2048 // Signed shift right.
2049 if (SimplifyDemandedBits(I->getOperand(0),
2050 (DemandedMask.shl(ShiftAmt)) & TypeMask,
2051 RHSKnownZero, RHSKnownOne, Depth+1))
2052 return true;
2053 assert((RHSKnownZero & RHSKnownOne) == 0 &&
2054 "Bits known to be one AND zero?");
2055 // Compute the new bits that are at the top now.
Zhou Shengd8c645b2007-03-14 09:07:33 +00002056 APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00002057 RHSKnownZero &= TypeMask;
2058 RHSKnownOne &= TypeMask;
2059 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
2060 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
2061
2062 // Handle the sign bits.
2063 APInt SignBit(APInt::getSignBit(BitWidth));
2064 // Adjust to where it is now in the mask.
2065 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
2066
2067 // If the input sign bit is known to be zero, or if none of the top bits
2068 // are demanded, turn this into an unsigned shift right.
2069 if ((RHSKnownZero & SignBit) != 0 ||
2070 (HighBits & ~DemandedMask) == HighBits) {
2071 // Perform the logical shift right.
2072 Value *NewVal = BinaryOperator::createLShr(
2073 I->getOperand(0), SA, I->getName());
2074 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
2075 return UpdateValueUsesWith(I, NewVal);
2076 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
2077 RHSKnownOne |= HighBits;
2078 }
2079 }
2080 break;
2081 }
2082
2083 // If the client is only demanding bits that we know, return the known
2084 // constant.
2085 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
2086 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
2087 return false;
2088}
2089
Chris Lattner2deeaea2006-10-05 06:55:50 +00002090
2091/// SimplifyDemandedVectorElts - The specified value producecs a vector with
2092/// 64 or fewer elements. DemandedElts contains the set of elements that are
2093/// actually used by the caller. This method analyzes which elements of the
2094/// operand are undef and returns that information in UndefElts.
2095///
2096/// If the information about demanded elements can be used to simplify the
2097/// operation, the operation is simplified, then the resultant value is
2098/// returned. This returns null if no change was made.
2099Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
2100 uint64_t &UndefElts,
2101 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002102 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002103 assert(VWidth <= 64 && "Vector too wide to analyze!");
2104 uint64_t EltMask = ~0ULL >> (64-VWidth);
2105 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
2106 "Invalid DemandedElts!");
2107
2108 if (isa<UndefValue>(V)) {
2109 // If the entire vector is undefined, just return this info.
2110 UndefElts = EltMask;
2111 return 0;
2112 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
2113 UndefElts = EltMask;
2114 return UndefValue::get(V->getType());
2115 }
2116
2117 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002118 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
2119 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002120 Constant *Undef = UndefValue::get(EltTy);
2121
2122 std::vector<Constant*> Elts;
2123 for (unsigned i = 0; i != VWidth; ++i)
2124 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
2125 Elts.push_back(Undef);
2126 UndefElts |= (1ULL << i);
2127 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
2128 Elts.push_back(Undef);
2129 UndefElts |= (1ULL << i);
2130 } else { // Otherwise, defined.
2131 Elts.push_back(CP->getOperand(i));
2132 }
2133
2134 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002135 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002136 return NewCP != CP ? NewCP : 0;
2137 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002138 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00002139 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002140 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002141 Constant *Zero = Constant::getNullValue(EltTy);
2142 Constant *Undef = UndefValue::get(EltTy);
2143 std::vector<Constant*> Elts;
2144 for (unsigned i = 0; i != VWidth; ++i)
2145 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
2146 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002147 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00002148 }
2149
2150 if (!V->hasOneUse()) { // Other users may use these bits.
2151 if (Depth != 0) { // Not at the root.
2152 // TODO: Just compute the UndefElts information recursively.
2153 return false;
2154 }
2155 return false;
2156 } else if (Depth == 10) { // Limit search depth.
2157 return false;
2158 }
2159
2160 Instruction *I = dyn_cast<Instruction>(V);
2161 if (!I) return false; // Only analyze instructions.
2162
2163 bool MadeChange = false;
2164 uint64_t UndefElts2;
2165 Value *TmpV;
2166 switch (I->getOpcode()) {
2167 default: break;
2168
2169 case Instruction::InsertElement: {
2170 // If this is a variable index, we don't know which element it overwrites.
2171 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002172 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00002173 if (Idx == 0) {
2174 // Note that we can't propagate undef elt info, because we don't know
2175 // which elt is getting updated.
2176 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2177 UndefElts2, Depth+1);
2178 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2179 break;
2180 }
2181
2182 // If this is inserting an element that isn't demanded, remove this
2183 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002184 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00002185 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
2186 return AddSoonDeadInstToWorklist(*I, 0);
2187
2188 // Otherwise, the element inserted overwrites whatever was there, so the
2189 // input demanded set is simpler than the output set.
2190 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
2191 DemandedElts & ~(1ULL << IdxNo),
2192 UndefElts, Depth+1);
2193 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2194
2195 // The inserted element is defined.
2196 UndefElts |= 1ULL << IdxNo;
2197 break;
2198 }
2199
2200 case Instruction::And:
2201 case Instruction::Or:
2202 case Instruction::Xor:
2203 case Instruction::Add:
2204 case Instruction::Sub:
2205 case Instruction::Mul:
2206 // div/rem demand all inputs, because they don't want divide by zero.
2207 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
2208 UndefElts, Depth+1);
2209 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
2210 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
2211 UndefElts2, Depth+1);
2212 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
2213
2214 // Output elements are undefined if both are undefined. Consider things
2215 // like undef&0. The result is known zero, not undef.
2216 UndefElts &= UndefElts2;
2217 break;
2218
2219 case Instruction::Call: {
2220 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2221 if (!II) break;
2222 switch (II->getIntrinsicID()) {
2223 default: break;
2224
2225 // Binary vector operations that work column-wise. A dest element is a
2226 // function of the corresponding input elements from the two inputs.
2227 case Intrinsic::x86_sse_sub_ss:
2228 case Intrinsic::x86_sse_mul_ss:
2229 case Intrinsic::x86_sse_min_ss:
2230 case Intrinsic::x86_sse_max_ss:
2231 case Intrinsic::x86_sse2_sub_sd:
2232 case Intrinsic::x86_sse2_mul_sd:
2233 case Intrinsic::x86_sse2_min_sd:
2234 case Intrinsic::x86_sse2_max_sd:
2235 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2236 UndefElts, Depth+1);
2237 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2238 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2239 UndefElts2, Depth+1);
2240 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2241
2242 // If only the low elt is demanded and this is a scalarizable intrinsic,
2243 // scalarize it now.
2244 if (DemandedElts == 1) {
2245 switch (II->getIntrinsicID()) {
2246 default: break;
2247 case Intrinsic::x86_sse_sub_ss:
2248 case Intrinsic::x86_sse_mul_ss:
2249 case Intrinsic::x86_sse2_sub_sd:
2250 case Intrinsic::x86_sse2_mul_sd:
2251 // TODO: Lower MIN/MAX/ABS/etc
2252 Value *LHS = II->getOperand(1);
2253 Value *RHS = II->getOperand(2);
2254 // Extract the element as scalars.
2255 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2256 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2257
2258 switch (II->getIntrinsicID()) {
2259 default: assert(0 && "Case stmts out of sync!");
2260 case Intrinsic::x86_sse_sub_ss:
2261 case Intrinsic::x86_sse2_sub_sd:
2262 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2263 II->getName()), *II);
2264 break;
2265 case Intrinsic::x86_sse_mul_ss:
2266 case Intrinsic::x86_sse2_mul_sd:
2267 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2268 II->getName()), *II);
2269 break;
2270 }
2271
2272 Instruction *New =
2273 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
2274 II->getName());
2275 InsertNewInstBefore(New, *II);
2276 AddSoonDeadInstToWorklist(*II, 0);
2277 return New;
2278 }
2279 }
2280
2281 // Output elements are undefined if both are undefined. Consider things
2282 // like undef&0. The result is known zero, not undef.
2283 UndefElts &= UndefElts2;
2284 break;
2285 }
2286 break;
2287 }
2288 }
2289 return MadeChange ? I : 0;
2290}
2291
Reid Spencer266e42b2006-12-23 06:05:41 +00002292/// @returns true if the specified compare instruction is
2293/// true when both operands are equal...
2294/// @brief Determine if the ICmpInst returns true if both operands are equal
2295static bool isTrueWhenEqual(ICmpInst &ICI) {
2296 ICmpInst::Predicate pred = ICI.getPredicate();
2297 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2298 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2299 pred == ICmpInst::ICMP_SLE;
2300}
2301
Chris Lattnerb8b97502003-08-13 19:01:45 +00002302/// AssociativeOpt - Perform an optimization on an associative operator. This
2303/// function is designed to check a chain of associative operators for a
2304/// potential to apply a certain optimization. Since the optimization may be
2305/// applicable if the expression was reassociated, this checks the chain, then
2306/// reassociates the expression as necessary to expose the optimization
2307/// opportunity. This makes use of a special Functor, which must define
2308/// 'shouldApply' and 'apply' methods.
2309///
2310template<typename Functor>
2311Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2312 unsigned Opcode = Root.getOpcode();
2313 Value *LHS = Root.getOperand(0);
2314
2315 // Quick check, see if the immediate LHS matches...
2316 if (F.shouldApply(LHS))
2317 return F.apply(Root);
2318
2319 // Otherwise, if the LHS is not of the same opcode as the root, return.
2320 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002321 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002322 // Should we apply this transform to the RHS?
2323 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2324
2325 // If not to the RHS, check to see if we should apply to the LHS...
2326 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2327 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2328 ShouldApply = true;
2329 }
2330
2331 // If the functor wants to apply the optimization to the RHS of LHSI,
2332 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2333 if (ShouldApply) {
2334 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002335
Chris Lattnerb8b97502003-08-13 19:01:45 +00002336 // Now all of the instructions are in the current basic block, go ahead
2337 // and perform the reassociation.
2338 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2339
2340 // First move the selected RHS to the LHS of the root...
2341 Root.setOperand(0, LHSI->getOperand(1));
2342
2343 // Make what used to be the LHS of the root be the user of the root...
2344 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00002345 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00002346 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2347 return 0;
2348 }
Chris Lattner284d3b02004-04-16 18:08:07 +00002349 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00002350 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00002351 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2352 BasicBlock::iterator ARI = &Root; ++ARI;
2353 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2354 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00002355
2356 // Now propagate the ExtraOperand down the chain of instructions until we
2357 // get to LHSI.
2358 while (TmpLHSI != LHSI) {
2359 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00002360 // Move the instruction to immediately before the chain we are
2361 // constructing to avoid breaking dominance properties.
2362 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2363 BB->getInstList().insert(ARI, NextLHSI);
2364 ARI = NextLHSI;
2365
Chris Lattnerb8b97502003-08-13 19:01:45 +00002366 Value *NextOp = NextLHSI->getOperand(1);
2367 NextLHSI->setOperand(1, ExtraOperand);
2368 TmpLHSI = NextLHSI;
2369 ExtraOperand = NextOp;
2370 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002371
Chris Lattnerb8b97502003-08-13 19:01:45 +00002372 // Now that the instructions are reassociated, have the functor perform
2373 // the transformation...
2374 return F.apply(Root);
2375 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002376
Chris Lattnerb8b97502003-08-13 19:01:45 +00002377 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2378 }
2379 return 0;
2380}
2381
2382
2383// AddRHS - Implements: X + X --> X << 1
2384struct AddRHS {
2385 Value *RHS;
2386 AddRHS(Value *rhs) : RHS(rhs) {}
2387 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2388 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00002389 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00002390 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002391 }
2392};
2393
2394// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2395// iff C1&C2 == 0
2396struct AddMaskingAnd {
2397 Constant *C2;
2398 AddMaskingAnd(Constant *c) : C2(c) {}
2399 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00002400 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002401 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002402 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00002403 }
2404 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002405 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002406 }
2407};
2408
Chris Lattner86102b82005-01-01 16:22:27 +00002409static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00002410 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002411 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002412 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002413 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002414
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002415 return IC->InsertNewInstBefore(CastInst::create(
2416 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00002417 }
2418
Chris Lattner183b3362004-04-09 19:05:30 +00002419 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00002420 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2421 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00002422
Chris Lattner183b3362004-04-09 19:05:30 +00002423 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2424 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00002425 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2426 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00002427 }
2428
2429 Value *Op0 = SO, *Op1 = ConstOperand;
2430 if (!ConstIsRHS)
2431 std::swap(Op0, Op1);
2432 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00002433 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2434 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00002435 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2436 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2437 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002438 else {
Chris Lattner183b3362004-04-09 19:05:30 +00002439 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00002440 abort();
2441 }
Chris Lattner86102b82005-01-01 16:22:27 +00002442 return IC->InsertNewInstBefore(New, I);
2443}
2444
2445// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2446// constant as the other operand, try to fold the binary operator into the
2447// select arguments. This also works for Cast instructions, which obviously do
2448// not have a second operand.
2449static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2450 InstCombiner *IC) {
2451 // Don't modify shared select instructions
2452 if (!SI->hasOneUse()) return 0;
2453 Value *TV = SI->getOperand(1);
2454 Value *FV = SI->getOperand(2);
2455
2456 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00002457 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00002458 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00002459
Chris Lattner86102b82005-01-01 16:22:27 +00002460 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2461 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2462
2463 return new SelectInst(SI->getCondition(), SelectTrueVal,
2464 SelectFalseVal);
2465 }
2466 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00002467}
2468
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002469
2470/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2471/// node as operand #0, see if we can fold the instruction into the PHI (which
2472/// is only possible if all operands to the PHI are constants).
2473Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2474 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00002475 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00002476 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002477
Chris Lattner04689872006-09-09 22:02:56 +00002478 // Check to see if all of the operands of the PHI are constants. If there is
2479 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002480 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00002481 BasicBlock *NonConstBB = 0;
2482 for (unsigned i = 0; i != NumPHIValues; ++i)
2483 if (!isa<Constant>(PN->getIncomingValue(i))) {
2484 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00002485 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00002486 NonConstBB = PN->getIncomingBlock(i);
2487
2488 // If the incoming non-constant value is in I's block, we have an infinite
2489 // loop.
2490 if (NonConstBB == I.getParent())
2491 return 0;
2492 }
2493
2494 // If there is exactly one non-constant value, we can insert a copy of the
2495 // operation in that block. However, if this is a critical edge, we would be
2496 // inserting the computation one some other paths (e.g. inside a loop). Only
2497 // do this if the pred block is unconditionally branching into the phi block.
2498 if (NonConstBB) {
2499 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2500 if (!BI || !BI->isUnconditional()) return 0;
2501 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002502
2503 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002504 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00002505 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002506 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002507 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002508
2509 // Next, add all of the operands to the PHI.
2510 if (I.getNumOperands() == 2) {
2511 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00002512 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002513 Value *InV;
2514 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002515 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2516 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2517 else
2518 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00002519 } else {
2520 assert(PN->getIncomingBlock(i) == NonConstBB);
2521 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2522 InV = BinaryOperator::create(BO->getOpcode(),
2523 PN->getIncomingValue(i), C, "phitmp",
2524 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00002525 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2526 InV = CmpInst::create(CI->getOpcode(),
2527 CI->getPredicate(),
2528 PN->getIncomingValue(i), C, "phitmp",
2529 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00002530 else
2531 assert(0 && "Unknown binop!");
2532
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002533 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002534 }
2535 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002536 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002537 } else {
2538 CastInst *CI = cast<CastInst>(&I);
2539 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00002540 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00002541 Value *InV;
2542 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002543 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00002544 } else {
2545 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002546 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2547 I.getType(), "phitmp",
2548 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00002549 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00002550 }
2551 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002552 }
2553 }
2554 return ReplaceInstUsesWith(I, NewPN);
2555}
2556
Chris Lattner113f4f42002-06-25 16:13:24 +00002557Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002558 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002560
Chris Lattnercf4a9962004-04-10 22:01:55 +00002561 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00002562 // X + undef -> undef
2563 if (isa<UndefValue>(RHS))
2564 return ReplaceInstUsesWith(I, RHS);
2565
Chris Lattnercf4a9962004-04-10 22:01:55 +00002566 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00002567 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00002568 if (RHSC->isNullValue())
2569 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00002570 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2571 if (CFP->isExactlyValue(-0.0))
2572 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00002573 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002574
Chris Lattnercf4a9962004-04-10 22:01:55 +00002575 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002576 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00002577 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00002578 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002579 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002580
2581 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2582 // (X & 254)+1 -> (X&254)|1
2583 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002584 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00002585 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00002586 KnownZero, KnownOne))
2587 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00002588 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002589
2590 if (isa<PHINode>(LHS))
2591 if (Instruction *NV = FoldOpIntoPhi(I))
2592 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002593
Chris Lattner330628a2006-01-06 17:59:59 +00002594 ConstantInt *XorRHS = 0;
2595 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00002596 if (isa<ConstantInt>(RHSC) &&
2597 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00002598 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
2599 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
2600 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
2601
2602 uint64_t C0080Val = 1ULL << 31;
2603 int64_t CFF80Val = -C0080Val;
2604 unsigned Size = 32;
2605 do {
2606 if (TySizeBits > Size) {
2607 bool Found = false;
2608 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2609 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2610 if (RHSSExt == CFF80Val) {
2611 if (XorRHS->getZExtValue() == C0080Val)
2612 Found = true;
2613 } else if (RHSZExt == C0080Val) {
2614 if (XorRHS->getSExtValue() == CFF80Val)
2615 Found = true;
2616 }
2617 if (Found) {
2618 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00002619 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002620 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00002621 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002622 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00002623 Size = 0; // Not a sign ext, but can't be any others either.
2624 goto FoundSExt;
2625 }
2626 }
2627 Size >>= 1;
2628 C0080Val >>= Size;
2629 CFF80Val >>= Size;
2630 } while (Size >= 8);
2631
2632FoundSExt:
2633 const Type *MiddleType = 0;
2634 switch (Size) {
2635 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00002636 case 32: MiddleType = Type::Int32Ty; break;
2637 case 16: MiddleType = Type::Int16Ty; break;
2638 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00002639 }
2640 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002641 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00002642 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002643 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00002644 }
2645 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00002646 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00002647
Chris Lattnerb8b97502003-08-13 19:01:45 +00002648 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00002649 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00002650 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00002651
2652 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2653 if (RHSI->getOpcode() == Instruction::Sub)
2654 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2655 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2656 }
2657 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2658 if (LHSI->getOpcode() == Instruction::Sub)
2659 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2660 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2661 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002662 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00002663
Chris Lattner147e9752002-05-08 22:46:53 +00002664 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00002665 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002666 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002667
2668 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00002669 if (!isa<Constant>(RHS))
2670 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002671 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00002672
Misha Brukmanb1c93172005-04-21 23:48:37 +00002673
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002674 ConstantInt *C2;
2675 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2676 if (X == RHS) // X*C + X --> X * (C+1)
2677 return BinaryOperator::createMul(RHS, AddOne(C2));
2678
2679 // X*C1 + X*C2 --> X * (C1+C2)
2680 ConstantInt *C1;
2681 if (X == dyn_castFoldableMul(RHS, C1))
2682 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00002683 }
2684
2685 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002686 if (dyn_castFoldableMul(RHS, C2) == LHS)
2687 return BinaryOperator::createMul(LHS, AddOne(C2));
2688
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002689 // X + ~X --> -1 since ~X = -X-1
2690 if (dyn_castNotVal(LHS) == RHS ||
2691 dyn_castNotVal(RHS) == LHS)
2692 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2693
Chris Lattner57c8d992003-02-18 19:57:07 +00002694
Chris Lattnerb8b97502003-08-13 19:01:45 +00002695 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002696 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00002697 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2698 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00002699
Chris Lattnerb9cde762003-10-02 15:11:26 +00002700 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002701 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002702 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
2703 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
2704 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00002705 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00002706
Chris Lattnerbff91d92004-10-08 05:07:56 +00002707 // (X & FF00) + xx00 -> (X+xx00) & FF00
2708 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2709 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2710 if (Anded == CRHS) {
2711 // See if all bits from the first bit set in the Add RHS up are included
2712 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002713 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002714
2715 // Form a mask of all bits from the lowest bit added through the top.
2716 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00002717 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002718
2719 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002720 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002721
Chris Lattnerbff91d92004-10-08 05:07:56 +00002722 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2723 // Okay, the xform is safe. Insert the new add pronto.
2724 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2725 LHS->getName()), I);
2726 return BinaryOperator::createAnd(NewAdd, C2);
2727 }
2728 }
2729 }
2730
Chris Lattnerd4252a72004-07-30 07:50:03 +00002731 // Try to fold constant add into select arguments.
2732 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002733 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002734 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002735 }
2736
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002737 // add (cast *A to intptrtype) B ->
2738 // cast (GEP (cast *A to sbyte*) B) ->
2739 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002740 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002741 CastInst *CI = dyn_cast<CastInst>(LHS);
2742 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002743 if (!CI) {
2744 CI = dyn_cast<CastInst>(RHS);
2745 Other = LHS;
2746 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002747 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002748 (CI->getType()->getPrimitiveSizeInBits() ==
2749 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002750 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002751 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002752 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002753 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002754 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002755 }
2756 }
2757
Chris Lattner113f4f42002-06-25 16:13:24 +00002758 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002759}
2760
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002761// isSignBit - Return true if the value represented by the constant only has the
2762// highest order bit set.
2763static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002764 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002765 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002766}
2767
Chris Lattner113f4f42002-06-25 16:13:24 +00002768Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002769 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002770
Chris Lattnere6794492002-08-12 21:17:25 +00002771 if (Op0 == Op1) // sub X, X -> 0
2772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002773
Chris Lattnere6794492002-08-12 21:17:25 +00002774 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002775 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002776 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002777
Chris Lattner81a7a232004-10-16 18:11:37 +00002778 if (isa<UndefValue>(Op0))
2779 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2780 if (isa<UndefValue>(Op1))
2781 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2782
Chris Lattner8f2f5982003-11-05 01:06:05 +00002783 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2784 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002785 if (C->isAllOnesValue())
2786 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002787
Chris Lattner8f2f5982003-11-05 01:06:05 +00002788 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002789 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002790 if (match(Op1, m_Not(m_Value(X))))
2791 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002792 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00002793 // -(X >>u 31) -> (X >>s 31)
2794 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00002795 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002796 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002797 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002798 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002799 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002800 if (CU->getZExtValue() ==
2801 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002802 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002803 return BinaryOperator::create(Instruction::AShr,
2804 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002805 }
2806 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002807 }
2808 else if (SI->getOpcode() == Instruction::AShr) {
2809 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2810 // Check to see if we are shifting out everything but the sign bit.
2811 if (CU->getZExtValue() ==
2812 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002813 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002814 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002815 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002816 }
2817 }
2818 }
Chris Lattner022167f2004-03-13 00:11:49 +00002819 }
Chris Lattner183b3362004-04-09 19:05:30 +00002820
2821 // Try to fold constant sub into select arguments.
2822 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002823 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002824 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002825
2826 if (isa<PHINode>(Op0))
2827 if (Instruction *NV = FoldOpIntoPhi(I))
2828 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002829 }
2830
Chris Lattnera9be4492005-04-07 16:15:25 +00002831 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2832 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002833 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002834 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002835 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002836 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002837 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002838 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2839 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2840 // C1-(X+C2) --> (C1-C2)-X
2841 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2842 Op1I->getOperand(0));
2843 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002844 }
2845
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002846 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002847 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2848 // is not used by anyone else...
2849 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002850 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002851 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002852 // Swap the two operands of the subexpr...
2853 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2854 Op1I->setOperand(0, IIOp1);
2855 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002856
Chris Lattner3082c5a2003-02-18 19:28:33 +00002857 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002858 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002859 }
2860
2861 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2862 //
2863 if (Op1I->getOpcode() == Instruction::And &&
2864 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2865 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2866
Chris Lattner396dbfe2004-06-09 05:08:07 +00002867 Value *NewNot =
2868 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002869 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002870 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002871
Reid Spencer3c514952006-10-16 23:08:08 +00002872 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002873 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002874 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002875 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002876 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002877 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002878 ConstantExpr::getNeg(DivRHS));
2879
Chris Lattner57c8d992003-02-18 19:57:07 +00002880 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002881 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002882 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002883 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002884 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002885 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002886 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002887 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002888 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002889
Chris Lattner7a002fe2006-12-02 00:13:08 +00002890 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002891 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2892 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002893 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2894 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2895 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2896 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002897 } else if (Op0I->getOpcode() == Instruction::Sub) {
2898 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2899 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002900 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002901
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002902 ConstantInt *C1;
2903 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2904 if (X == Op1) { // X*C - X --> X * (C-1)
2905 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2906 return BinaryOperator::createMul(Op1, CP1);
2907 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002908
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002909 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2910 if (X == dyn_castFoldableMul(Op1, C2))
2911 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2912 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002913 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002914}
2915
Reid Spencer266e42b2006-12-23 06:05:41 +00002916/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002917/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002918static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2919 switch (pred) {
2920 case ICmpInst::ICMP_SLT:
2921 // True if LHS s< RHS and RHS == 0
2922 return RHS->isNullValue();
2923 case ICmpInst::ICMP_SLE:
2924 // True if LHS s<= RHS and RHS == -1
2925 return RHS->isAllOnesValue();
2926 case ICmpInst::ICMP_UGE:
2927 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2928 return RHS->getZExtValue() == (1ULL <<
2929 (RHS->getType()->getPrimitiveSizeInBits()-1));
2930 case ICmpInst::ICMP_UGT:
2931 // True if LHS u> RHS and RHS == high-bit-mask - 1
2932 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002933 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002934 default:
2935 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002936 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002937}
2938
Chris Lattner113f4f42002-06-25 16:13:24 +00002939Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002940 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002941 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002942
Chris Lattner81a7a232004-10-16 18:11:37 +00002943 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2945
Chris Lattnere6794492002-08-12 21:17:25 +00002946 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002947 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2948 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002949
2950 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002951 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002952 if (SI->getOpcode() == Instruction::Shl)
2953 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002954 return BinaryOperator::createMul(SI->getOperand(0),
2955 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002956
Chris Lattnercce81be2003-09-11 22:24:54 +00002957 if (CI->isNullValue())
2958 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2959 if (CI->equalsInt(1)) // X * 1 == X
2960 return ReplaceInstUsesWith(I, Op0);
2961 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002962 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002963
Reid Spencere0fc4df2006-10-20 07:07:24 +00002964 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002965 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2966 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002967 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002968 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002969 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002970 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002971 if (Op1F->isNullValue())
2972 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002973
Chris Lattner3082c5a2003-02-18 19:28:33 +00002974 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2975 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2976 if (Op1F->getValue() == 1.0)
2977 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2978 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002979
2980 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2981 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2982 isa<ConstantInt>(Op0I->getOperand(1))) {
2983 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2984 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2985 Op1, "tmp");
2986 InsertNewInstBefore(Add, I);
2987 Value *C1C2 = ConstantExpr::getMul(Op1,
2988 cast<Constant>(Op0I->getOperand(1)));
2989 return BinaryOperator::createAdd(Add, C1C2);
2990
2991 }
Chris Lattner183b3362004-04-09 19:05:30 +00002992
2993 // Try to fold constant mul into select arguments.
2994 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002995 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002996 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002997
2998 if (isa<PHINode>(Op0))
2999 if (Instruction *NV = FoldOpIntoPhi(I))
3000 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00003001 }
3002
Chris Lattner934a64cf2003-03-10 23:23:04 +00003003 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3004 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003005 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00003006
Chris Lattner2635b522004-02-23 05:39:21 +00003007 // If one of the operands of the multiply is a cast from a boolean value, then
3008 // we know the bool is either zero or one, so this is a 'masking' multiply.
3009 // See if we can simplify things based on how the boolean was originally
3010 // formed.
3011 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00003012 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00003013 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003014 BoolCast = CI;
3015 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00003016 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00003017 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00003018 BoolCast = CI;
3019 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003020 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003021 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3022 const Type *SCOpTy = SCIOp0->getType();
3023
Reid Spencer266e42b2006-12-23 06:05:41 +00003024 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00003025 // multiply into a shift/and combination.
3026 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00003027 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00003028 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00003029 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003030 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00003031 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00003032 InsertNewInstBefore(
3033 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00003034 BoolCast->getOperand(0)->getName()+
3035 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00003036
3037 // If the multiply type is not the same as the source type, sign extend
3038 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003039 if (I.getType() != V->getType()) {
3040 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
3041 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
3042 Instruction::CastOps opcode =
3043 (SrcBits == DstBits ? Instruction::BitCast :
3044 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3045 V = InsertCastBefore(opcode, V, I.getType(), I);
3046 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003047
Chris Lattner2635b522004-02-23 05:39:21 +00003048 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003049 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00003050 }
3051 }
3052 }
3053
Chris Lattner113f4f42002-06-25 16:13:24 +00003054 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00003055}
3056
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003057/// This function implements the transforms on div instructions that work
3058/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3059/// used by the visitors to those instructions.
3060/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003061Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00003063
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003064 // undef / X -> 0
3065 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003067
3068 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003069 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003070 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003071
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003072 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003073 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3074 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003075 // same basic block, then we replace the select with Y, and the condition
3076 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00003077 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003078 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00003079 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3080 if (ST->isNullValue()) {
3081 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3082 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003083 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003084 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3085 I.setOperand(1, SI->getOperand(2));
3086 else
3087 UpdateValueUsesWith(SI, SI->getOperand(2));
3088 return &I;
3089 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003090
Chris Lattnerd79dc792006-09-09 20:26:32 +00003091 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
3092 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3093 if (ST->isNullValue()) {
3094 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3095 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003096 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00003097 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3098 I.setOperand(1, SI->getOperand(1));
3099 else
3100 UpdateValueUsesWith(SI, SI->getOperand(1));
3101 return &I;
3102 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003103 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003104
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003105 return 0;
3106}
Misha Brukmanb1c93172005-04-21 23:48:37 +00003107
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003108/// This function implements the transforms common to both integer division
3109/// instructions (udiv and sdiv). It is called by the visitors to those integer
3110/// division instructions.
3111/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003112Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3114
3115 if (Instruction *Common = commonDivTransforms(I))
3116 return Common;
3117
3118 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3119 // div X, 1 == X
3120 if (RHS->equalsInt(1))
3121 return ReplaceInstUsesWith(I, Op0);
3122
3123 // (X / C1) / C2 -> X / (C1*C2)
3124 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3125 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3126 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3127 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3128 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00003129 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003130
3131 if (!RHS->isNullValue()) { // avoid X udiv 0
3132 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3133 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3134 return R;
3135 if (isa<PHINode>(Op0))
3136 if (Instruction *NV = FoldOpIntoPhi(I))
3137 return NV;
3138 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003139 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003140
Chris Lattner3082c5a2003-02-18 19:28:33 +00003141 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003142 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00003143 if (LHS->equalsInt(0))
3144 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3145
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003146 return 0;
3147}
3148
3149Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3150 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3151
3152 // Handle the integer div common cases
3153 if (Instruction *Common = commonIDivTransforms(I))
3154 return Common;
3155
3156 // X udiv C^2 -> X >> C
3157 // Check to see if this is an unsigned division with an exact power of 2,
3158 // if so, convert to a right shift.
3159 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3160 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
3161 if (isPowerOf2_64(Val)) {
3162 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00003163 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00003164 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003165 }
3166 }
3167
3168 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00003169 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003170 if (RHSI->getOpcode() == Instruction::Shl &&
3171 isa<ConstantInt>(RHSI->getOperand(0))) {
3172 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
3173 if (isPowerOf2_64(C1)) {
3174 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003175 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003176 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003177 Constant *C2V = ConstantInt::get(NTy, C2);
3178 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00003179 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00003180 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00003181 }
3182 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00003183 }
3184
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003185 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3186 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00003187 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003188 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00003189 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3190 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
3191 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
3192 // Compute the shift amounts
3193 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
3194 // Construct the "on true" case of the select
3195 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3196 Instruction *TSI = BinaryOperator::createLShr(
3197 Op0, TC, SI->getName()+".t");
3198 TSI = InsertNewInstBefore(TSI, I);
3199
3200 // Construct the "on false" case of the select
3201 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3202 Instruction *FSI = BinaryOperator::createLShr(
3203 Op0, FC, SI->getName()+".f");
3204 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003205
Reid Spencer3939b1a2007-03-05 23:36:13 +00003206 // construct the select instruction and return it.
3207 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003208 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00003209 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003210 return 0;
3211}
3212
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003213Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215
3216 // Handle the integer div common cases
3217 if (Instruction *Common = commonIDivTransforms(I))
3218 return Common;
3219
3220 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3221 // sdiv X, -1 == -X
3222 if (RHS->isAllOnesValue())
3223 return BinaryOperator::createNeg(Op0);
3224
3225 // -X/C -> X/-C
3226 if (Value *LHSNeg = dyn_castNegVal(Op0))
3227 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3228 }
3229
3230 // If the sign bits of both operands are zero (i.e. we can prove they are
3231 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00003232 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00003233 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3234 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3235 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3236 }
3237 }
3238
3239 return 0;
3240}
3241
3242Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3243 return commonDivTransforms(I);
3244}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003245
Chris Lattner85dda9a2006-03-02 06:50:58 +00003246/// GetFactor - If we can prove that the specified value is at least a multiple
3247/// of some factor, return that factor.
3248static Constant *GetFactor(Value *V) {
3249 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3250 return CI;
3251
3252 // Unless we can be tricky, we know this is a multiple of 1.
3253 Constant *Result = ConstantInt::get(V->getType(), 1);
3254
3255 Instruction *I = dyn_cast<Instruction>(V);
3256 if (!I) return Result;
3257
3258 if (I->getOpcode() == Instruction::Mul) {
3259 // Handle multiplies by a constant, etc.
3260 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
3261 GetFactor(I->getOperand(1)));
3262 } else if (I->getOpcode() == Instruction::Shl) {
3263 // (X<<C) -> X * (1 << C)
3264 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
3265 ShRHS = ConstantExpr::getShl(Result, ShRHS);
3266 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
3267 }
3268 } else if (I->getOpcode() == Instruction::And) {
3269 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3270 // X & 0xFFF0 is known to be a multiple of 16.
3271 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
3272 if (Zeros != V->getType()->getPrimitiveSizeInBits())
3273 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00003274 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00003275 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003276 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00003277 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003278 if (!CI->isIntegerCast())
3279 return Result;
3280 Value *Op = CI->getOperand(0);
3281 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00003282 }
3283 return Result;
3284}
3285
Reid Spencer7eb55b32006-11-02 01:53:59 +00003286/// This function implements the transforms on rem instructions that work
3287/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3288/// is used by the visitors to those instructions.
3289/// @brief Transforms common to all three rem instructions
3290Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003291 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00003292
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003293 // 0 % X == 0, we don't need to preserve faults!
3294 if (Constant *LHS = dyn_cast<Constant>(Op0))
3295 if (LHS->isNullValue())
3296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3297
3298 if (isa<UndefValue>(Op0)) // undef % X -> 0
3299 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3300 if (isa<UndefValue>(Op1))
3301 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00003302
3303 // Handle cases involving: rem X, (select Cond, Y, Z)
3304 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3305 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3306 // the same basic block, then we replace the select with Y, and the
3307 // condition of the select with false (if the cond value is in the same
3308 // BB). If the select has uses other than the div, this allows them to be
3309 // simplified also.
3310 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3311 if (ST->isNullValue()) {
3312 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3313 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003314 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003315 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3316 I.setOperand(1, SI->getOperand(2));
3317 else
3318 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00003319 return &I;
3320 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003321 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3322 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3323 if (ST->isNullValue()) {
3324 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3325 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00003326 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00003327 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3328 I.setOperand(1, SI->getOperand(1));
3329 else
3330 UpdateValueUsesWith(SI, SI->getOperand(1));
3331 return &I;
3332 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00003333 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00003334
Reid Spencer7eb55b32006-11-02 01:53:59 +00003335 return 0;
3336}
3337
3338/// This function implements the transforms common to both integer remainder
3339/// instructions (urem and srem). It is called by the visitors to those integer
3340/// remainder instructions.
3341/// @brief Common integer remainder transforms
3342Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3344
3345 if (Instruction *common = commonRemTransforms(I))
3346 return common;
3347
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00003348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00003349 // X % 0 == undef, we don't need to preserve faults!
3350 if (RHS->equalsInt(0))
3351 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3352
Chris Lattner3082c5a2003-02-18 19:28:33 +00003353 if (RHS->equalsInt(1)) // X % 1 == 0
3354 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355
Chris Lattnerb70f1412006-02-28 05:49:21 +00003356 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3357 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3358 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3359 return R;
3360 } else if (isa<PHINode>(Op0I)) {
3361 if (Instruction *NV = FoldOpIntoPhi(I))
3362 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00003363 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003364 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
3365 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00003366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00003367 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003368 }
3369
Reid Spencer7eb55b32006-11-02 01:53:59 +00003370 return 0;
3371}
3372
3373Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3375
3376 if (Instruction *common = commonIRemTransforms(I))
3377 return common;
3378
3379 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3380 // X urem C^2 -> X and C
3381 // Check to see if this is an unsigned remainder with an exact power of 2,
3382 // if so, convert to a bitwise and.
3383 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3384 if (isPowerOf2_64(C->getZExtValue()))
3385 return BinaryOperator::createAnd(Op0, SubOne(C));
3386 }
3387
Chris Lattner2e90b732006-02-05 07:54:04 +00003388 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003389 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3390 if (RHSI->getOpcode() == Instruction::Shl &&
3391 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003392 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00003393 if (isPowerOf2_64(C1)) {
3394 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3395 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3396 "tmp"), I);
3397 return BinaryOperator::createAnd(Op0, Add);
3398 }
3399 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00003400 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00003401
Reid Spencer7eb55b32006-11-02 01:53:59 +00003402 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3403 // where C1&C2 are powers of two.
3404 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3405 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3406 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3407 // STO == 0 and SFO == 0 handled above.
3408 if (isPowerOf2_64(STO->getZExtValue()) &&
3409 isPowerOf2_64(SFO->getZExtValue())) {
3410 Value *TrueAnd = InsertNewInstBefore(
3411 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3412 Value *FalseAnd = InsertNewInstBefore(
3413 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3414 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3415 }
3416 }
Chris Lattner2e90b732006-02-05 07:54:04 +00003417 }
3418
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003419 return 0;
3420}
3421
Reid Spencer7eb55b32006-11-02 01:53:59 +00003422Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3424
3425 if (Instruction *common = commonIRemTransforms(I))
3426 return common;
3427
3428 if (Value *RHSNeg = dyn_castNegVal(Op1))
3429 if (!isa<ConstantInt>(RHSNeg) ||
3430 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
3431 // X % -Y -> X % Y
3432 AddUsesToWorkList(I);
3433 I.setOperand(1, RHSNeg);
3434 return &I;
3435 }
3436
3437 // If the top bits of both operands are zero (i.e. we can prove they are
3438 // unsigned inputs), turn this into a urem.
3439 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
3440 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3441 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3442 return BinaryOperator::createURem(Op0, Op1, I.getName());
3443 }
3444
3445 return 0;
3446}
3447
3448Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00003449 return commonRemTransforms(I);
3450}
3451
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003452// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00003453static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00003454 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00003455 if (isSigned) {
3456 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00003457 APInt Val(APInt::getSignedMaxValue(TypeBits));
3458 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00003459 }
Reid Spenceref599b02007-03-19 21:10:28 +00003460 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003461}
3462
3463// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00003464static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3465 if (isSigned) {
3466 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00003467 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3468 APInt Val(APInt::getSignedMinValue(TypeBits));
3469 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00003470 }
Reid Spencer3b93db72007-03-19 21:08:07 +00003471 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003472}
3473
Chris Lattner35167c32004-06-09 07:59:58 +00003474// isOneBitSet - Return true if there is exactly one bit set in the specified
3475// constant.
3476static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00003477 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00003478}
3479
Chris Lattner8fc5af42004-09-23 21:46:38 +00003480#if 0 // Currently unused
3481// isLowOnes - Return true if the constant is of the form 0+1+.
3482static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003483 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003484
3485 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003486 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003487
3488 uint64_t U = V+1; // If it is low ones, this should be a power of two.
3489 return U && V && (U & V) == 0;
3490}
3491#endif
3492
3493// isHighOnes - Return true if the constant is of the form 1+0+.
3494// This is the same as lowones(~X).
3495static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00003496 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00003497}
3498
Reid Spencer266e42b2006-12-23 06:05:41 +00003499/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00003500/// are carefully arranged to allow folding of expressions such as:
3501///
3502/// (A < B) | (A > B) --> (A != B)
3503///
Reid Spencer266e42b2006-12-23 06:05:41 +00003504/// Note that this is only valid if the first and second predicates have the
3505/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003506///
Reid Spencer266e42b2006-12-23 06:05:41 +00003507/// Three bits are used to represent the condition, as follows:
3508/// 0 A > B
3509/// 1 A == B
3510/// 2 A < B
3511///
3512/// <=> Value Definition
3513/// 000 0 Always false
3514/// 001 1 A > B
3515/// 010 2 A == B
3516/// 011 3 A >= B
3517/// 100 4 A < B
3518/// 101 5 A != B
3519/// 110 6 A <= B
3520/// 111 7 Always true
3521///
3522static unsigned getICmpCode(const ICmpInst *ICI) {
3523 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003524 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00003525 case ICmpInst::ICMP_UGT: return 1; // 001
3526 case ICmpInst::ICMP_SGT: return 1; // 001
3527 case ICmpInst::ICMP_EQ: return 2; // 010
3528 case ICmpInst::ICMP_UGE: return 3; // 011
3529 case ICmpInst::ICMP_SGE: return 3; // 011
3530 case ICmpInst::ICMP_ULT: return 4; // 100
3531 case ICmpInst::ICMP_SLT: return 4; // 100
3532 case ICmpInst::ICMP_NE: return 5; // 101
3533 case ICmpInst::ICMP_ULE: return 6; // 110
3534 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00003535 // True -> 7
3536 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00003537 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00003538 return 0;
3539 }
3540}
3541
Reid Spencer266e42b2006-12-23 06:05:41 +00003542/// getICmpValue - This is the complement of getICmpCode, which turns an
3543/// opcode and two operands into either a constant true or false, or a brand
3544/// new /// ICmp instruction. The sign is passed in to determine which kind
3545/// of predicate to use in new icmp instructions.
3546static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3547 switch (code) {
3548 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00003549 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00003550 case 1:
3551 if (sign)
3552 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3553 else
3554 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3555 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3556 case 3:
3557 if (sign)
3558 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3559 else
3560 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3561 case 4:
3562 if (sign)
3563 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3564 else
3565 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3566 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3567 case 6:
3568 if (sign)
3569 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3570 else
3571 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00003572 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00003573 }
3574}
3575
Reid Spencer266e42b2006-12-23 06:05:41 +00003576static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3577 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3578 (ICmpInst::isSignedPredicate(p1) &&
3579 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3580 (ICmpInst::isSignedPredicate(p2) &&
3581 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3582}
3583
3584namespace {
3585// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3586struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003587 InstCombiner &IC;
3588 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00003589 ICmpInst::Predicate pred;
3590 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3591 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3592 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00003593 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00003594 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3595 if (PredicatesFoldable(pred, ICI->getPredicate()))
3596 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3597 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003598 return false;
3599 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003600 Instruction *apply(Instruction &Log) const {
3601 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3602 if (ICI->getOperand(0) != LHS) {
3603 assert(ICI->getOperand(1) == LHS);
3604 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00003605 }
3606
Chris Lattnerd1bce952007-03-13 14:27:42 +00003607 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00003608 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00003609 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003610 unsigned Code;
3611 switch (Log.getOpcode()) {
3612 case Instruction::And: Code = LHSCode & RHSCode; break;
3613 case Instruction::Or: Code = LHSCode | RHSCode; break;
3614 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00003615 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00003616 }
3617
Chris Lattnerd1bce952007-03-13 14:27:42 +00003618 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3619 ICmpInst::isSignedPredicate(ICI->getPredicate());
3620
3621 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00003622 if (Instruction *I = dyn_cast<Instruction>(RV))
3623 return I;
3624 // Otherwise, it's a constant boolean value...
3625 return IC.ReplaceInstUsesWith(Log, RV);
3626 }
3627};
Chris Lattnere3a63d12006-11-15 04:53:24 +00003628} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00003629
Chris Lattnerba1cb382003-09-19 17:17:26 +00003630// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3631// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00003632// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00003633Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003634 ConstantInt *OpRHS,
3635 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00003636 BinaryOperator &TheAnd) {
3637 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00003638 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00003639 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003640 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003641
Chris Lattnerba1cb382003-09-19 17:17:26 +00003642 switch (Op->getOpcode()) {
3643 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00003644 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003645 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00003646 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003647 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003648 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003649 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003650 }
3651 break;
3652 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00003653 if (Together == AndRHS) // (X | C) & C --> C
3654 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003655
Chris Lattner86102b82005-01-01 16:22:27 +00003656 if (Op->hasOneUse() && Together != OpRHS) {
3657 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00003658 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00003659 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003660 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00003661 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003662 }
3663 break;
3664 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003665 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003666 // Adding a one to a single bit bit-field should be turned into an XOR
3667 // of the bit. First thing to check is to see if this AND is with a
3668 // single bit constant.
Reid Spencer6274c722007-03-23 18:46:34 +00003669 APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
Chris Lattnerba1cb382003-09-19 17:17:26 +00003670
3671 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00003672 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003673 // Ok, at this point, we know that we are masking the result of the
3674 // ADD down to exactly one bit. If the constant we are adding has
3675 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencer6274c722007-03-23 18:46:34 +00003676 APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00003677
Chris Lattnerba1cb382003-09-19 17:17:26 +00003678 // Check to see if any bits below the one bit set in AndRHSV are set.
3679 if ((AddRHS & (AndRHSV-1)) == 0) {
3680 // If not, the only thing that can effect the output of the AND is
3681 // the bit specified by AndRHSV. If that bit is set, the effect of
3682 // the XOR is to toggle the bit. If it is clear, then the ADD has
3683 // no effect.
3684 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3685 TheAnd.setOperand(0, X);
3686 return &TheAnd;
3687 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003688 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00003689 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003690 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003691 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003692 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00003693 }
3694 }
3695 }
3696 }
3697 break;
Chris Lattner2da29172003-09-19 19:05:02 +00003698
3699 case Instruction::Shl: {
3700 // We know that the AND will not produce any of the bits shifted in, so if
3701 // the anded constant includes them, clear them now!
3702 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003703 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00003704 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
3705 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003706
Chris Lattner7e794272004-09-24 15:21:34 +00003707 if (CI == ShlMask) { // Masking out bits that the shift already masks
3708 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3709 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00003710 TheAnd.setOperand(1, CI);
3711 return &TheAnd;
3712 }
3713 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003714 }
Reid Spencerfdff9382006-11-08 06:47:33 +00003715 case Instruction::LShr:
3716 {
Chris Lattner2da29172003-09-19 19:05:02 +00003717 // We know that the AND will not produce any of the bits shifted in, so if
3718 // the anded constant includes them, clear them now! This only applies to
3719 // unsigned shifts, because a signed shr may bring in set bits!
3720 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00003721 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003722 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3723 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00003724
Reid Spencerfdff9382006-11-08 06:47:33 +00003725 if (CI == ShrMask) { // Masking out bits that the shift already masks.
3726 return ReplaceInstUsesWith(TheAnd, Op);
3727 } else if (CI != AndRHS) {
3728 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3729 return &TheAnd;
3730 }
3731 break;
3732 }
3733 case Instruction::AShr:
3734 // Signed shr.
3735 // See if this is shifting in some sign extension, then masking it out
3736 // with an and.
3737 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003738 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00003739 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00003740 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3741 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003742 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003743 // Make the argument unsigned.
3744 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003745 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003746 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003747 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003748 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003749 }
Chris Lattner2da29172003-09-19 19:05:02 +00003750 }
3751 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003752 }
3753 return 0;
3754}
3755
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003756
Chris Lattner6862fbd2004-09-29 17:40:11 +00003757/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3758/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003759/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3760/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003761/// insert new instructions.
3762Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003763 bool isSigned, bool Inside,
3764 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003765 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003766 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003767 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003768
Chris Lattner6862fbd2004-09-29 17:40:11 +00003769 if (Inside) {
3770 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003771 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003772
Reid Spencer266e42b2006-12-23 06:05:41 +00003773 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003774 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003775 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003776 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3777 return new ICmpInst(pred, V, Hi);
3778 }
3779
3780 // Emit V-Lo <u Hi-Lo
3781 Constant *NegLo = ConstantExpr::getNeg(Lo);
3782 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003783 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003784 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3785 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003786 }
3787
3788 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003789 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003790
Reid Spencerf4071162007-03-21 23:19:50 +00003791 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003792 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003793 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003794 ICmpInst::Predicate pred = (isSigned ?
3795 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3796 return new ICmpInst(pred, V, Hi);
3797 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003798
Reid Spencerf4071162007-03-21 23:19:50 +00003799 // Emit V-Lo >u Hi-1-Lo
3800 // Note that Hi has already had one subtracted from it, above.
3801 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003803 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003804 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3805 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003806}
3807
Chris Lattnerb4b25302005-09-18 07:22:02 +00003808// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3809// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3810// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3811// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003812static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003813 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003814 if (!isShiftedMask_64(V)) return false;
3815
3816 // look for the first zero bit after the run of ones
3817 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3818 // look for the first non-zero bit
3819 ME = 64-CountLeadingZeros_64(V);
3820 return true;
3821}
3822
3823
3824
3825/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3826/// where isSub determines whether the operator is a sub. If we can fold one of
3827/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003828///
3829/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3830/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3831/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3832///
3833/// return (A +/- B).
3834///
3835Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003836 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003837 Instruction &I) {
3838 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3839 if (!LHSI || LHSI->getNumOperands() != 2 ||
3840 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3841
3842 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3843
3844 switch (LHSI->getOpcode()) {
3845 default: return 0;
3846 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003847 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3848 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencer6274c722007-03-23 18:46:34 +00003849 if ((Mask->getValue() & Mask->getValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003850 break;
3851
3852 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3853 // part, we don't need any explicit masks to take them out of A. If that
3854 // is all N is, ignore it.
3855 unsigned MB, ME;
3856 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003857 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3858 APInt Mask(APInt::getAllOnesValue(BitWidth));
3859 Mask = APIntOps::lshr(Mask, BitWidth-MB+1);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003860 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003861 break;
3862 }
3863 }
Chris Lattneraf517572005-09-18 04:24:45 +00003864 return 0;
3865 case Instruction::Or:
3866 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003867 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencer6274c722007-03-23 18:46:34 +00003868 if ((Mask->getValue() & Mask->getValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003869 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003870 break;
3871 return 0;
3872 }
3873
3874 Instruction *New;
3875 if (isSub)
3876 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3877 else
3878 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3879 return InsertNewInstBefore(New, I);
3880}
3881
Chris Lattner113f4f42002-06-25 16:13:24 +00003882Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003883 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003885
Chris Lattner81a7a232004-10-16 18:11:37 +00003886 if (isa<UndefValue>(Op1)) // X & undef -> 0
3887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3888
Chris Lattner86102b82005-01-01 16:22:27 +00003889 // and X, X = X
3890 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003891 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003892
Chris Lattner5b2edb12006-02-12 08:02:11 +00003893 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003894 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003895 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003896 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3897 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3898 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003899 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003900 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003901 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003902 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003903 if (CP->isAllOnesValue())
3904 return ReplaceInstUsesWith(I, I.getOperand(0));
3905 }
3906 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003907
Zhou Sheng75b871f2007-01-11 12:24:14 +00003908 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003909 APInt AndRHSMask(AndRHS->getValue());
3910 APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3911 APInt NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003912
Chris Lattnerba1cb382003-09-19 17:17:26 +00003913 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003914 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003915 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003916 Value *Op0LHS = Op0I->getOperand(0);
3917 Value *Op0RHS = Op0I->getOperand(1);
3918 switch (Op0I->getOpcode()) {
3919 case Instruction::Xor:
3920 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003921 // If the mask is only needed on one incoming arm, push it up.
3922 if (Op0I->hasOneUse()) {
3923 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3924 // Not masking anything out for the LHS, move to RHS.
3925 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3926 Op0RHS->getName()+".masked");
3927 InsertNewInstBefore(NewRHS, I);
3928 return BinaryOperator::create(
3929 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003930 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003931 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003932 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3933 // Not masking anything out for the RHS, move to LHS.
3934 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3935 Op0LHS->getName()+".masked");
3936 InsertNewInstBefore(NewLHS, I);
3937 return BinaryOperator::create(
3938 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3939 }
3940 }
3941
Chris Lattner86102b82005-01-01 16:22:27 +00003942 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003943 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003944 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3945 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3946 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3947 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3948 return BinaryOperator::createAnd(V, AndRHS);
3949 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3950 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003951 break;
3952
3953 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003954 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3955 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3956 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3957 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3958 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003959 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003960 }
3961
Chris Lattner16464b32003-07-23 19:25:52 +00003962 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003963 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003964 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003965 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003966 // If this is an integer truncation or change from signed-to-unsigned, and
3967 // if the source is an and/or with immediate, transform it. This
3968 // frequently occurs for bitfield accesses.
3969 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003970 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003971 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003972 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003973 if (CastOp->getOpcode() == Instruction::And) {
3974 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003975 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3976 // This will fold the two constants together, which may allow
3977 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003978 Instruction *NewCast = CastInst::createTruncOrBitCast(
3979 CastOp->getOperand(0), I.getType(),
3980 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003981 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003982 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003983 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003984 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003985 return BinaryOperator::createAnd(NewCast, C3);
3986 } else if (CastOp->getOpcode() == Instruction::Or) {
3987 // Change: and (cast (or X, C1) to T), C2
3988 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003989 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003990 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3991 return ReplaceInstUsesWith(I, AndRHS);
3992 }
3993 }
Chris Lattner33217db2003-07-23 19:36:21 +00003994 }
Chris Lattner183b3362004-04-09 19:05:30 +00003995
3996 // Try to fold constant and into select arguments.
3997 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003998 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003999 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004000 if (isa<PHINode>(Op0))
4001 if (Instruction *NV = FoldOpIntoPhi(I))
4002 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00004003 }
4004
Chris Lattnerbb74e222003-03-10 23:06:50 +00004005 Value *Op0NotVal = dyn_castNotVal(Op0);
4006 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004007
Chris Lattner023a4832004-06-18 06:07:51 +00004008 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4010
Misha Brukman9c003d82004-07-30 12:50:08 +00004011 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00004012 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004013 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
4014 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00004015 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00004016 return BinaryOperator::createNot(Or);
4017 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004018
4019 {
4020 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00004021 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
4022 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4023 return ReplaceInstUsesWith(I, Op1);
4024 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
4025 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4026 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004027
4028 if (Op0->hasOneUse() &&
4029 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4030 if (A == Op1) { // (A^B)&A -> A&(A^B)
4031 I.swapOperands(); // Simplify below
4032 std::swap(Op0, Op1);
4033 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4034 cast<BinaryOperator>(Op0)->swapOperands();
4035 I.swapOperands(); // Simplify below
4036 std::swap(Op0, Op1);
4037 }
4038 }
4039 if (Op1->hasOneUse() &&
4040 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4041 if (B == Op0) { // B&(A^B) -> B&(B^A)
4042 cast<BinaryOperator>(Op1)->swapOperands();
4043 std::swap(A, B);
4044 }
4045 if (A == Op0) { // A&(A^B) -> A & ~B
4046 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
4047 InsertNewInstBefore(NotB, I);
4048 return BinaryOperator::createAnd(A, NotB);
4049 }
4050 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00004051 }
4052
Reid Spencer266e42b2006-12-23 06:05:41 +00004053 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4054 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4055 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004056 return R;
4057
Chris Lattner623826c2004-09-28 21:48:02 +00004058 Value *LHSVal, *RHSVal;
4059 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004060 ICmpInst::Predicate LHSCC, RHSCC;
4061 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4062 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4063 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4064 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4065 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4066 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4067 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4068 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00004069 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004070 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4071 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4072 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4073 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004074 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00004075 std::swap(LHS, RHS);
4076 std::swap(LHSCst, RHSCst);
4077 std::swap(LHSCC, RHSCC);
4078 }
4079
Reid Spencer266e42b2006-12-23 06:05:41 +00004080 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00004081 // comparing a value against two constants and and'ing the result
4082 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004083 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4084 // (from the FoldICmpLogical check above), that the two constants
4085 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00004086 assert(LHSCst != RHSCst && "Compares not folded above?");
4087
4088 switch (LHSCC) {
4089 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004090 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00004091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004093 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4094 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4095 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004096 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004097 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4098 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4099 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00004100 return ReplaceInstUsesWith(I, LHS);
4101 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004102 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00004103 switch (RHSCC) {
4104 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004105 case ICmpInst::ICMP_ULT:
4106 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4107 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4108 break; // (X != 13 & X u< 15) -> no change
4109 case ICmpInst::ICMP_SLT:
4110 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4111 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4112 break; // (X != 13 & X s< 15) -> no change
4113 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4114 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4115 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00004116 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004117 case ICmpInst::ICMP_NE:
4118 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00004119 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4120 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4121 LHSVal->getName()+".off");
4122 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00004123 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4124 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00004125 }
4126 break; // (X != 13 & X != 15) -> no change
4127 }
4128 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004129 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00004130 switch (RHSCC) {
4131 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004132 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4133 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004135 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4136 break;
4137 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4138 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00004139 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4141 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004142 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004143 break;
4144 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00004145 switch (RHSCC) {
4146 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004147 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4148 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00004149 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004150 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4151 break;
4152 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4153 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00004154 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004155 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4156 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004157 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004158 break;
4159 case ICmpInst::ICMP_UGT:
4160 switch (RHSCC) {
4161 default: assert(0 && "Unknown integer condition code!");
4162 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4163 return ReplaceInstUsesWith(I, LHS);
4164 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4165 return ReplaceInstUsesWith(I, RHS);
4166 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4167 break;
4168 case ICmpInst::ICMP_NE:
4169 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4170 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4171 break; // (X u> 13 & X != 15) -> no change
4172 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4173 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4174 true, I);
4175 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4176 break;
4177 }
4178 break;
4179 case ICmpInst::ICMP_SGT:
4180 switch (RHSCC) {
4181 default: assert(0 && "Unknown integer condition code!");
4182 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
4183 return ReplaceInstUsesWith(I, LHS);
4184 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4185 return ReplaceInstUsesWith(I, RHS);
4186 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4187 break;
4188 case ICmpInst::ICMP_NE:
4189 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4190 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4191 break; // (X s> 13 & X != 15) -> no change
4192 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4193 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4194 true, I);
4195 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4196 break;
4197 }
4198 break;
Chris Lattner623826c2004-09-28 21:48:02 +00004199 }
4200 }
4201 }
4202
Chris Lattner3af10532006-05-05 06:39:07 +00004203 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004204 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004209 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4211 I.getType(), TD) &&
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4213 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004214 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4215 Op1C->getOperand(0),
4216 I.getName());
4217 InsertNewInstBefore(NewOp, I);
4218 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4219 }
Chris Lattner3af10532006-05-05 06:39:07 +00004220 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004221
4222 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004223 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004226 SI0->getOperand(1) == SI1->getOperand(1) &&
4227 (SI0->hasOneUse() || SI1->hasOneUse())) {
4228 Instruction *NewOp =
4229 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4230 SI1->getOperand(0),
4231 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004232 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4233 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004234 }
Chris Lattner3af10532006-05-05 06:39:07 +00004235 }
4236
Chris Lattner113f4f42002-06-25 16:13:24 +00004237 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004238}
4239
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004240/// CollectBSwapParts - Look to see if the specified value defines a single byte
4241/// in the result. If it does, and if the specified byte hasn't been filled in
4242/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004243static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004244 Instruction *I = dyn_cast<Instruction>(V);
4245 if (I == 0) return true;
4246
4247 // If this is an or instruction, it is an inner node of the bswap.
4248 if (I->getOpcode() == Instruction::Or)
4249 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4250 CollectBSwapParts(I->getOperand(1), ByteValues);
4251
4252 // If this is a shift by a constant int, and it is "24", then its operand
4253 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00004254 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004255 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00004256 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004257 8*(ByteValues.size()-1))
4258 return true;
4259
4260 unsigned DestNo;
4261 if (I->getOpcode() == Instruction::Shl) {
4262 // X << 24 defines the top byte with the lowest of the input bytes.
4263 DestNo = ByteValues.size()-1;
4264 } else {
4265 // X >>u 24 defines the low byte with the highest of the input bytes.
4266 DestNo = 0;
4267 }
4268
4269 // If the destination byte value is already defined, the values are or'd
4270 // together, which isn't a bswap (unless it's an or of the same bits).
4271 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4272 return true;
4273 ByteValues[DestNo] = I->getOperand(0);
4274 return false;
4275 }
4276
4277 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4278 // don't have this.
4279 Value *Shift = 0, *ShiftLHS = 0;
4280 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4281 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4282 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4283 return true;
4284 Instruction *SI = cast<Instruction>(Shift);
4285
4286 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004287 if (ShiftAmt->getZExtValue() & 7 ||
4288 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004289 return true;
4290
4291 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4292 unsigned DestByte;
4293 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004294 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004295 break;
4296 // Unknown mask for bswap.
4297 if (DestByte == ByteValues.size()) return true;
4298
Reid Spencere0fc4df2006-10-20 07:07:24 +00004299 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004300 unsigned SrcByte;
4301 if (SI->getOpcode() == Instruction::Shl)
4302 SrcByte = DestByte - ShiftBytes;
4303 else
4304 SrcByte = DestByte + ShiftBytes;
4305
4306 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4307 if (SrcByte != ByteValues.size()-DestByte-1)
4308 return true;
4309
4310 // If the destination byte value is already defined, the values are or'd
4311 // together, which isn't a bswap (unless it's an or of the same bits).
4312 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4313 return true;
4314 ByteValues[DestByte] = SI->getOperand(0);
4315 return false;
4316}
4317
4318/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4319/// If so, insert the new bswap intrinsic and return it.
4320Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00004321 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00004322 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004323 return 0;
4324
4325 /// ByteValues - For each byte of the result, we keep track of which value
4326 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00004327 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00004328 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004329
4330 // Try to find all the pieces corresponding to the bswap.
4331 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4332 CollectBSwapParts(I.getOperand(1), ByteValues))
4333 return 0;
4334
4335 // Check to see if all of the bytes come from the same value.
4336 Value *V = ByteValues[0];
4337 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4338
4339 // Check to make sure that all of the bytes come from the same value.
4340 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4341 if (ByteValues[i] != V)
4342 return 0;
4343
4344 // If they do then *success* we can turn this into a bswap. Figure out what
4345 // bswap to make it into.
4346 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00004347 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00004348 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004349 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00004350 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004351 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00004352 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004353 FnName = "llvm.bswap.i64";
4354 else
4355 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00004356 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004357 return new CallInst(F, V);
4358}
4359
4360
Chris Lattner113f4f42002-06-25 16:13:24 +00004361Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004362 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004364
Chris Lattner81a7a232004-10-16 18:11:37 +00004365 if (isa<UndefValue>(Op1))
4366 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004367 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00004368
Chris Lattner5b2edb12006-02-12 08:02:11 +00004369 // or X, X = X
4370 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00004371 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004372
Chris Lattner5b2edb12006-02-12 08:02:11 +00004373 // See if we can simplify any instructions used by the instruction whose sole
4374 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004375 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4376 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Reid Spencerd84d35b2007-02-15 02:26:10 +00004377 if (!isa<VectorType>(I.getType()) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004378 SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner5b2edb12006-02-12 08:02:11 +00004379 KnownZero, KnownOne))
4380 return &I;
4381
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004382 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00004383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004384 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00004385 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4386 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004387 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004388 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004389 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004390 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
4391 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00004392
Chris Lattnerd4252a72004-07-30 07:50:03 +00004393 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4394 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004395 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004396 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004397 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004398 return BinaryOperator::createXor(Or,
4399 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00004400 }
Chris Lattner183b3362004-04-09 19:05:30 +00004401
4402 // Try to fold constant and into select arguments.
4403 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004404 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004405 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004406 if (isa<PHINode>(Op0))
4407 if (Instruction *NV = FoldOpIntoPhi(I))
4408 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00004409 }
4410
Chris Lattner330628a2006-01-06 17:59:59 +00004411 Value *A = 0, *B = 0;
4412 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00004413
4414 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4415 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4416 return ReplaceInstUsesWith(I, Op1);
4417 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4418 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4419 return ReplaceInstUsesWith(I, Op0);
4420
Chris Lattnerb7845d62006-07-10 20:25:24 +00004421 // (A | B) | C and A | (B | C) -> bswap if possible.
4422 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004423 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00004424 match(Op1, m_Or(m_Value(), m_Value())) ||
4425 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4426 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00004427 if (Instruction *BSwap = MatchBSwap(I))
4428 return BSwap;
4429 }
4430
Chris Lattnerb62f5082005-05-09 04:58:36 +00004431 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4432 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004433 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004434 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4435 InsertNewInstBefore(NOr, I);
4436 NOr->takeName(Op0);
4437 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004438 }
4439
4440 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4441 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00004442 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004443 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4444 InsertNewInstBefore(NOr, I);
4445 NOr->takeName(Op0);
4446 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00004447 }
4448
Chris Lattner15212982005-09-18 03:42:07 +00004449 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00004450 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00004451 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
4452
4453 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
4454 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
4455
4456
Chris Lattner01f56c62005-09-18 06:02:59 +00004457 // If we have: ((V + N) & C1) | (V & C2)
4458 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4459 // replace with V+N.
4460 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00004461 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00004462 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00004463 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4464 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004465 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004466 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00004467 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004468 return ReplaceInstUsesWith(I, A);
4469 }
4470 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004471 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00004472 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4473 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004474 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004475 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00004476 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00004477 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00004478 }
4479 }
4480 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004481
4482 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004483 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4484 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4485 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004486 SI0->getOperand(1) == SI1->getOperand(1) &&
4487 (SI0->hasOneUse() || SI1->hasOneUse())) {
4488 Instruction *NewOp =
4489 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4490 SI1->getOperand(0),
4491 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004492 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4493 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004494 }
4495 }
Chris Lattner812aab72003-08-12 19:11:07 +00004496
Chris Lattnerd4252a72004-07-30 07:50:03 +00004497 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4498 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00004499 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004500 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00004501 } else {
4502 A = 0;
4503 }
Chris Lattner4294cec2005-05-07 23:49:08 +00004504 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00004505 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4506 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00004507 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004508 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00004509
Misha Brukman9c003d82004-07-30 12:50:08 +00004510 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00004511 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4512 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4513 I.getName()+".demorgan"), I);
4514 return BinaryOperator::createNot(And);
4515 }
Chris Lattner3e327a42003-03-10 23:13:59 +00004516 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00004517
Reid Spencer266e42b2006-12-23 06:05:41 +00004518 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4519 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4520 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004521 return R;
4522
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004523 Value *LHSVal, *RHSVal;
4524 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 ICmpInst::Predicate LHSCC, RHSCC;
4526 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4527 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4528 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4529 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4530 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4531 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4532 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4533 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004534 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00004535 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
4536 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
4537 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4538 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00004539 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004540 std::swap(LHS, RHS);
4541 std::swap(LHSCst, RHSCst);
4542 std::swap(LHSCC, RHSCC);
4543 }
4544
Reid Spencer266e42b2006-12-23 06:05:41 +00004545 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004546 // comparing a value against two constants and or'ing the result
4547 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00004548 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4549 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004550 // equal.
4551 assert(LHSCst != RHSCst && "Compares not folded above?");
4552
4553 switch (LHSCC) {
4554 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004555 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004556 switch (RHSCC) {
4557 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004559 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4560 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4561 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4562 LHSVal->getName()+".off");
4563 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004564 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004566 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004567 break; // (X == 13 | X == 15) -> no change
4568 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4569 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00004570 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004571 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4572 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4573 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004574 return ReplaceInstUsesWith(I, RHS);
4575 }
4576 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004578 switch (RHSCC) {
4579 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4581 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4582 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004583 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004584 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4585 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4586 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004587 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004588 }
4589 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004590 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004591 switch (RHSCC) {
4592 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004593 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004594 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004595 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4596 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4597 false, I);
4598 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4599 break;
4600 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4601 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004602 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00004603 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4604 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004605 }
4606 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00004607 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004608 switch (RHSCC) {
4609 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00004610 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4611 break;
4612 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4613 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4614 false, I);
4615 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4616 break;
4617 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4618 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4619 return ReplaceInstUsesWith(I, RHS);
4620 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4621 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004622 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004623 break;
4624 case ICmpInst::ICMP_UGT:
4625 switch (RHSCC) {
4626 default: assert(0 && "Unknown integer condition code!");
4627 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4628 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4629 return ReplaceInstUsesWith(I, LHS);
4630 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4631 break;
4632 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4633 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004634 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004635 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4636 break;
4637 }
4638 break;
4639 case ICmpInst::ICMP_SGT:
4640 switch (RHSCC) {
4641 default: assert(0 && "Unknown integer condition code!");
4642 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4643 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4644 return ReplaceInstUsesWith(I, LHS);
4645 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4646 break;
4647 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4648 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00004649 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004650 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4651 break;
4652 }
4653 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00004654 }
4655 }
4656 }
Chris Lattner3af10532006-05-05 06:39:07 +00004657
4658 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004659 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004660 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004661 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4662 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004663 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004664 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004665 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4666 I.getType(), TD) &&
4667 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4668 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004669 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4670 Op1C->getOperand(0),
4671 I.getName());
4672 InsertNewInstBefore(NewOp, I);
4673 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4674 }
Chris Lattner3af10532006-05-05 06:39:07 +00004675 }
Chris Lattner3af10532006-05-05 06:39:07 +00004676
Chris Lattner15212982005-09-18 03:42:07 +00004677
Chris Lattner113f4f42002-06-25 16:13:24 +00004678 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004679}
4680
Chris Lattnerc2076352004-02-16 01:20:27 +00004681// XorSelf - Implements: X ^ X --> 0
4682struct XorSelf {
4683 Value *RHS;
4684 XorSelf(Value *rhs) : RHS(rhs) {}
4685 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4686 Instruction *apply(BinaryOperator &Xor) const {
4687 return &Xor;
4688 }
4689};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004690
4691
Chris Lattner113f4f42002-06-25 16:13:24 +00004692Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004693 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004695
Chris Lattner81a7a232004-10-16 18:11:37 +00004696 if (isa<UndefValue>(Op1))
4697 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4698
Chris Lattnerc2076352004-02-16 01:20:27 +00004699 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4700 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4701 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00004702 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00004703 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00004704
4705 // See if we can simplify any instructions used by the instruction whose sole
4706 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00004707 if (!isa<VectorType>(I.getType())) {
4708 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4709 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4710 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4711 KnownZero, KnownOne))
4712 return &I;
4713 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004714
Zhou Sheng75b871f2007-01-11 12:24:14 +00004715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004716 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4717 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004718 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004719 return new ICmpInst(ICI->getInversePredicate(),
4720 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00004721
Reid Spencer266e42b2006-12-23 06:05:41 +00004722 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00004723 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004724 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4725 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004726 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4727 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004728 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004729 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004730 }
Chris Lattner023a4832004-06-18 06:07:51 +00004731
4732 // ~(~X & Y) --> (X | ~Y)
4733 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4734 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4735 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4736 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004737 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004738 Op0I->getOperand(1)->getName()+".not");
4739 InsertNewInstBefore(NotY, I);
4740 return BinaryOperator::createOr(Op0NotVal, NotY);
4741 }
4742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004743
Chris Lattner97638592003-07-23 21:37:07 +00004744 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004745 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004746 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004747 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004748 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4749 return BinaryOperator::createSub(
4750 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004751 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004752 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004753 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004754 } else if (Op0I->getOpcode() == Instruction::Or) {
4755 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004756 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004757 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4758 // Anything in both C1 and C2 is known to be zero, remove it from
4759 // NewRHS.
4760 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4761 NewRHS = ConstantExpr::getAnd(NewRHS,
4762 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004763 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004764 I.setOperand(0, Op0I->getOperand(0));
4765 I.setOperand(1, NewRHS);
4766 return &I;
4767 }
Chris Lattner97638592003-07-23 21:37:07 +00004768 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004769 }
Chris Lattner183b3362004-04-09 19:05:30 +00004770
4771 // Try to fold constant and into select arguments.
4772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004773 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004774 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004775 if (isa<PHINode>(Op0))
4776 if (Instruction *NV = FoldOpIntoPhi(I))
4777 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004778 }
4779
Chris Lattnerbb74e222003-03-10 23:06:50 +00004780 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004781 if (X == Op1)
4782 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004783 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004784
Chris Lattnerbb74e222003-03-10 23:06:50 +00004785 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004786 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004787 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004788
Chris Lattner07418422007-03-18 22:51:34 +00004789
4790 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4791 if (Op1I) {
4792 Value *A, *B;
4793 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4794 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004795 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004796 I.swapOperands();
4797 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004798 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004799 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004800 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004801 }
Chris Lattner07418422007-03-18 22:51:34 +00004802 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4803 if (Op0 == A) // A^(A^B) == B
4804 return ReplaceInstUsesWith(I, B);
4805 else if (Op0 == B) // A^(B^A) == B
4806 return ReplaceInstUsesWith(I, A);
4807 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4808 if (A == Op0) // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004809 Op1I->swapOperands();
Chris Lattner07418422007-03-18 22:51:34 +00004810 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004811 I.swapOperands(); // Simplified below.
4812 std::swap(Op0, Op1);
4813 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004814 }
Chris Lattner07418422007-03-18 22:51:34 +00004815 }
4816
4817 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4818 if (Op0I) {
4819 Value *A, *B;
4820 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4821 if (A == Op1) // (B|A)^B == (A|B)^B
4822 std::swap(A, B);
4823 if (B == Op1) { // (A|B)^B == A & ~B
4824 Instruction *NotB =
4825 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4826 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004827 }
Chris Lattner07418422007-03-18 22:51:34 +00004828 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4829 if (Op1 == A) // (A^B)^A == B
4830 return ReplaceInstUsesWith(I, B);
4831 else if (Op1 == B) // (B^A)^A == B
4832 return ReplaceInstUsesWith(I, A);
4833 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4834 if (A == Op1) // (A&B)^A -> (B&A)^A
4835 std::swap(A, B);
4836 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004837 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004838 Instruction *N =
4839 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004840 return BinaryOperator::createAnd(N, Op1);
4841 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004842 }
Chris Lattner07418422007-03-18 22:51:34 +00004843 }
4844
4845 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4846 if (Op0I && Op1I && Op0I->isShift() &&
4847 Op0I->getOpcode() == Op1I->getOpcode() &&
4848 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4849 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4850 Instruction *NewOp =
4851 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4852 Op1I->getOperand(0),
4853 Op0I->getName()), I);
4854 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4855 Op1I->getOperand(1));
4856 }
4857
4858 if (Op0I && Op1I) {
4859 Value *A, *B, *C, *D;
4860 // (A & B)^(A | B) -> A ^ B
4861 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4862 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4863 if ((A == C && B == D) || (A == D && B == C))
4864 return BinaryOperator::createXor(A, B);
4865 }
4866 // (A | B)^(A & B) -> A ^ B
4867 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4868 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4869 if ((A == C && B == D) || (A == D && B == C))
4870 return BinaryOperator::createXor(A, B);
4871 }
4872
4873 // (A & B)^(C & D)
4874 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4875 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4876 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4877 // (X & Y)^(X & Y) -> (Y^Z) & X
4878 Value *X = 0, *Y = 0, *Z = 0;
4879 if (A == C)
4880 X = A, Y = B, Z = D;
4881 else if (A == D)
4882 X = A, Y = B, Z = C;
4883 else if (B == C)
4884 X = B, Y = A, Z = D;
4885 else if (B == D)
4886 X = B, Y = A, Z = C;
4887
4888 if (X) {
4889 Instruction *NewOp =
4890 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4891 return BinaryOperator::createAnd(NewOp, X);
4892 }
4893 }
4894 }
4895
Reid Spencer266e42b2006-12-23 06:05:41 +00004896 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4897 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4898 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004899 return R;
4900
Chris Lattner3af10532006-05-05 06:39:07 +00004901 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004902 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004903 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004904 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4905 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004906 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004907 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004908 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4909 I.getType(), TD) &&
4910 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4911 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004912 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4913 Op1C->getOperand(0),
4914 I.getName());
4915 InsertNewInstBefore(NewOp, I);
4916 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4917 }
Chris Lattner3af10532006-05-05 06:39:07 +00004918 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004919
Chris Lattner113f4f42002-06-25 16:13:24 +00004920 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004921}
4922
Chris Lattner6862fbd2004-09-29 17:40:11 +00004923/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4924/// overflowed for this type.
4925static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004926 ConstantInt *In2, bool IsSigned = false) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004927 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4928
Reid Spencerf4071162007-03-21 23:19:50 +00004929 if (IsSigned)
4930 if (In2->getValue().isNegative())
4931 return Result->getValue().sgt(In1->getValue());
4932 else
4933 return Result->getValue().slt(In1->getValue());
4934 else
4935 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004936}
4937
Chris Lattner0798af32005-01-13 20:14:25 +00004938/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4939/// code necessary to compute the offset from the base pointer (without adding
4940/// in the base pointer). Return the result as a signed integer of intptr size.
4941static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4942 TargetData &TD = IC.getTargetData();
4943 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004944 const Type *IntPtrTy = TD.getIntPtrType();
4945 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004946
4947 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004948 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004949
Chris Lattner0798af32005-01-13 20:14:25 +00004950 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4951 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004952 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004953 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004954 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4955 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004956 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004957 Scale = ConstantExpr::getMul(OpC, Scale);
4958 if (Constant *RC = dyn_cast<Constant>(Result))
4959 Result = ConstantExpr::getAdd(RC, Scale);
4960 else {
4961 // Emit an add instruction.
4962 Result = IC.InsertNewInstBefore(
4963 BinaryOperator::createAdd(Result, Scale,
4964 GEP->getName()+".offs"), I);
4965 }
4966 }
4967 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004968 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004969 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004970 Op->getName()+".c"), I);
4971 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004972 // We'll let instcombine(mul) convert this to a shl if possible.
4973 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4974 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004975
4976 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004977 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004978 GEP->getName()+".offs"), I);
4979 }
4980 }
4981 return Result;
4982}
4983
Reid Spencer266e42b2006-12-23 06:05:41 +00004984/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004985/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004986Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4987 ICmpInst::Predicate Cond,
4988 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004989 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004990
4991 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4992 if (isa<PointerType>(CI->getOperand(0)->getType()))
4993 RHS = CI->getOperand(0);
4994
Chris Lattner0798af32005-01-13 20:14:25 +00004995 Value *PtrBase = GEPLHS->getOperand(0);
4996 if (PtrBase == RHS) {
4997 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004998 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4999 // each index is zero or not.
5000 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00005001 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00005002 gep_type_iterator GTI = gep_type_begin(GEPLHS);
5003 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00005004 bool EmitIt = true;
5005 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
5006 if (isa<UndefValue>(C)) // undef index -> undef.
5007 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5008 if (C->isNullValue())
5009 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00005010 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
5011 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00005012 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00005013 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00005014 ConstantInt::get(Type::Int1Ty,
5015 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00005016 }
5017
5018 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005019 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00005020 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00005021 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
5022 if (InVal == 0)
5023 InVal = Comp;
5024 else {
5025 InVal = InsertNewInstBefore(InVal, I);
5026 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005027 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00005028 InVal = BinaryOperator::createOr(InVal, Comp);
5029 else // True if all are equal
5030 InVal = BinaryOperator::createAnd(InVal, Comp);
5031 }
5032 }
5033 }
5034
5035 if (InVal)
5036 return InVal;
5037 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005038 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00005039 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5040 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00005041 }
Chris Lattner0798af32005-01-13 20:14:25 +00005042
Reid Spencer266e42b2006-12-23 06:05:41 +00005043 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005044 // the result to fold to a constant!
5045 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
5046 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5047 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5049 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00005050 }
5051 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005052 // If the base pointers are different, but the indices are the same, just
5053 // compare the base pointer.
5054 if (PtrBase != GEPRHS->getOperand(0)) {
5055 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005056 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00005057 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005058 if (IndicesTheSame)
5059 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5060 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5061 IndicesTheSame = false;
5062 break;
5063 }
5064
5065 // If all indices are the same, just compare the base pointers.
5066 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00005067 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5068 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005069
5070 // Otherwise, the base pointers are different and the indices are
5071 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00005072 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00005073 }
Chris Lattner0798af32005-01-13 20:14:25 +00005074
Chris Lattner81e84172005-01-13 22:25:21 +00005075 // If one of the GEPs has all zero indices, recurse.
5076 bool AllZeros = true;
5077 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5078 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5079 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5080 AllZeros = false;
5081 break;
5082 }
5083 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005084 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5085 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00005086
5087 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00005088 AllZeros = true;
5089 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5090 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5091 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5092 AllZeros = false;
5093 break;
5094 }
5095 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005096 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00005097
Chris Lattner4fa89822005-01-14 00:20:05 +00005098 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5099 // If the GEPs only differ by one index, compare it.
5100 unsigned NumDifferences = 0; // Keep track of # differences.
5101 unsigned DiffOperand = 0; // The operand that differs.
5102 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5103 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005104 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5105 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005106 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00005107 NumDifferences = 2;
5108 break;
5109 } else {
5110 if (NumDifferences++) break;
5111 DiffOperand = i;
5112 }
5113 }
5114
5115 if (NumDifferences == 0) // SAME GEP?
5116 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00005117 ConstantInt::get(Type::Int1Ty,
5118 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00005119 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00005120 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5121 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00005122 // Make sure we do a signed comparison here.
5123 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00005124 }
5125 }
5126
Reid Spencer266e42b2006-12-23 06:05:41 +00005127 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00005128 // the result to fold to a constant!
5129 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5130 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5131 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5132 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5133 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00005134 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00005135 }
5136 }
5137 return 0;
5138}
5139
Reid Spencer266e42b2006-12-23 06:05:41 +00005140Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5141 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005142 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005143
Chris Lattner6ee923f2007-01-14 19:42:17 +00005144 // Fold trivial predicates.
5145 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5146 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5147 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5148 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5149
5150 // Simplify 'fcmp pred X, X'
5151 if (Op0 == Op1) {
5152 switch (I.getPredicate()) {
5153 default: assert(0 && "Unknown predicate!");
5154 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5155 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5156 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5157 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5158 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5159 case FCmpInst::FCMP_OLT: // True if ordered and less than
5160 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5161 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5162
5163 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5164 case FCmpInst::FCMP_ULT: // True if unordered or less than
5165 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5166 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5167 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5168 I.setPredicate(FCmpInst::FCMP_UNO);
5169 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5170 return &I;
5171
5172 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5173 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5174 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5175 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5176 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5177 I.setPredicate(FCmpInst::FCMP_ORD);
5178 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5179 return &I;
5180 }
5181 }
5182
Reid Spencer266e42b2006-12-23 06:05:41 +00005183 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005184 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00005185
Reid Spencer266e42b2006-12-23 06:05:41 +00005186 // Handle fcmp with constant RHS
5187 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5188 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5189 switch (LHSI->getOpcode()) {
5190 case Instruction::PHI:
5191 if (Instruction *NV = FoldOpIntoPhi(I))
5192 return NV;
5193 break;
5194 case Instruction::Select:
5195 // If either operand of the select is a constant, we can fold the
5196 // comparison into the select arms, which will cause one to be
5197 // constant folded and the select turned into a bitwise or.
5198 Value *Op1 = 0, *Op2 = 0;
5199 if (LHSI->hasOneUse()) {
5200 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5201 // Fold the known value into the constant operand.
5202 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5203 // Insert a new FCmp of the other select operand.
5204 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5205 LHSI->getOperand(2), RHSC,
5206 I.getName()), I);
5207 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5208 // Fold the known value into the constant operand.
5209 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5210 // Insert a new FCmp of the other select operand.
5211 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5212 LHSI->getOperand(1), RHSC,
5213 I.getName()), I);
5214 }
5215 }
5216
5217 if (Op1)
5218 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5219 break;
5220 }
5221 }
5222
5223 return Changed ? &I : 0;
5224}
5225
5226Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5227 bool Changed = SimplifyCompare(I);
5228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5229 const Type *Ty = Op0->getType();
5230
5231 // icmp X, X
5232 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00005233 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5234 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005235
5236 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00005237 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00005238
5239 // icmp of GlobalValues can never equal each other as long as they aren't
5240 // external weak linkage type.
5241 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
5242 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
5243 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00005244 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5245 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005246
5247 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00005248 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005249 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5250 isa<ConstantPointerNull>(Op0)) &&
5251 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00005252 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00005253 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5254 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005255
Reid Spencer266e42b2006-12-23 06:05:41 +00005256 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00005257 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005258 switch (I.getPredicate()) {
5259 default: assert(0 && "Invalid icmp instruction!");
5260 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005261 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005262 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00005263 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005264 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005265 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00005266 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005267
Reid Spencer266e42b2006-12-23 06:05:41 +00005268 case ICmpInst::ICMP_UGT:
5269 case ICmpInst::ICMP_SGT:
5270 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00005271 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005272 case ICmpInst::ICMP_ULT:
5273 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00005274 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5275 InsertNewInstBefore(Not, I);
5276 return BinaryOperator::createAnd(Not, Op1);
5277 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005278 case ICmpInst::ICMP_UGE:
5279 case ICmpInst::ICMP_SGE:
5280 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00005281 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00005282 case ICmpInst::ICMP_ULE:
5283 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00005284 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5285 InsertNewInstBefore(Not, I);
5286 return BinaryOperator::createOr(Not, Op1);
5287 }
5288 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005289 }
5290
Chris Lattner2dd01742004-06-09 04:24:29 +00005291 // See if we are doing a comparison between a constant and an instruction that
5292 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00005293 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005294 switch (I.getPredicate()) {
5295 default: break;
5296 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5297 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005298 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005299 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5300 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5301 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5302 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5303 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005304
Reid Spencer266e42b2006-12-23 06:05:41 +00005305 case ICmpInst::ICMP_SLT:
5306 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005307 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005308 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5309 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5310 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5311 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5312 break;
5313
5314 case ICmpInst::ICMP_UGT:
5315 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005316 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005317 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5318 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5319 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5320 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5321 break;
5322
5323 case ICmpInst::ICMP_SGT:
5324 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005325 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005326 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5327 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5328 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5329 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5330 break;
5331
5332 case ICmpInst::ICMP_ULE:
5333 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005334 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005335 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5336 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5337 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5338 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5339 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005340
Reid Spencer266e42b2006-12-23 06:05:41 +00005341 case ICmpInst::ICMP_SLE:
5342 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005343 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005344 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5345 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5346 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5347 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5348 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005349
Reid Spencer266e42b2006-12-23 06:05:41 +00005350 case ICmpInst::ICMP_UGE:
5351 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005352 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005353 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5354 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5355 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5356 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5357 break;
5358
5359 case ICmpInst::ICMP_SGE:
5360 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00005361 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005362 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5363 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5364 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5365 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5366 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005367 }
5368
Reid Spencer266e42b2006-12-23 06:05:41 +00005369 // If we still have a icmp le or icmp ge instruction, turn it into the
5370 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00005371 // already been handled above, this requires little checking.
5372 //
Reid Spencer266e42b2006-12-23 06:05:41 +00005373 if (I.getPredicate() == ICmpInst::ICMP_ULE)
5374 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5375 if (I.getPredicate() == ICmpInst::ICMP_SLE)
5376 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5377 if (I.getPredicate() == ICmpInst::ICMP_UGE)
5378 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5379 if (I.getPredicate() == ICmpInst::ICMP_SGE)
5380 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00005381
5382 // See if we can fold the comparison based on bits known to be zero or one
5383 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005384 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5385 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5386 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00005387 KnownZero, KnownOne, 0))
5388 return &I;
5389
5390 // Given the known and unknown bits, compute a range that the LHS could be
5391 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005392 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005393 // Compute the Min, Max and RHS values based on the known bits. For the
5394 // EQ and NE we use unsigned values.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005395 APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005396 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005397 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5398 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00005399 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005400 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5401 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00005402 }
5403 switch (I.getPredicate()) { // LE/GE have been folded already.
5404 default: assert(0 && "Unknown icmp opcode!");
5405 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005406 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005407 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005408 break;
5409 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005410 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005411 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 break;
5413 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005414 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005415 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005416 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005417 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005418 break;
5419 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005420 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005421 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005422 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005423 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005424 break;
5425 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005426 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005427 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005428 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005429 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005430 break;
5431 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005432 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005433 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005434 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00005435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005436 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00005437 }
5438 }
5439
Reid Spencer266e42b2006-12-23 06:05:41 +00005440 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005441 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00005442 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00005443 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005444 switch (LHSI->getOpcode()) {
5445 case Instruction::And:
5446 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5447 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00005448 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5449
Reid Spencer266e42b2006-12-23 06:05:41 +00005450 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00005451 // and/compare to be the input width without changing the value
5452 // produced, eliminating a cast.
5453 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
5454 // We can do this transformation if either the AND constant does not
5455 // have its sign bit set or if it is an equality comparison.
5456 // Extending a relational comparison when we're checking the sign
5457 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005458 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005459 (I.isEquality() || AndCST->getValue().isPositive() &&
5460 CI->getValue().isPositive())) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00005461 ConstantInt *NewCST;
5462 ConstantInt *NewCI;
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005463 APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
5464 uint32_t BitWidth = cast<IntegerType>(
5465 Cast->getOperand(0)->getType())->getBitWidth();
5466 NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
5467 NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
Chris Lattner4922a0e2006-09-18 05:27:43 +00005468 Instruction *NewAnd =
5469 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
5470 LHSI->getName());
5471 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005472 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00005473 }
5474 }
5475
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005476 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5477 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5478 // happens a LOT in code produced by the C front-end, for bitfield
5479 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00005480 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5481 if (Shift && !Shift->isShift())
5482 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005483
Reid Spencere0fc4df2006-10-20 07:07:24 +00005484 ConstantInt *ShAmt;
5485 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00005486 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5487 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005488
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005489 // We can fold this as long as we can't shift unknown bits
5490 // into the mask. This can only happen with signed shift
5491 // rights, as they sign-extend.
5492 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005493 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005494 if (!CanFold) {
5495 // To test for the bad case of the signed shr, see if any
5496 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005497 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00005498 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
5499
Reid Spencer2341c222007-02-02 02:16:23 +00005500 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005501 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00005502 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
5503 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005504 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
5505 CanFold = true;
5506 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005507
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005508 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00005509 Constant *NewCst;
5510 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005511 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005512 else
5513 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005514
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005515 // Check to see if we are shifting out any of the bits being
5516 // compared.
5517 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
5518 // If we shifted bits out, the fold is not going to work out.
5519 // As a special case, check to see if this means that the
5520 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00005521 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005522 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005523 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005524 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005525 } else {
5526 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005527 Constant *NewAndCST;
5528 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00005529 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00005530 else
5531 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5532 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00005533 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005534 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005535 AddUsesToWorkList(I);
5536 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00005537 }
5538 }
Chris Lattner35167c32004-06-09 07:59:58 +00005539 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005540
5541 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5542 // preferable because it allows the C<<Y expression to be hoisted out
5543 // of a loop if Y is invariant and X is not.
5544 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00005545 I.isEquality() && !Shift->isArithmeticShift() &&
5546 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005547 // Compute C << Y.
5548 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00005549 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005550 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005551 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005552 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00005553 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00005554 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00005555 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005556 }
5557 InsertNewInstBefore(cast<Instruction>(NS), I);
5558
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005559 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00005560 Instruction *NewAnd = BinaryOperator::createAnd(
5561 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005562 InsertNewInstBefore(NewAnd, I);
5563
5564 I.setOperand(0, NewAnd);
5565 return &I;
5566 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005567 }
5568 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005569
Reid Spencer266e42b2006-12-23 06:05:41 +00005570 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005571 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005572 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005573 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
5574
5575 // Check that the shift amount is in range. If not, don't perform
5576 // undefined shifts. When the shift is visited it will be
5577 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005578 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005579 break;
5580
Chris Lattner272d5ca2004-09-28 18:22:15 +00005581 // If we are comparing against bits always shifted out, the
5582 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005583 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00005584 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005585 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005586 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005587 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00005588 return ReplaceInstUsesWith(I, Cst);
5589 }
5590
5591 if (LHSI->hasOneUse()) {
5592 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005593 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005594 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00005595 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005596
Chris Lattner272d5ca2004-09-28 18:22:15 +00005597 Instruction *AndI =
5598 BinaryOperator::createAnd(LHSI->getOperand(0),
5599 Mask, LHSI->getName()+".mask");
5600 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005601 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00005602 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00005603 }
5604 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00005605 }
5606 break;
5607
Reid Spencer266e42b2006-12-23 06:05:41 +00005608 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00005609 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00005610 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005611 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00005612 // Check that the shift amount is in range. If not, don't perform
5613 // undefined shifts. When the shift is visited it will be
5614 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00005615 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005616 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00005617 break;
5618
Chris Lattner1023b872004-09-27 16:18:50 +00005619 // If we are comparing against bits always shifted out, the
5620 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00005621 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00005622 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00005623 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
5624 ShAmt);
5625 else
5626 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
5627 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005628
Chris Lattner1023b872004-09-27 16:18:50 +00005629 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00005630 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00005631 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00005632 return ReplaceInstUsesWith(I, Cst);
5633 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005634
Chris Lattner1023b872004-09-27 16:18:50 +00005635 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005636 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00005637
Chris Lattner1023b872004-09-27 16:18:50 +00005638 // Otherwise strength reduce the shift into an and.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005639 APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
5640 Constant *Mask = ConstantInt::get(Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005641
Chris Lattner1023b872004-09-27 16:18:50 +00005642 Instruction *AndI =
5643 BinaryOperator::createAnd(LHSI->getOperand(0),
5644 Mask, LHSI->getName()+".mask");
5645 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005646 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00005647 ConstantExpr::getShl(CI, ShAmt));
5648 }
Chris Lattner1023b872004-09-27 16:18:50 +00005649 }
5650 }
5651 break;
Chris Lattner7e794272004-09-24 15:21:34 +00005652
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005653 case Instruction::SDiv:
5654 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00005655 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005656 // Fold this div into the comparison, producing a range check.
5657 // Determine, based on the divide type, what the range is being
5658 // checked. If there is an overflow on the low or high side, remember
5659 // it, otherwise compute the range [low, hi) bounding the new value.
5660 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005661 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005662 // FIXME: If the operand types don't match the type of the divide
5663 // then don't attempt this transform. The code below doesn't have the
5664 // logic to deal with a signed divide and an unsigned compare (and
5665 // vice versa). This is because (x /s C1) <s C2 produces different
5666 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5667 // (x /u C1) <u C2. Simply casting the operands and result won't
5668 // work. :( The if statement below tests that condition and bails
5669 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00005670 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5671 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005672 break;
Reid Spencerf4071162007-03-21 23:19:50 +00005673 if (DivRHS->isZero())
5674 break; // Don't hack on div by zero
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005675
5676 // Initialize the variables that will indicate the nature of the
5677 // range check.
5678 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00005679 ConstantInt *LoBound = 0, *HiBound = 0;
5680
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005681 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5682 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5683 // C2 (CI). By solving for X we can turn this into a range check
5684 // instead of computing a divide.
5685 ConstantInt *Prod =
5686 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00005687
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005688 // Determine if the product overflows by seeing if the product is
5689 // not equal to the divide. Make sure we do the same kind of divide
5690 // as in the LHS instruction that we're folding.
Reid Spencerf4071162007-03-21 23:19:50 +00005691 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5692 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005693
Reid Spencer266e42b2006-12-23 06:05:41 +00005694 // Get the ICmp opcode
5695 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00005696
Reid Spencerf4071162007-03-21 23:19:50 +00005697 if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00005698 LoBound = Prod;
5699 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00005700 HiOverflow = ProdOV ||
5701 AddWithOverflow(HiBound, LoBound, DivRHS, false);
Reid Spencer450434e2007-03-19 20:58:18 +00005702 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005703 if (CI->isNullValue()) { // (X / pos) op 0
5704 // Can't overflow.
5705 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5706 HiBound = DivRHS;
Reid Spencer450434e2007-03-19 20:58:18 +00005707 } else if (CI->getValue().isPositive()) { // (X / pos) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005708 LoBound = Prod;
5709 LoOverflow = ProdOV;
Reid Spencerf4071162007-03-21 23:19:50 +00005710 HiOverflow = ProdOV ||
5711 AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005712 } else { // (X / pos) op neg
5713 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5714 LoOverflow = AddWithOverflow(LoBound, Prod,
Reid Spencerf4071162007-03-21 23:19:50 +00005715 cast<ConstantInt>(DivRHSH), true);
5716 HiBound = AddOne(Prod);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005717 HiOverflow = ProdOV;
5718 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005719 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00005720 if (CI->isNullValue()) { // (X / neg) op 0
5721 LoBound = AddOne(DivRHS);
5722 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00005723 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005724 LoBound = 0; // - INTMIN = INTMIN
Reid Spencer450434e2007-03-19 20:58:18 +00005725 } else if (CI->getValue().isPositive()) { // (X / neg) op pos
Chris Lattner6862fbd2004-09-29 17:40:11 +00005726 HiOverflow = LoOverflow = ProdOV;
5727 if (!LoOverflow)
Reid Spencerf4071162007-03-21 23:19:50 +00005728 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5729 true);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005730 HiBound = AddOne(Prod);
5731 } else { // (X / neg) op neg
5732 LoBound = Prod;
5733 LoOverflow = HiOverflow = ProdOV;
5734 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5735 }
Chris Lattner0b41e862004-10-08 19:15:44 +00005736
Chris Lattnera92af962004-10-11 19:40:04 +00005737 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00005738 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005739 }
5740
5741 if (LoBound) {
5742 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005743 switch (predicate) {
5744 default: assert(0 && "Unhandled icmp opcode!");
5745 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005746 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005747 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005748 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005749 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5750 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005751 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005752 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5753 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005754 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005755 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5756 true, I);
5757 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005758 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005759 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00005760 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005761 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5762 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005763 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00005764 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5765 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005766 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005767 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5768 false, I);
5769 case ICmpInst::ICMP_ULT:
5770 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005771 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005772 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005773 return new ICmpInst(predicate, X, LoBound);
5774 case ICmpInst::ICMP_UGT:
5775 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00005776 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005777 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005778 if (predicate == ICmpInst::ICMP_UGT)
5779 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5780 else
5781 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00005782 }
5783 }
5784 }
5785 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00005786 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005787
Reid Spencer266e42b2006-12-23 06:05:41 +00005788 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005789 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005790 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005791
Reid Spencere0fc4df2006-10-20 07:07:24 +00005792 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5793 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00005794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5795 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005796 case Instruction::SRem:
5797 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005798 if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00005799 BO->hasOneUse()) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005800 APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5801 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00005802 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5803 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005804 return new ICmpInst(I.getPredicate(), NewRem,
5805 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00005806 }
Chris Lattner22d00a82005-08-02 19:16:58 +00005807 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005808 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00005809 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00005810 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5811 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00005812 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00005813 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5814 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00005815 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005816 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5817 // efficiently invertible, or if the add has just this one use.
5818 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005819
Chris Lattnerc992add2003-08-13 05:33:12 +00005820 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005821 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005822 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005823 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005824 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00005825 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00005826 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005827 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00005828 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005829 }
5830 }
5831 break;
5832 case Instruction::Xor:
5833 // For the xor case, we can xor two constants together, eliminating
5834 // the explicit xor.
5835 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005836 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5837 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005838
5839 // FALLTHROUGH
5840 case Instruction::Sub:
5841 // Replace (([sub|xor] A, B) != 0) with (A != B)
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005842 if (CI->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00005843 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5844 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005845 break;
5846
5847 case Instruction::Or:
5848 // If bits are being or'd in that are not present in the constant we
5849 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005850 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005851 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005852 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005853 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5854 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005855 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005856 break;
5857
5858 case Instruction::And:
5859 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005860 // If bits are being compared against that are and'd out, then the
5861 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005862 if (!ConstantExpr::getAnd(CI,
5863 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005864 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5865 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005866
Chris Lattner35167c32004-06-09 07:59:58 +00005867 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005868 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005869 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5870 ICmpInst::ICMP_NE, Op0,
5871 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005872
Reid Spencer266e42b2006-12-23 06:05:41 +00005873 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005874 if (isSignBit(BOC)) {
5875 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005876 Constant *Zero = Constant::getNullValue(X->getType());
5877 ICmpInst::Predicate pred = isICMP_NE ?
5878 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5879 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005880 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005881
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005882 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005883 if (CI->isNullValue() && isHighOnes(BOC)) {
5884 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005885 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005886 ICmpInst::Predicate pred = isICMP_NE ?
5887 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5888 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005889 }
5890
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005891 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005892 default: break;
5893 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005894 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5895 // Handle set{eq|ne} <intrinsic>, intcst.
5896 switch (II->getIntrinsicID()) {
5897 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005898 case Intrinsic::bswap_i16:
5899 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005900 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005901 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005902 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005903 ByteSwap_16(CI->getZExtValue())));
5904 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005905 case Intrinsic::bswap_i32:
5906 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005907 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005908 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005909 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005910 ByteSwap_32(CI->getZExtValue())));
5911 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005912 case Intrinsic::bswap_i64:
5913 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005914 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005915 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005916 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005917 ByteSwap_64(CI->getZExtValue())));
5918 return &I;
5919 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005920 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005921 } else { // Not a ICMP_EQ/ICMP_NE
5922 // If the LHS is a cast from an integral value of the same size, then
5923 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005924 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5925 Value *CastOp = Cast->getOperand(0);
5926 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005927 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005928 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005929 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005930 // If this is an unsigned comparison, try to make the comparison use
5931 // smaller constant values.
5932 switch (I.getPredicate()) {
5933 default: break;
5934 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5935 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005936 if (CUI->getValue() == APInt::getSignBit(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005937 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005938 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
Reid Spencer266e42b2006-12-23 06:05:41 +00005939 break;
5940 }
5941 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5942 ConstantInt *CUI = cast<ConstantInt>(CI);
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005943 if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
Reid Spencer266e42b2006-12-23 06:05:41 +00005944 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5945 Constant::getNullValue(SrcTy));
5946 break;
5947 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005948 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005949
Chris Lattner2b55ea32004-02-23 07:16:20 +00005950 }
5951 }
Chris Lattnere967b342003-06-04 05:10:11 +00005952 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005953 }
5954
Reid Spencer266e42b2006-12-23 06:05:41 +00005955 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005956 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5957 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5958 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005959 case Instruction::GetElementPtr:
5960 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005961 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005962 bool isAllZeros = true;
5963 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5964 if (!isa<Constant>(LHSI->getOperand(i)) ||
5965 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5966 isAllZeros = false;
5967 break;
5968 }
5969 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005970 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005971 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5972 }
5973 break;
5974
Chris Lattner77c32c32005-04-23 15:31:55 +00005975 case Instruction::PHI:
5976 if (Instruction *NV = FoldOpIntoPhi(I))
5977 return NV;
5978 break;
5979 case Instruction::Select:
5980 // If either operand of the select is a constant, we can fold the
5981 // comparison into the select arms, which will cause one to be
5982 // constant folded and the select turned into a bitwise or.
5983 Value *Op1 = 0, *Op2 = 0;
5984 if (LHSI->hasOneUse()) {
5985 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5986 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005987 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988 // Insert a new ICmp of the other select operand.
5989 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990 LHSI->getOperand(2), RHSC,
5991 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005992 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5993 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005994 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5995 // Insert a new ICmp of the other select operand.
5996 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5997 LHSI->getOperand(1), RHSC,
5998 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005999 }
6000 }
Jeff Cohen82639852005-04-23 21:38:35 +00006001
Chris Lattner77c32c32005-04-23 15:31:55 +00006002 if (Op1)
6003 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
6004 break;
6005 }
6006 }
6007
Reid Spencer266e42b2006-12-23 06:05:41 +00006008 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00006009 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00006010 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00006011 return NI;
6012 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006013 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6014 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00006015 return NI;
6016
Reid Spencer266e42b2006-12-23 06:05:41 +00006017 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00006018 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6019 // now.
6020 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6021 if (isa<PointerType>(Op0->getType()) &&
6022 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00006023 // We keep moving the cast from the left operand over to the right
6024 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00006025 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006026
Chris Lattner64d87b02007-01-06 01:45:59 +00006027 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6028 // so eliminate it as well.
6029 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6030 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006031
Chris Lattner16930792003-11-03 04:25:02 +00006032 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00006033 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00006034 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006035 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00006036 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00006037 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00006038 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00006039 }
Reid Spencer266e42b2006-12-23 06:05:41 +00006040 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00006041 }
Chris Lattner64d87b02007-01-06 01:45:59 +00006042 }
6043
6044 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006045 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00006046 // This comes up when you have code like
6047 // int X = A < B;
6048 // if (X) ...
6049 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006050 // with a constant or another cast from the same type.
6051 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00006052 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006053 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00006054 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006055
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006056 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00006057 Value *A, *B, *C, *D;
6058 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6059 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6060 Value *OtherVal = A == Op1 ? B : A;
6061 return new ICmpInst(I.getPredicate(), OtherVal,
6062 Constant::getNullValue(A->getType()));
6063 }
6064
6065 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6066 // A^c1 == C^c2 --> A == C^(c1^c2)
6067 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6068 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6069 if (Op1->hasOneUse()) {
6070 Constant *NC = ConstantExpr::getXor(C1, C2);
6071 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
6072 return new ICmpInst(I.getPredicate(), A,
6073 InsertNewInstBefore(Xor, I));
6074 }
6075
6076 // A^B == A^D -> B == D
6077 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6078 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6079 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6080 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6081 }
6082 }
6083
6084 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6085 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006086 // A == (A^B) -> B == 0
6087 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00006088 return new ICmpInst(I.getPredicate(), OtherVal,
6089 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006090 }
6091 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006092 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006093 return new ICmpInst(I.getPredicate(), B,
6094 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00006095 }
6096 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006097 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00006098 return new ICmpInst(I.getPredicate(), B,
6099 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006100 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006101
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00006102 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6103 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6104 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6105 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6106 Value *X = 0, *Y = 0, *Z = 0;
6107
6108 if (A == C) {
6109 X = B; Y = D; Z = A;
6110 } else if (A == D) {
6111 X = B; Y = C; Z = A;
6112 } else if (B == C) {
6113 X = A; Y = D; Z = B;
6114 } else if (B == D) {
6115 X = A; Y = C; Z = B;
6116 }
6117
6118 if (X) { // Build (X^Y) & Z
6119 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
6120 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
6121 I.setOperand(0, Op1);
6122 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6123 return &I;
6124 }
6125 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00006126 }
Chris Lattner113f4f42002-06-25 16:13:24 +00006127 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006128}
6129
Reid Spencer266e42b2006-12-23 06:05:41 +00006130// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006131// We only handle extending casts so far.
6132//
Reid Spencer266e42b2006-12-23 06:05:41 +00006133Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6134 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006135 Value *LHSCIOp = LHSCI->getOperand(0);
6136 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00006137 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006138 Value *RHSCIOp;
6139
Reid Spencer266e42b2006-12-23 06:05:41 +00006140 // We only handle extension cast instructions, so far. Enforce this.
6141 if (LHSCI->getOpcode() != Instruction::ZExt &&
6142 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00006143 return 0;
6144
Reid Spencer266e42b2006-12-23 06:05:41 +00006145 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6146 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006147
Reid Spencer266e42b2006-12-23 06:05:41 +00006148 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006149 // Not an extension from the same type?
6150 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006151 if (RHSCIOp->getType() != LHSCIOp->getType())
6152 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00006153
6154 // If the signedness of the two compares doesn't agree (i.e. one is a sext
6155 // and the other is a zext), then we can't handle this.
6156 if (CI->getOpcode() != LHSCI->getOpcode())
6157 return 0;
6158
6159 // Likewise, if the signedness of the [sz]exts and the compare don't match,
6160 // then we can't handle this.
6161 if (isSignedExt != isSignedCmp && !ICI.isEquality())
6162 return 0;
6163
6164 // Okay, just insert a compare of the reduced operands now!
6165 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00006166 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006167
Reid Spencer266e42b2006-12-23 06:05:41 +00006168 // If we aren't dealing with a constant on the RHS, exit early
6169 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6170 if (!CI)
6171 return 0;
6172
6173 // Compute the constant that would happen if we truncated to SrcTy then
6174 // reextended to DestTy.
6175 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6176 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6177
6178 // If the re-extended constant didn't change...
6179 if (Res2 == CI) {
6180 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6181 // For example, we might have:
6182 // %A = sext short %X to uint
6183 // %B = icmp ugt uint %A, 1330
6184 // It is incorrect to transform this into
6185 // %B = icmp ugt short %X, 1330
6186 // because %A may have negative value.
6187 //
6188 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6189 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00006190 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00006191 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6192 else
6193 return 0;
6194 }
6195
6196 // The re-extended constant changed so the constant cannot be represented
6197 // in the shorter type. Consequently, we cannot emit a simple comparison.
6198
6199 // First, handle some easy cases. We know the result cannot be equal at this
6200 // point so handle the ICI.isEquality() cases
6201 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006202 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00006203 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00006204 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00006205
6206 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6207 // should have been folded away previously and not enter in here.
6208 Value *Result;
6209 if (isSignedCmp) {
6210 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006211 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00006212 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00006213 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00006214 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006215 } else {
6216 // We're performing an unsigned comparison.
6217 if (isSignedExt) {
6218 // We're performing an unsigned comp with a sign extended value.
6219 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00006220 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00006221 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6222 NegOne, ICI.getName()), ICI);
6223 } else {
6224 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00006225 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006226 }
6227 }
6228
6229 // Finally, return the value computed.
6230 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6231 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6232 return ReplaceInstUsesWith(ICI, Result);
6233 } else {
6234 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6235 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6236 "ICmp should be folded!");
6237 if (Constant *CI = dyn_cast<Constant>(Result))
6238 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6239 else
6240 return BinaryOperator::createNot(Result);
6241 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006242}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006243
Reid Spencer2341c222007-02-02 02:16:23 +00006244Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6245 return commonShiftTransforms(I);
6246}
6247
6248Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6249 return commonShiftTransforms(I);
6250}
6251
6252Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6253 return commonShiftTransforms(I);
6254}
6255
6256Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6257 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00006258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006259
6260 // shl X, 0 == X and shr X, 0 == X
6261 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00006262 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00006263 Op0 == Constant::getNullValue(Op0->getType()))
6264 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006265
Reid Spencer266e42b2006-12-23 06:05:41 +00006266 if (isa<UndefValue>(Op0)) {
6267 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00006268 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00006269 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6271 }
6272 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006273 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6274 return ReplaceInstUsesWith(I, Op0);
6275 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00006276 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00006277 }
6278
Chris Lattnerd4dee402006-11-10 23:38:52 +00006279 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6280 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00006281 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00006282 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006283 return ReplaceInstUsesWith(I, CSI);
6284
Chris Lattner183b3362004-04-09 19:05:30 +00006285 // Try to fold constant and into select arguments.
6286 if (isa<Constant>(Op0))
6287 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00006288 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00006289 return R;
6290
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006291 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006292 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00006293 if (MaskedValueIsZero(Op0,
6294 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006295 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00006296 }
6297 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006298
Reid Spencere0fc4df2006-10-20 07:07:24 +00006299 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00006300 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6301 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00006302 return 0;
6303}
6304
Reid Spencere0fc4df2006-10-20 07:07:24 +00006305Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00006306 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00006307 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00006308
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006309 // See if we can simplify any instructions used by the instruction whose sole
6310 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00006311 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6312 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6313 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00006314 KnownZero, KnownOne))
6315 return &I;
6316
Chris Lattner14553932006-01-06 07:12:35 +00006317 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6318 // of a signed value.
6319 //
Reid Spencer6274c722007-03-23 18:46:34 +00006320 if (Op1->getZExtValue() >= TypeBits) { // shift amount always <= 32 bits
Chris Lattnerd5fea612007-02-02 05:29:55 +00006321 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00006322 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6323 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00006324 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00006325 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00006326 }
Chris Lattner14553932006-01-06 07:12:35 +00006327 }
6328
6329 // ((X*C1) << C2) == (X * (C1 << C2))
6330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6331 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6332 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6333 return BinaryOperator::createMul(BO->getOperand(0),
6334 ConstantExpr::getShl(BOOp, Op1));
6335
6336 // Try to fold constant and into select arguments.
6337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6338 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6339 return R;
6340 if (isa<PHINode>(Op0))
6341 if (Instruction *NV = FoldOpIntoPhi(I))
6342 return NV;
6343
6344 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00006345 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6346 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6347 Value *V1, *V2;
6348 ConstantInt *CC;
6349 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006350 default: break;
6351 case Instruction::Add:
6352 case Instruction::And:
6353 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00006354 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006355 // These operators commute.
6356 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006357 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6358 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00006359 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006360 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00006361 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00006362 Op0BO->getName());
6363 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006364 Instruction *X =
6365 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6366 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006367 InsertNewInstBefore(X, I); // (X + (Y << C))
6368 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006369 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006370 return BinaryOperator::createAnd(X, C2);
6371 }
Chris Lattner14553932006-01-06 07:12:35 +00006372
Chris Lattner797dee72005-09-18 06:30:59 +00006373 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00006374 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006375 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00006376 match(Op0BOOp1,
6377 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00006378 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6379 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006380 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006381 Op0BO->getOperand(0), Op1,
6382 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006383 InsertNewInstBefore(YS, I); // (Y << C)
6384 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006385 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006386 V1->getName()+".mask");
6387 InsertNewInstBefore(XM, I); // X & (CC << C)
6388
6389 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6390 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006391 }
Chris Lattner14553932006-01-06 07:12:35 +00006392
Reid Spencer2f34b982007-02-02 14:41:37 +00006393 // FALL THROUGH.
6394 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00006395 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006396 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6397 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00006398 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006399 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006400 Op0BO->getOperand(1), Op1,
6401 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006402 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006403 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00006404 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006405 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006406 InsertNewInstBefore(X, I); // (X + (Y << C))
6407 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00006408 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00006409 return BinaryOperator::createAnd(X, C2);
6410 }
Chris Lattner14553932006-01-06 07:12:35 +00006411
Chris Lattner1df0e982006-05-31 21:14:00 +00006412 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00006413 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6414 match(Op0BO->getOperand(0),
6415 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00006416 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00006417 cast<BinaryOperator>(Op0BO->getOperand(0))
6418 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00006419 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00006420 Op0BO->getOperand(1), Op1,
6421 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00006422 InsertNewInstBefore(YS, I); // (Y << C)
6423 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00006424 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00006425 V1->getName()+".mask");
6426 InsertNewInstBefore(XM, I); // X & (CC << C)
6427
Chris Lattner1df0e982006-05-31 21:14:00 +00006428 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00006429 }
Chris Lattner14553932006-01-06 07:12:35 +00006430
Chris Lattner27cb9db2005-09-18 05:12:10 +00006431 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00006432 }
Chris Lattner14553932006-01-06 07:12:35 +00006433 }
6434
6435
6436 // If the operand is an bitwise operator with a constant RHS, and the
6437 // shift is the only use, we can pull it out of the shift.
6438 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6439 bool isValid = true; // Valid only for And, Or, Xor
6440 bool highBitSet = false; // Transform if high bit of constant set?
6441
6442 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006443 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00006444 case Instruction::Add:
6445 isValid = isLeftShift;
6446 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00006447 case Instruction::Or:
6448 case Instruction::Xor:
6449 highBitSet = false;
6450 break;
6451 case Instruction::And:
6452 highBitSet = true;
6453 break;
Chris Lattner14553932006-01-06 07:12:35 +00006454 }
6455
6456 // If this is a signed shift right, and the high bit is modified
6457 // by the logical operation, do not perform the transformation.
6458 // The highBitSet boolean indicates the value of the high bit of
6459 // the constant which would cause it to be modified for this
6460 // operation.
6461 //
Chris Lattner3e009e82007-02-05 00:57:54 +00006462 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencer6274c722007-03-23 18:46:34 +00006463 APInt Val(Op0C->getValue());
6464 isValid = ((Val & APInt::getSignBit(TypeBits)) != 0) == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00006465 }
6466
6467 if (isValid) {
6468 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6469
6470 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006471 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00006472 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006473 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00006474
6475 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6476 NewRHS);
6477 }
6478 }
6479 }
6480 }
6481
Chris Lattnereb372a02006-01-06 07:52:12 +00006482 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00006483 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6484 if (ShiftOp && !ShiftOp->isShift())
6485 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00006486
Reid Spencere0fc4df2006-10-20 07:07:24 +00006487 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006488 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencer6274c722007-03-23 18:46:34 +00006489 // shift amount always <= 32 bits
Reid Spencere0fc4df2006-10-20 07:07:24 +00006490 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
6491 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00006492 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6493 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6494 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00006495
Chris Lattner3e009e82007-02-05 00:57:54 +00006496 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00006497 if (AmtSum > TypeBits)
6498 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00006499
6500 const IntegerType *Ty = cast<IntegerType>(I.getType());
6501
6502 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00006503 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00006504 return BinaryOperator::create(I.getOpcode(), X,
6505 ConstantInt::get(Ty, AmtSum));
6506 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6507 I.getOpcode() == Instruction::AShr) {
6508 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6509 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6510 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6511 I.getOpcode() == Instruction::LShr) {
6512 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6513 Instruction *Shift =
6514 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6515 InsertNewInstBefore(Shift, I);
6516
Reid Spencer6274c722007-03-23 18:46:34 +00006517 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
6518 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006519 }
6520
Chris Lattner3e009e82007-02-05 00:57:54 +00006521 // Okay, if we get here, one shift must be left, and the other shift must be
6522 // right. See if the amounts are equal.
6523 if (ShiftAmt1 == ShiftAmt2) {
6524 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6525 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer6274c722007-03-23 18:46:34 +00006526 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt1));
6527 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006528 }
6529 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6530 if (I.getOpcode() == Instruction::LShr) {
Reid Spencer6274c722007-03-23 18:46:34 +00006531 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt1));
6532 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006533 }
6534 // We can simplify ((X << C) >>s C) into a trunc + sext.
6535 // NOTE: we could do this for any C, but that would make 'unusual' integer
6536 // types. For now, just stick to ones well-supported by the code
6537 // generators.
6538 const Type *SExtType = 0;
6539 switch (Ty->getBitWidth() - ShiftAmt1) {
Reid Spencer6274c722007-03-23 18:46:34 +00006540 case 1 : SExtType = Type::Int1Ty; break;
6541 case 8 : SExtType = Type::Int8Ty; break;
6542 case 16 : SExtType = Type::Int16Ty; break;
6543 case 32 : SExtType = Type::Int32Ty; break;
6544 case 64 : SExtType = Type::Int64Ty; break;
6545 case 128: SExtType = IntegerType::get(128); break;
Chris Lattner3e009e82007-02-05 00:57:54 +00006546 default: break;
6547 }
6548 if (SExtType) {
6549 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6550 InsertNewInstBefore(NewTrunc, I);
6551 return new SExtInst(NewTrunc, Ty);
6552 }
6553 // Otherwise, we can't handle it yet.
6554 } else if (ShiftAmt1 < ShiftAmt2) {
6555 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00006556
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006557 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006558 if (I.getOpcode() == Instruction::Shl) {
6559 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6560 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006561 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00006562 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00006563 InsertNewInstBefore(Shift, I);
6564
Reid Spencer6274c722007-03-23 18:46:34 +00006565 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt2));
6566 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00006567 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006568
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006569 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006570 if (I.getOpcode() == Instruction::LShr) {
6571 assert(ShiftOp->getOpcode() == Instruction::Shl);
6572 Instruction *Shift =
6573 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6574 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00006575
Reid Spencer6274c722007-03-23 18:46:34 +00006576 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
6577 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00006578 }
Chris Lattner3e009e82007-02-05 00:57:54 +00006579
6580 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6581 } else {
6582 assert(ShiftAmt2 < ShiftAmt1);
6583 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
6584
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006585 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006586 if (I.getOpcode() == Instruction::Shl) {
6587 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6588 ShiftOp->getOpcode() == Instruction::AShr);
6589 Instruction *Shift =
6590 BinaryOperator::create(ShiftOp->getOpcode(), X,
6591 ConstantInt::get(Ty, ShiftDiff));
6592 InsertNewInstBefore(Shift, I);
6593
Reid Spencer6274c722007-03-23 18:46:34 +00006594 APInt Mask(APInt::getAllOnesValue(TypeBits).shl(ShiftAmt2));
6595 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006596 }
6597
Chris Lattner83ac5ae92007-02-05 05:57:49 +00006598 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00006599 if (I.getOpcode() == Instruction::LShr) {
6600 assert(ShiftOp->getOpcode() == Instruction::Shl);
6601 Instruction *Shift =
6602 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6603 InsertNewInstBefore(Shift, I);
6604
Reid Spencer6274c722007-03-23 18:46:34 +00006605 APInt Mask(APInt::getAllOnesValue(TypeBits).lshr(ShiftAmt2));
6606 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00006607 }
6608
6609 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00006610 }
Chris Lattnereb372a02006-01-06 07:52:12 +00006611 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00006612 return 0;
6613}
6614
Chris Lattner48a44f72002-05-02 17:06:02 +00006615
Chris Lattner8f663e82005-10-29 04:36:15 +00006616/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6617/// expression. If so, decompose it, returning some value X, such that Val is
6618/// X*Scale+Offset.
6619///
6620static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6621 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00006622 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00006623 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00006624 Offset = CI->getZExtValue();
6625 Scale = 1;
6626 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00006627 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6628 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006629 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00006630 if (I->getOpcode() == Instruction::Shl) {
6631 // This is a value scaled by '1 << the shift amt'.
6632 Scale = 1U << CUI->getZExtValue();
6633 Offset = 0;
6634 return I->getOperand(0);
6635 } else if (I->getOpcode() == Instruction::Mul) {
6636 // This value is scaled by 'CUI'.
6637 Scale = CUI->getZExtValue();
6638 Offset = 0;
6639 return I->getOperand(0);
6640 } else if (I->getOpcode() == Instruction::Add) {
6641 // We have X+C. Check to see if we really have (X*C2)+C1,
6642 // where C1 is divisible by C2.
6643 unsigned SubScale;
6644 Value *SubVal =
6645 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6646 Offset += CUI->getZExtValue();
6647 if (SubScale > 1 && (Offset % SubScale == 0)) {
6648 Scale = SubScale;
6649 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00006650 }
6651 }
6652 }
6653 }
6654 }
6655
6656 // Otherwise, we can't look past this.
6657 Scale = 1;
6658 Offset = 0;
6659 return Val;
6660}
6661
6662
Chris Lattner216be912005-10-24 06:03:58 +00006663/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6664/// try to eliminate the cast by moving the type information into the alloc.
6665Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
6666 AllocationInst &AI) {
6667 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00006668 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00006669
Chris Lattnerac87beb2005-10-24 06:22:12 +00006670 // Remove any uses of AI that are dead.
6671 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00006672
Chris Lattnerac87beb2005-10-24 06:22:12 +00006673 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6674 Instruction *User = cast<Instruction>(*UI++);
6675 if (isInstructionTriviallyDead(User)) {
6676 while (UI != E && *UI == User)
6677 ++UI; // If this instruction uses AI more than once, don't break UI.
6678
Chris Lattnerac87beb2005-10-24 06:22:12 +00006679 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00006680 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00006681 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00006682 }
6683 }
6684
Chris Lattner216be912005-10-24 06:03:58 +00006685 // Get the type really allocated and the type casted to.
6686 const Type *AllocElTy = AI.getAllocatedType();
6687 const Type *CastElTy = PTy->getElementType();
6688 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006689
Chris Lattner945e4372007-02-14 05:52:17 +00006690 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6691 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00006692 if (CastElTyAlign < AllocElTyAlign) return 0;
6693
Chris Lattner46705b22005-10-24 06:35:18 +00006694 // If the allocation has multiple uses, only promote it if we are strictly
6695 // increasing the alignment of the resultant allocation. If we keep it the
6696 // same, we open the door to infinite loops of various kinds.
6697 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6698
Chris Lattner216be912005-10-24 06:03:58 +00006699 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6700 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00006701 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00006702
Chris Lattner8270c332005-10-29 03:19:53 +00006703 // See if we can satisfy the modulus by pulling a scale out of the array
6704 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00006705 unsigned ArraySizeScale, ArrayOffset;
6706 Value *NumElements = // See if the array size is a decomposable linear expr.
6707 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6708
Chris Lattner8270c332005-10-29 03:19:53 +00006709 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6710 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00006711 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6712 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006713
Chris Lattner8270c332005-10-29 03:19:53 +00006714 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6715 Value *Amt = 0;
6716 if (Scale == 1) {
6717 Amt = NumElements;
6718 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006719 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006720 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6721 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006722 Amt = ConstantExpr::getMul(
6723 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6724 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006725 else if (Scale != 1) {
6726 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6727 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006728 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006729 }
6730
Chris Lattner8f663e82005-10-29 04:36:15 +00006731 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006732 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006733 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6734 Amt = InsertNewInstBefore(Tmp, AI);
6735 }
6736
Chris Lattner216be912005-10-24 06:03:58 +00006737 AllocationInst *New;
6738 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006739 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006740 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006741 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006742 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006743 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006744
6745 // If the allocation has multiple uses, insert a cast and change all things
6746 // that used it to use the new cast. This will also hack on CI, but it will
6747 // die soon.
6748 if (!AI.hasOneUse()) {
6749 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006750 // New is the allocation instruction, pointer typed. AI is the original
6751 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6752 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006753 InsertNewInstBefore(NewCast, AI);
6754 AI.replaceAllUsesWith(NewCast);
6755 }
Chris Lattner216be912005-10-24 06:03:58 +00006756 return ReplaceInstUsesWith(CI, New);
6757}
6758
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006759/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006760/// and return it as type Ty without inserting any new casts and without
6761/// changing the computed value. This is used by code that tries to decide
6762/// whether promoting or shrinking integer operations to wider or smaller types
6763/// will allow us to eliminate a truncate or extend.
6764///
6765/// This is a truncation operation if Ty is smaller than V->getType(), or an
6766/// extension operation if Ty is larger.
6767static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006768 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006769 // We can always evaluate constants in another type.
6770 if (isa<ConstantInt>(V))
6771 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006772
6773 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006774 if (!I) return false;
6775
6776 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006777
6778 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006779 case Instruction::Add:
6780 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006781 case Instruction::And:
6782 case Instruction::Or:
6783 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006784 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006785 // These operators can all arbitrarily be extended or truncated.
6786 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6787 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006788
Chris Lattner960acb02006-11-29 07:18:39 +00006789 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006790 if (!I->hasOneUse()) return false;
6791 // If we are truncating the result of this SHL, and if it's a shift of a
6792 // constant amount, we can always perform a SHL in a smaller type.
6793 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6794 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6795 CI->getZExtValue() < Ty->getBitWidth())
6796 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6797 }
6798 break;
6799 case Instruction::LShr:
6800 if (!I->hasOneUse()) return false;
6801 // If this is a truncate of a logical shr, we can truncate it to a smaller
6802 // lshr iff we know that the bits we would otherwise be shifting in are
6803 // already zeros.
6804 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006805 uint32_t BitWidth = OrigTy->getBitWidth();
Zhou Sheng755f04b2007-03-23 02:39:25 +00006806 if (Ty->getBitWidth() < BitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006807 MaskedValueIsZero(I->getOperand(0),
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00006808 APInt::getAllOnesValue(BitWidth) &
6809 APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6810 && CI->getZExtValue() < Ty->getBitWidth()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006811 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6812 }
6813 }
Chris Lattner960acb02006-11-29 07:18:39 +00006814 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006815 case Instruction::Trunc:
6816 case Instruction::ZExt:
6817 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006818 // If this is a cast from the destination type, we can trivially eliminate
6819 // it, and this will remove a cast overall.
6820 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006821 // If the first operand is itself a cast, and is eliminable, do not count
6822 // this as an eliminable cast. We would prefer to eliminate those two
6823 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006824 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006825 return true;
6826
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006827 ++NumCastsRemoved;
6828 return true;
6829 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006830 break;
6831 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006832 // TODO: Can handle more cases here.
6833 break;
6834 }
6835
6836 return false;
6837}
6838
6839/// EvaluateInDifferentType - Given an expression that
6840/// CanEvaluateInDifferentType returns true for, actually insert the code to
6841/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006842Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006843 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006844 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006845 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006846
6847 // Otherwise, it must be an instruction.
6848 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006849 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006850 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006851 case Instruction::Add:
6852 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006853 case Instruction::And:
6854 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006855 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006856 case Instruction::AShr:
6857 case Instruction::LShr:
6858 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006859 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006860 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6861 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6862 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006863 break;
6864 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006865 case Instruction::Trunc:
6866 case Instruction::ZExt:
6867 case Instruction::SExt:
6868 case Instruction::BitCast:
6869 // If the source type of the cast is the type we're trying for then we can
6870 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006871 if (I->getOperand(0)->getType() == Ty)
6872 return I->getOperand(0);
6873
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006874 // Some other kind of cast, which shouldn't happen, so just ..
6875 // FALL THROUGH
6876 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006877 // TODO: Can handle more cases here.
6878 assert(0 && "Unreachable!");
6879 break;
6880 }
6881
6882 return InsertNewInstBefore(Res, *I);
6883}
6884
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006885/// @brief Implement the transforms common to all CastInst visitors.
6886Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006887 Value *Src = CI.getOperand(0);
6888
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006889 // Casting undef to anything results in undef so might as just replace it and
6890 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006891 if (isa<UndefValue>(Src)) // cast undef -> undef
6892 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6893
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006894 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6895 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006896 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006897 if (Instruction::CastOps opc =
6898 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6899 // The first cast (CSrc) is eliminable so we need to fix up or replace
6900 // the second cast (CI). CSrc will then have a good chance of being dead.
6901 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006902 }
6903 }
Chris Lattner03841652004-05-25 04:29:21 +00006904
Chris Lattnerd0d51602003-06-21 23:12:02 +00006905 // If casting the result of a getelementptr instruction with no offset, turn
6906 // this into a cast of the original pointer!
6907 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006908 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006909 bool AllZeroOperands = true;
6910 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6911 if (!isa<Constant>(GEP->getOperand(i)) ||
6912 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6913 AllZeroOperands = false;
6914 break;
6915 }
6916 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006917 // Changing the cast operand is usually not a good idea but it is safe
6918 // here because the pointer operand is being replaced with another
6919 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006920 CI.setOperand(0, GEP->getOperand(0));
6921 return &CI;
6922 }
6923 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006924
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006925 // If we are casting a malloc or alloca to a pointer to a type of the same
6926 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006927 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006928 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6929 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006930
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006931 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006932 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6933 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6934 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006935
6936 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006937 if (isa<PHINode>(Src))
6938 if (Instruction *NV = FoldOpIntoPhi(CI))
6939 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006940
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006941 return 0;
6942}
6943
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006944/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6945/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006946/// cases.
6947/// @brief Implement the transforms common to CastInst with integer operands
6948Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6949 if (Instruction *Result = commonCastTransforms(CI))
6950 return Result;
6951
6952 Value *Src = CI.getOperand(0);
6953 const Type *SrcTy = Src->getType();
6954 const Type *DestTy = CI.getType();
6955 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6956 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6957
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006958 // See if we can simplify any instructions used by the LHS whose sole
6959 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006960 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6961 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006962 KnownZero, KnownOne))
6963 return &CI;
6964
6965 // If the source isn't an instruction or has more than one use then we
6966 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006967 Instruction *SrcI = dyn_cast<Instruction>(Src);
6968 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006969 return 0;
6970
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006971 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006972 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006973 if (!isa<BitCastInst>(CI) &&
6974 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6975 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006976 // If this cast is a truncate, evaluting in a different type always
6977 // eliminates the cast, so it is always a win. If this is a noop-cast
6978 // this just removes a noop cast which isn't pointful, but simplifies
6979 // the code. If this is a zero-extension, we need to do an AND to
6980 // maintain the clear top-part of the computation, so we require that
6981 // the input have eliminated at least one cast. If this is a sign
6982 // extension, we insert two new casts (to do the extension) so we
6983 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006984 bool DoXForm;
6985 switch (CI.getOpcode()) {
6986 default:
6987 // All the others use floating point so we shouldn't actually
6988 // get here because of the check above.
6989 assert(0 && "Unknown cast type");
6990 case Instruction::Trunc:
6991 DoXForm = true;
6992 break;
6993 case Instruction::ZExt:
6994 DoXForm = NumCastsRemoved >= 1;
6995 break;
6996 case Instruction::SExt:
6997 DoXForm = NumCastsRemoved >= 2;
6998 break;
6999 case Instruction::BitCast:
7000 DoXForm = false;
7001 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007002 }
7003
7004 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00007005 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7006 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007007 assert(Res->getType() == DestTy);
7008 switch (CI.getOpcode()) {
7009 default: assert(0 && "Unknown cast type!");
7010 case Instruction::Trunc:
7011 case Instruction::BitCast:
7012 // Just replace this cast with the result.
7013 return ReplaceInstUsesWith(CI, Res);
7014 case Instruction::ZExt: {
7015 // We need to emit an AND to clear the high bits.
7016 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencer4154e732007-03-22 20:56:53 +00007017 Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
7018 C = ConstantExpr::getZExt(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007019 return BinaryOperator::createAnd(Res, C);
7020 }
7021 case Instruction::SExt:
7022 // We need to emit a cast to truncate, then a cast to sext.
7023 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007024 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7025 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007026 }
7027 }
7028 }
7029
7030 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7031 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7032
7033 switch (SrcI->getOpcode()) {
7034 case Instruction::Add:
7035 case Instruction::Mul:
7036 case Instruction::And:
7037 case Instruction::Or:
7038 case Instruction::Xor:
7039 // If we are discarding information, or just changing the sign,
7040 // rewrite.
7041 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7042 // Don't insert two casts if they cannot be eliminated. We allow
7043 // two casts to be inserted if the sizes are the same. This could
7044 // only be converting signedness, which is a noop.
7045 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007046 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7047 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007048 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007049 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7050 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7051 return BinaryOperator::create(
7052 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007053 }
7054 }
7055
7056 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7057 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7058 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00007059 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007060 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007061 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007062 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7063 }
7064 break;
7065 case Instruction::SDiv:
7066 case Instruction::UDiv:
7067 case Instruction::SRem:
7068 case Instruction::URem:
7069 // If we are just changing the sign, rewrite.
7070 if (DestBitSize == SrcBitSize) {
7071 // Don't insert two casts if they cannot be eliminated. We allow
7072 // two casts to be inserted if the sizes are the same. This could
7073 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00007074 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7075 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007076 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7077 Op0, DestTy, SrcI);
7078 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7079 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007080 return BinaryOperator::create(
7081 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7082 }
7083 }
7084 break;
7085
7086 case Instruction::Shl:
7087 // Allow changing the sign of the source operand. Do not allow
7088 // changing the size of the shift, UNLESS the shift amount is a
7089 // constant. We must not change variable sized shifts to a smaller
7090 // size, because it is undefined to shift more bits out than exist
7091 // in the value.
7092 if (DestBitSize == SrcBitSize ||
7093 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007094 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7095 Instruction::BitCast : Instruction::Trunc);
7096 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00007097 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007098 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007099 }
7100 break;
7101 case Instruction::AShr:
7102 // If this is a signed shr, and if all bits shifted in are about to be
7103 // truncated off, turn it into an unsigned shr to allow greater
7104 // simplifications.
7105 if (DestBitSize < SrcBitSize &&
7106 isa<ConstantInt>(Op1)) {
7107 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
7108 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7109 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00007110 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007111 }
7112 }
7113 break;
7114
Reid Spencer266e42b2006-12-23 06:05:41 +00007115 case Instruction::ICmp:
7116 // If we are just checking for a icmp eq of a single bit and casting it
7117 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007118 // cast to integer to avoid the comparison.
7119 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer4154e732007-03-22 20:56:53 +00007120 APInt Op1CV(Op1C->getValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007121 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
7122 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
7123 // cast (X == 1) to int --> X iff X has only the low bit set.
7124 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
7125 // cast (X != 0) to int --> X iff X has only the low bit set.
7126 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
7127 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
7128 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00007129 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007130 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00007131 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7132 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7133 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007134 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00007135
7136 // This only works for EQ and NE
7137 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
7138 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
7139 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007140
Zhou Sheng0900993e2007-03-23 03:13:21 +00007141 APInt KnownZeroMask(KnownZero ^ TypeMask);
7142 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00007143 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00007144 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007145 // (X&4) == 2 --> false
7146 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00007147 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007148 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007149 return ReplaceInstUsesWith(CI, Res);
7150 }
7151
Zhou Sheng0900993e2007-03-23 03:13:21 +00007152 unsigned ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007153 Value *In = Op0;
7154 if (ShiftAmt) {
7155 // Perform a logical shr by shiftamt.
7156 // Insert the shift to put the result in the low bit.
7157 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007158 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00007159 ConstantInt::get(In->getType(), ShiftAmt),
7160 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007161 }
7162
Reid Spencer266e42b2006-12-23 06:05:41 +00007163 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007164 Constant *One = ConstantInt::get(In->getType(), 1);
7165 In = BinaryOperator::createXor(In, One, "tmp");
7166 InsertNewInstBefore(cast<Instruction>(In), CI);
7167 }
7168
7169 if (CI.getType() == In->getType())
7170 return ReplaceInstUsesWith(CI, In);
7171 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007172 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007173 }
7174 }
7175 }
7176 break;
7177 }
7178 return 0;
7179}
7180
7181Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007182 if (Instruction *Result = commonIntCastTransforms(CI))
7183 return Result;
7184
7185 Value *Src = CI.getOperand(0);
7186 const Type *Ty = CI.getType();
7187 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
Reid Spencer4154e732007-03-22 20:56:53 +00007188 unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00007189
7190 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7191 switch (SrcI->getOpcode()) {
7192 default: break;
7193 case Instruction::LShr:
7194 // We can shrink lshr to something smaller if we know the bits shifted in
7195 // are already zeros.
7196 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7197 unsigned ShAmt = ShAmtV->getZExtValue();
7198
7199 // Get a mask for the bits shifting in.
Reid Spencer4154e732007-03-22 20:56:53 +00007200 APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
7201 SrcBitWidth-ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00007202 Value* SrcIOp0 = SrcI->getOperand(0);
7203 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00007204 if (ShAmt >= DestBitWidth) // All zeros.
7205 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7206
7207 // Okay, we can shrink this. Truncate the input, then return a new
7208 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00007209 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7210 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7211 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00007212 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00007213 }
Chris Lattnerc209b582006-12-05 01:26:29 +00007214 } else { // This is a variable shr.
7215
7216 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7217 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7218 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00007219 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00007220 Value *One = ConstantInt::get(SrcI->getType(), 1);
7221
Reid Spencer2341c222007-02-02 02:16:23 +00007222 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00007223 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00007224 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00007225 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7226 SrcI->getOperand(0),
7227 "tmp"), CI);
7228 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00007229 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00007230 }
Chris Lattnerd747f012006-11-29 07:04:07 +00007231 }
7232 break;
7233 }
7234 }
7235
7236 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007237}
7238
7239Instruction *InstCombiner::visitZExt(CastInst &CI) {
7240 // If one of the common conversion will work ..
7241 if (Instruction *Result = commonIntCastTransforms(CI))
7242 return Result;
7243
7244 Value *Src = CI.getOperand(0);
7245
7246 // If this is a cast of a cast
7247 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007248 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7249 // types and if the sizes are just right we can convert this into a logical
7250 // 'and' which will be much cheaper than the pair of casts.
7251 if (isa<TruncInst>(CSrc)) {
7252 // Get the sizes of the types involved
7253 Value *A = CSrc->getOperand(0);
7254 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
7255 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7256 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7257 // If we're actually extending zero bits and the trunc is a no-op
7258 if (MidSize < DstSize && SrcSize == DstSize) {
7259 // Replace both of the casts with an And of the type mask.
Reid Spencer4154e732007-03-22 20:56:53 +00007260 APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
7261 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007262 Instruction *And =
7263 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7264 // Unfortunately, if the type changed, we need to cast it back.
7265 if (And->getType() != CI.getType()) {
7266 And->setName(CSrc->getName()+".mask");
7267 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007268 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007269 }
7270 return And;
7271 }
7272 }
7273 }
7274
7275 return 0;
7276}
7277
7278Instruction *InstCombiner::visitSExt(CastInst &CI) {
7279 return commonIntCastTransforms(CI);
7280}
7281
7282Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7283 return commonCastTransforms(CI);
7284}
7285
7286Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7287 return commonCastTransforms(CI);
7288}
7289
7290Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007291 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007292}
7293
7294Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007295 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007296}
7297
7298Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7299 return commonCastTransforms(CI);
7300}
7301
7302Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7303 return commonCastTransforms(CI);
7304}
7305
7306Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00007307 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007308}
7309
7310Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7311 return commonCastTransforms(CI);
7312}
7313
7314Instruction *InstCombiner::visitBitCast(CastInst &CI) {
7315
7316 // If the operands are integer typed then apply the integer transforms,
7317 // otherwise just apply the common ones.
7318 Value *Src = CI.getOperand(0);
7319 const Type *SrcTy = Src->getType();
7320 const Type *DestTy = CI.getType();
7321
Chris Lattner03c49532007-01-15 02:27:26 +00007322 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007323 if (Instruction *Result = commonIntCastTransforms(CI))
7324 return Result;
7325 } else {
7326 if (Instruction *Result = commonCastTransforms(CI))
7327 return Result;
7328 }
7329
7330
7331 // Get rid of casts from one type to the same type. These are useless and can
7332 // be replaced by the operand.
7333 if (DestTy == Src->getType())
7334 return ReplaceInstUsesWith(CI, Src);
7335
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007336 // If the source and destination are pointers, and this cast is equivalent to
7337 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
7338 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007339 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7340 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
7341 const Type *DstElTy = DstPTy->getElementType();
7342 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007343
Reid Spencerc635f472006-12-31 05:48:39 +00007344 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007345 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007346 while (SrcElTy != DstElTy &&
7347 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7348 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7349 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007350 ++NumZeros;
7351 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00007352
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007353 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007354 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00007355 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7356 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00007357 }
7358 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007359 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00007360
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007361 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7362 if (SVI->hasOneUse()) {
7363 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7364 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007365 if (isa<VectorType>(DestTy) &&
7366 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007367 SVI->getType()->getNumElements()) {
7368 CastInst *Tmp;
7369 // If either of the operands is a cast from CI.getType(), then
7370 // evaluating the shuffle in the casted destination's type will allow
7371 // us to eliminate at least one cast.
7372 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7373 Tmp->getOperand(0)->getType() == DestTy) ||
7374 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7375 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007376 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7377 SVI->getOperand(0), DestTy, &CI);
7378 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7379 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007380 // Return a new shuffle vector. Use the same element ID's, as we
7381 // know the vector types match #elts.
7382 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00007383 }
7384 }
7385 }
7386 }
Chris Lattner260ab202002-04-18 17:39:14 +00007387 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00007388}
7389
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007390/// GetSelectFoldableOperands - We want to turn code that looks like this:
7391/// %C = or %A, %B
7392/// %D = select %cond, %C, %A
7393/// into:
7394/// %C = select %cond, %B, 0
7395/// %D = or %A, %C
7396///
7397/// Assuming that the specified instruction is an operand to the select, return
7398/// a bitmask indicating which operands of this instruction are foldable if they
7399/// equal the other incoming value of the select.
7400///
7401static unsigned GetSelectFoldableOperands(Instruction *I) {
7402 switch (I->getOpcode()) {
7403 case Instruction::Add:
7404 case Instruction::Mul:
7405 case Instruction::And:
7406 case Instruction::Or:
7407 case Instruction::Xor:
7408 return 3; // Can fold through either operand.
7409 case Instruction::Sub: // Can only fold on the amount subtracted.
7410 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00007411 case Instruction::LShr:
7412 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00007413 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007414 default:
7415 return 0; // Cannot fold
7416 }
7417}
7418
7419/// GetSelectFoldableConstant - For the same transformation as the previous
7420/// function, return the identity constant that goes into the select.
7421static Constant *GetSelectFoldableConstant(Instruction *I) {
7422 switch (I->getOpcode()) {
7423 default: assert(0 && "This cannot happen!"); abort();
7424 case Instruction::Add:
7425 case Instruction::Sub:
7426 case Instruction::Or:
7427 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007428 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00007429 case Instruction::LShr:
7430 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00007431 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007432 case Instruction::And:
7433 return ConstantInt::getAllOnesValue(I->getType());
7434 case Instruction::Mul:
7435 return ConstantInt::get(I->getType(), 1);
7436 }
7437}
7438
Chris Lattner411336f2005-01-19 21:50:18 +00007439/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7440/// have the same opcode and only one use each. Try to simplify this.
7441Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7442 Instruction *FI) {
7443 if (TI->getNumOperands() == 1) {
7444 // If this is a non-volatile load or a cast from the same type,
7445 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007446 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00007447 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7448 return 0;
7449 } else {
7450 return 0; // unknown unary op.
7451 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007452
Chris Lattner411336f2005-01-19 21:50:18 +00007453 // Fold this by inserting a select from the input values.
7454 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7455 FI->getOperand(0), SI.getName()+".v");
7456 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007457 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7458 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00007459 }
7460
Reid Spencer2341c222007-02-02 02:16:23 +00007461 // Only handle binary operators here.
7462 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00007463 return 0;
7464
7465 // Figure out if the operations have any operands in common.
7466 Value *MatchOp, *OtherOpT, *OtherOpF;
7467 bool MatchIsOpZero;
7468 if (TI->getOperand(0) == FI->getOperand(0)) {
7469 MatchOp = TI->getOperand(0);
7470 OtherOpT = TI->getOperand(1);
7471 OtherOpF = FI->getOperand(1);
7472 MatchIsOpZero = true;
7473 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7474 MatchOp = TI->getOperand(1);
7475 OtherOpT = TI->getOperand(0);
7476 OtherOpF = FI->getOperand(0);
7477 MatchIsOpZero = false;
7478 } else if (!TI->isCommutative()) {
7479 return 0;
7480 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7481 MatchOp = TI->getOperand(0);
7482 OtherOpT = TI->getOperand(1);
7483 OtherOpF = FI->getOperand(0);
7484 MatchIsOpZero = true;
7485 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7486 MatchOp = TI->getOperand(1);
7487 OtherOpT = TI->getOperand(0);
7488 OtherOpF = FI->getOperand(1);
7489 MatchIsOpZero = true;
7490 } else {
7491 return 0;
7492 }
7493
7494 // If we reach here, they do have operations in common.
7495 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7496 OtherOpF, SI.getName()+".v");
7497 InsertNewInstBefore(NewSI, SI);
7498
7499 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7500 if (MatchIsOpZero)
7501 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7502 else
7503 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00007504 }
Reid Spencer2f34b982007-02-02 14:41:37 +00007505 assert(0 && "Shouldn't get here");
7506 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00007507}
7508
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007509Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00007510 Value *CondVal = SI.getCondition();
7511 Value *TrueVal = SI.getTrueValue();
7512 Value *FalseVal = SI.getFalseValue();
7513
7514 // select true, X, Y -> X
7515 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00007516 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00007517 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00007518
7519 // select C, X, X -> X
7520 if (TrueVal == FalseVal)
7521 return ReplaceInstUsesWith(SI, TrueVal);
7522
Chris Lattner81a7a232004-10-16 18:11:37 +00007523 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7524 return ReplaceInstUsesWith(SI, FalseVal);
7525 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7526 return ReplaceInstUsesWith(SI, TrueVal);
7527 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7528 if (isa<Constant>(TrueVal))
7529 return ReplaceInstUsesWith(SI, TrueVal);
7530 else
7531 return ReplaceInstUsesWith(SI, FalseVal);
7532 }
7533
Reid Spencer542964f2007-01-11 18:21:29 +00007534 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007535 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007536 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007537 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007538 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007539 } else {
7540 // Change: A = select B, false, C --> A = and !B, C
7541 Value *NotCond =
7542 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7543 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007544 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007545 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007546 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007547 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00007548 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007549 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007550 } else {
7551 // Change: A = select B, C, true --> A = or !B, C
7552 Value *NotCond =
7553 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7554 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007555 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00007556 }
7557 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00007558 }
Chris Lattner1c631e82004-04-08 04:43:23 +00007559
Chris Lattner183b3362004-04-09 19:05:30 +00007560 // Selecting between two integer constants?
7561 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7562 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7563 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00007564 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007565 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00007566 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00007567 // select C, 0, 1 -> cast !C to int
7568 Value *NotCond =
7569 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00007570 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007571 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00007572 }
Chris Lattner35167c32004-06-09 07:59:58 +00007573
Reid Spencer266e42b2006-12-23 06:05:41 +00007574 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00007575
Reid Spencer266e42b2006-12-23 06:05:41 +00007576 // (x <s 0) ? -1 : 0 -> ashr x, 31
7577 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00007578 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
7579 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7580 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00007581 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00007582 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007583 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007584 else {
7585 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00007586 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00007587 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00007588 }
7589
7590 if (CanXForm) {
7591 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007592 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00007593 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00007594 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00007595 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7596 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7597 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00007598 InsertNewInstBefore(SRA, SI);
7599
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007600 // Finally, convert to the type of the select RHS. We figure out
7601 // if this requires a SExt, Trunc or BitCast based on the sizes.
7602 Instruction::CastOps opc = Instruction::BitCast;
7603 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
7604 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
7605 if (SRASize < SISize)
7606 opc = Instruction::SExt;
7607 else if (SRASize > SISize)
7608 opc = Instruction::Trunc;
7609 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00007610 }
7611 }
7612
7613
7614 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00007615 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00007616 // non-constant value, eliminate this whole mess. This corresponds to
7617 // cases like this: ((X & 27) ? 27 : 0)
7618 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00007619 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007620 cast<Constant>(IC->getOperand(1))->isNullValue())
7621 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7622 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007623 isa<ConstantInt>(ICA->getOperand(1)) &&
7624 (ICA->getOperand(1) == TrueValC ||
7625 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00007626 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7627 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00007628 // know whether we have a icmp_ne or icmp_eq and whether the
7629 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00007630 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007631 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00007632 Value *V = ICA;
7633 if (ShouldNotVal)
7634 V = InsertNewInstBefore(BinaryOperator::create(
7635 Instruction::Xor, V, ICA->getOperand(1)), SI);
7636 return ReplaceInstUsesWith(SI, V);
7637 }
Chris Lattner380c7e92006-09-20 04:44:59 +00007638 }
Chris Lattner533bc492004-03-30 19:37:13 +00007639 }
Chris Lattner623fba12004-04-10 22:21:27 +00007640
7641 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00007642 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7643 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00007644 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007645 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00007646 return ReplaceInstUsesWith(SI, FalseVal);
7647 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007648 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00007649 return ReplaceInstUsesWith(SI, TrueVal);
7650 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7651
Reid Spencer266e42b2006-12-23 06:05:41 +00007652 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00007653 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00007654 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00007655 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007656 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00007657 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7658 return ReplaceInstUsesWith(SI, TrueVal);
7659 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7660 }
7661 }
7662
7663 // See if we are selecting two values based on a comparison of the two values.
7664 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7665 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7666 // Transform (X == Y) ? X : Y -> Y
7667 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7668 return ReplaceInstUsesWith(SI, FalseVal);
7669 // Transform (X != Y) ? X : Y -> X
7670 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7671 return ReplaceInstUsesWith(SI, TrueVal);
7672 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7673
7674 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7675 // Transform (X == Y) ? Y : X -> X
7676 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7677 return ReplaceInstUsesWith(SI, FalseVal);
7678 // Transform (X != Y) ? Y : X -> Y
7679 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00007680 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00007681 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7682 }
7683 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007684
Chris Lattnera04c9042005-01-13 22:52:24 +00007685 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7686 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7687 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00007688 Instruction *AddOp = 0, *SubOp = 0;
7689
Chris Lattner411336f2005-01-19 21:50:18 +00007690 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7691 if (TI->getOpcode() == FI->getOpcode())
7692 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7693 return IV;
7694
7695 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7696 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00007697 if (TI->getOpcode() == Instruction::Sub &&
7698 FI->getOpcode() == Instruction::Add) {
7699 AddOp = FI; SubOp = TI;
7700 } else if (FI->getOpcode() == Instruction::Sub &&
7701 TI->getOpcode() == Instruction::Add) {
7702 AddOp = TI; SubOp = FI;
7703 }
7704
7705 if (AddOp) {
7706 Value *OtherAddOp = 0;
7707 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7708 OtherAddOp = AddOp->getOperand(1);
7709 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7710 OtherAddOp = AddOp->getOperand(0);
7711 }
7712
7713 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00007714 // So at this point we know we have (Y -> OtherAddOp):
7715 // select C, (add X, Y), (sub X, Z)
7716 Value *NegVal; // Compute -Z
7717 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7718 NegVal = ConstantExpr::getNeg(C);
7719 } else {
7720 NegVal = InsertNewInstBefore(
7721 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007722 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007723
7724 Value *NewTrueOp = OtherAddOp;
7725 Value *NewFalseOp = NegVal;
7726 if (AddOp != TI)
7727 std::swap(NewTrueOp, NewFalseOp);
7728 Instruction *NewSel =
7729 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7730
7731 NewSel = InsertNewInstBefore(NewSel, SI);
7732 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007733 }
7734 }
7735 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007736
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007737 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007738 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007739 // See the comment above GetSelectFoldableOperands for a description of the
7740 // transformation we are doing here.
7741 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7742 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7743 !isa<Constant>(FalseVal))
7744 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7745 unsigned OpToFold = 0;
7746 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7747 OpToFold = 1;
7748 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7749 OpToFold = 2;
7750 }
7751
7752 if (OpToFold) {
7753 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007754 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007755 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007756 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007757 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7759 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007760 else {
7761 assert(0 && "Unknown instruction!!");
7762 }
7763 }
7764 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007765
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007766 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7767 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7768 !isa<Constant>(TrueVal))
7769 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7770 unsigned OpToFold = 0;
7771 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7772 OpToFold = 1;
7773 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7774 OpToFold = 2;
7775 }
7776
7777 if (OpToFold) {
7778 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007779 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007780 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007781 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007782 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7784 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007785 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007786 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007787 }
7788 }
7789 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007790
7791 if (BinaryOperator::isNot(CondVal)) {
7792 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7793 SI.setOperand(1, FalseVal);
7794 SI.setOperand(2, TrueVal);
7795 return &SI;
7796 }
7797
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007798 return 0;
7799}
7800
Chris Lattner82f2ef22006-03-06 20:18:44 +00007801/// GetKnownAlignment - If the specified pointer has an alignment that we can
7802/// determine, return it, otherwise return 0.
7803static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7804 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7805 unsigned Align = GV->getAlignment();
7806 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007807 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007808 return Align;
7809 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7810 unsigned Align = AI->getAlignment();
7811 if (Align == 0 && TD) {
7812 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007813 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007814 else if (isa<MallocInst>(AI)) {
7815 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007816 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007817 Align =
7818 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007819 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007820 Align =
7821 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007822 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007823 }
7824 }
7825 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007826 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007827 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007828 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007829 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007830 if (isa<PointerType>(CI->getOperand(0)->getType()))
7831 return GetKnownAlignment(CI->getOperand(0), TD);
7832 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007833 } else if (isa<GetElementPtrInst>(V) ||
7834 (isa<ConstantExpr>(V) &&
7835 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7836 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007837 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7838 if (BaseAlignment == 0) return 0;
7839
7840 // If all indexes are zero, it is just the alignment of the base pointer.
7841 bool AllZeroOperands = true;
7842 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7843 if (!isa<Constant>(GEPI->getOperand(i)) ||
7844 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7845 AllZeroOperands = false;
7846 break;
7847 }
7848 if (AllZeroOperands)
7849 return BaseAlignment;
7850
7851 // Otherwise, if the base alignment is >= the alignment we expect for the
7852 // base pointer type, then we know that the resultant pointer is aligned at
7853 // least as much as its type requires.
7854 if (!TD) return 0;
7855
7856 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007857 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007858 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007859 <= BaseAlignment) {
7860 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007861 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007862 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007863 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007864 return 0;
7865 }
7866 return 0;
7867}
7868
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007869
Chris Lattnerc66b2232006-01-13 20:11:04 +00007870/// visitCallInst - CallInst simplification. This mostly only handles folding
7871/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7872/// the heavy lifting.
7873///
Chris Lattner970c33a2003-06-19 17:00:31 +00007874Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007875 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7876 if (!II) return visitCallSite(&CI);
7877
Chris Lattner51ea1272004-02-28 05:22:00 +00007878 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7879 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007880 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007881 bool Changed = false;
7882
7883 // memmove/cpy/set of zero bytes is a noop.
7884 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7885 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7886
Chris Lattner00648e12004-10-12 04:52:52 +00007887 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007888 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007889 // Replace the instruction with just byte operations. We would
7890 // transform other cases to loads/stores, but we don't know if
7891 // alignment is sufficient.
7892 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007893 }
7894
Chris Lattner00648e12004-10-12 04:52:52 +00007895 // If we have a memmove and the source operation is a constant global,
7896 // then the source and dest pointers can't alias, so we can change this
7897 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007898 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007899 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7900 if (GVSrc->isConstant()) {
7901 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007902 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007903 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007904 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007905 Name = "llvm.memcpy.i32";
7906 else
7907 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007908 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007909 CI.getCalledFunction()->getFunctionType());
7910 CI.setOperand(0, MemCpy);
7911 Changed = true;
7912 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007913 }
Chris Lattner00648e12004-10-12 04:52:52 +00007914
Chris Lattner82f2ef22006-03-06 20:18:44 +00007915 // If we can determine a pointer alignment that is bigger than currently
7916 // set, update the alignment.
7917 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7918 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7919 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7920 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007921 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007922 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007923 Changed = true;
7924 }
7925 } else if (isa<MemSetInst>(MI)) {
7926 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007927 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007928 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007929 Changed = true;
7930 }
7931 }
7932
Chris Lattnerc66b2232006-01-13 20:11:04 +00007933 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007934 } else {
7935 switch (II->getIntrinsicID()) {
7936 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007937 case Intrinsic::ppc_altivec_lvx:
7938 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007939 case Intrinsic::x86_sse_loadu_ps:
7940 case Intrinsic::x86_sse2_loadu_pd:
7941 case Intrinsic::x86_sse2_loadu_dq:
7942 // Turn PPC lvx -> load if the pointer is known aligned.
7943 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007944 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007945 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007946 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007947 return new LoadInst(Ptr);
7948 }
7949 break;
7950 case Intrinsic::ppc_altivec_stvx:
7951 case Intrinsic::ppc_altivec_stvxl:
7952 // Turn stvx -> store if the pointer is known aligned.
7953 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007954 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007955 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7956 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007957 return new StoreInst(II->getOperand(1), Ptr);
7958 }
7959 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007960 case Intrinsic::x86_sse_storeu_ps:
7961 case Intrinsic::x86_sse2_storeu_pd:
7962 case Intrinsic::x86_sse2_storeu_dq:
7963 case Intrinsic::x86_sse2_storel_dq:
7964 // Turn X86 storeu -> store if the pointer is known aligned.
7965 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7966 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007967 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7968 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007969 return new StoreInst(II->getOperand(2), Ptr);
7970 }
7971 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007972
7973 case Intrinsic::x86_sse_cvttss2si: {
7974 // These intrinsics only demands the 0th element of its input vector. If
7975 // we can simplify the input based on that, do so now.
7976 uint64_t UndefElts;
7977 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7978 UndefElts)) {
7979 II->setOperand(1, V);
7980 return II;
7981 }
7982 break;
7983 }
7984
Chris Lattnere79d2492006-04-06 19:19:17 +00007985 case Intrinsic::ppc_altivec_vperm:
7986 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007987 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007988 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7989
7990 // Check that all of the elements are integer constants or undefs.
7991 bool AllEltsOk = true;
7992 for (unsigned i = 0; i != 16; ++i) {
7993 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7994 !isa<UndefValue>(Mask->getOperand(i))) {
7995 AllEltsOk = false;
7996 break;
7997 }
7998 }
7999
8000 if (AllEltsOk) {
8001 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008002 Value *Op0 = InsertCastBefore(Instruction::BitCast,
8003 II->getOperand(1), Mask->getType(), CI);
8004 Value *Op1 = InsertCastBefore(Instruction::BitCast,
8005 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00008006 Value *Result = UndefValue::get(Op0->getType());
8007
8008 // Only extract each element once.
8009 Value *ExtractedElts[32];
8010 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8011
8012 for (unsigned i = 0; i != 16; ++i) {
8013 if (isa<UndefValue>(Mask->getOperand(i)))
8014 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008015 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00008016 Idx &= 31; // Match the hardware behavior.
8017
8018 if (ExtractedElts[Idx] == 0) {
8019 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00008020 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00008021 InsertNewInstBefore(Elt, CI);
8022 ExtractedElts[Idx] = Elt;
8023 }
8024
8025 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00008026 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00008027 InsertNewInstBefore(cast<Instruction>(Result), CI);
8028 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008029 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00008030 }
8031 }
8032 break;
8033
Chris Lattner503221f2006-01-13 21:28:09 +00008034 case Intrinsic::stackrestore: {
8035 // If the save is right next to the restore, remove the restore. This can
8036 // happen when variable allocas are DCE'd.
8037 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8038 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8039 BasicBlock::iterator BI = SS;
8040 if (&*++BI == II)
8041 return EraseInstFromFunction(CI);
8042 }
8043 }
8044
8045 // If the stack restore is in a return/unwind block and if there are no
8046 // allocas or calls between the restore and the return, nuke the restore.
8047 TerminatorInst *TI = II->getParent()->getTerminator();
8048 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8049 BasicBlock::iterator BI = II;
8050 bool CannotRemove = false;
8051 for (++BI; &*BI != TI; ++BI) {
8052 if (isa<AllocaInst>(BI) ||
8053 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8054 CannotRemove = true;
8055 break;
8056 }
8057 }
8058 if (!CannotRemove)
8059 return EraseInstFromFunction(CI);
8060 }
8061 break;
8062 }
8063 }
Chris Lattner00648e12004-10-12 04:52:52 +00008064 }
8065
Chris Lattnerc66b2232006-01-13 20:11:04 +00008066 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008067}
8068
8069// InvokeInst simplification
8070//
8071Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00008072 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00008073}
8074
Chris Lattneraec3d942003-10-07 22:32:43 +00008075// visitCallSite - Improvements for call and invoke instructions.
8076//
8077Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008078 bool Changed = false;
8079
8080 // If the callee is a constexpr cast of a function, attempt to move the cast
8081 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00008082 if (transformConstExprCastCall(CS)) return 0;
8083
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008084 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00008085
Chris Lattner61d9d812005-05-13 07:09:09 +00008086 if (Function *CalleeF = dyn_cast<Function>(Callee))
8087 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8088 Instruction *OldCall = CS.getInstruction();
8089 // If the call and callee calling conventions don't match, this call must
8090 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008091 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008092 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00008093 if (!OldCall->use_empty())
8094 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8095 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8096 return EraseInstFromFunction(*OldCall);
8097 return 0;
8098 }
8099
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008100 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8101 // This instruction is not reachable, just remove it. We insert a store to
8102 // undef so that we know that this code is not reachable, despite the fact
8103 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008104 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008105 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008106 CS.getInstruction());
8107
8108 if (!CS.getInstruction()->use_empty())
8109 CS.getInstruction()->
8110 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8111
8112 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8113 // Don't break the CFG, insert a dummy cond branch.
8114 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00008115 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00008116 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008117 return EraseInstFromFunction(*CS.getInstruction());
8118 }
Chris Lattner81a7a232004-10-16 18:11:37 +00008119
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008120 const PointerType *PTy = cast<PointerType>(Callee->getType());
8121 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8122 if (FTy->isVarArg()) {
8123 // See if we can optimize any arguments passed through the varargs area of
8124 // the call.
8125 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8126 E = CS.arg_end(); I != E; ++I)
8127 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8128 // If this cast does not effect the value passed through the varargs
8129 // area, we can eliminate the use of the cast.
8130 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008131 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008132 *I = Op;
8133 Changed = true;
8134 }
8135 }
8136 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008137
Chris Lattner75b4d1d2003-10-07 22:54:13 +00008138 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00008139}
8140
Chris Lattner970c33a2003-06-19 17:00:31 +00008141// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8142// attempt to move the cast to the arguments of the call/invoke.
8143//
8144bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8145 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8146 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008147 if (CE->getOpcode() != Instruction::BitCast ||
8148 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00008149 return false;
Reid Spencer87436872004-07-18 00:38:32 +00008150 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00008151 Instruction *Caller = CS.getInstruction();
8152
8153 // Okay, this is a cast from a function to a different type. Unless doing so
8154 // would cause a type conversion of one of our arguments, change this call to
8155 // be a direct call with arguments casted to the appropriate types.
8156 //
8157 const FunctionType *FT = Callee->getFunctionType();
8158 const Type *OldRetTy = Caller->getType();
8159
Chris Lattner1f7942f2004-01-14 06:06:08 +00008160 // Check to see if we are changing the return type...
8161 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00008162 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00008163 // Conversion is ok if changing from pointer to int of same size.
8164 !(isa<PointerType>(FT->getReturnType()) &&
8165 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00008166 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00008167
8168 // If the callsite is an invoke instruction, and the return value is used by
8169 // a PHI node in a successor, we cannot change the return type of the call
8170 // because there is no place to put the cast instruction (without breaking
8171 // the critical edge). Bail out in this case.
8172 if (!Caller->use_empty())
8173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8174 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8175 UI != E; ++UI)
8176 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8177 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008178 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00008179 return false;
8180 }
Chris Lattner970c33a2003-06-19 17:00:31 +00008181
8182 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8183 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008184
Chris Lattner970c33a2003-06-19 17:00:31 +00008185 CallSite::arg_iterator AI = CS.arg_begin();
8186 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8187 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008188 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008189 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00008190 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00008191 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00008192 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00008193 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00008194 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8195 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Reid Spencer6274c722007-03-23 18:46:34 +00008196 && c->getValue().isPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00008197 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00008198 }
8199
8200 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00008201 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00008202 return false; // Do not delete arguments unless we have a function body...
8203
8204 // Okay, we decided that this is a safe thing to do: go ahead and start
8205 // inserting cast instructions as necessary...
8206 std::vector<Value*> Args;
8207 Args.reserve(NumActualArgs);
8208
8209 AI = CS.arg_begin();
8210 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8211 const Type *ParamTy = FT->getParamType(i);
8212 if ((*AI)->getType() == ParamTy) {
8213 Args.push_back(*AI);
8214 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00008215 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00008216 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008217 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008218 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00008219 }
8220 }
8221
8222 // If the function takes more arguments than the call was taking, add them
8223 // now...
8224 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8225 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8226
8227 // If we are removing arguments to the function, emit an obnoxious warning...
8228 if (FT->getNumParams() < NumActualArgs)
8229 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00008230 cerr << "WARNING: While resolving call to function '"
8231 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00008232 } else {
8233 // Add all of the arguments in their promoted form to the arg list...
8234 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8235 const Type *PTy = getPromotedType((*AI)->getType());
8236 if (PTy != (*AI)->getType()) {
8237 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00008238 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8239 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008240 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00008241 InsertNewInstBefore(Cast, *Caller);
8242 Args.push_back(Cast);
8243 } else {
8244 Args.push_back(*AI);
8245 }
8246 }
8247 }
8248
8249 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00008250 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00008251
8252 Instruction *NC;
8253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00008254 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008255 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00008256 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008257 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00008258 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00008259 if (cast<CallInst>(Caller)->isTailCall())
8260 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00008261 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00008262 }
8263
Chris Lattner6e0123b2007-02-11 01:23:03 +00008264 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00008265 Value *NV = NC;
8266 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8267 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00008268 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00008269 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8270 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00008271 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00008272
8273 // If this is an invoke instruction, we should insert it after the first
8274 // non-phi, instruction in the normal successor block.
8275 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8276 BasicBlock::iterator I = II->getNormalDest()->begin();
8277 while (isa<PHINode>(I)) ++I;
8278 InsertNewInstBefore(NC, *I);
8279 } else {
8280 // Otherwise, it's a call, just insert cast right after the call instr
8281 InsertNewInstBefore(NC, *Caller);
8282 }
Chris Lattner51ea1272004-02-28 05:22:00 +00008283 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008284 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00008285 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00008286 }
8287 }
8288
8289 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8290 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00008291 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008292 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00008293 return true;
8294}
8295
Chris Lattnercadac0c2006-11-01 04:51:18 +00008296/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8297/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8298/// and a single binop.
8299Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8300 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00008301 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8302 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008303 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00008304 Value *LHSVal = FirstInst->getOperand(0);
8305 Value *RHSVal = FirstInst->getOperand(1);
8306
8307 const Type *LHSType = LHSVal->getType();
8308 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00008309
8310 // Scan to see if all operands are the same opcode, all have one use, and all
8311 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008312 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00008313 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00008314 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00008315 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00008316 // types or GEP's with different index types.
8317 I->getOperand(0)->getType() != LHSType ||
8318 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00008319 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00008320
8321 // If they are CmpInst instructions, check their predicates
8322 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8323 if (cast<CmpInst>(I)->getPredicate() !=
8324 cast<CmpInst>(FirstInst)->getPredicate())
8325 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008326
8327 // Keep track of which operand needs a phi node.
8328 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8329 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00008330 }
8331
Chris Lattner4f218d52006-11-08 19:42:28 +00008332 // Otherwise, this is safe to transform, determine if it is profitable.
8333
8334 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8335 // Indexes are often folded into load/store instructions, so we don't want to
8336 // hide them behind a phi.
8337 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8338 return 0;
8339
Chris Lattnercadac0c2006-11-01 04:51:18 +00008340 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00008341 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00008342 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00008343 if (LHSVal == 0) {
8344 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8345 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8346 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008347 InsertNewInstBefore(NewLHS, PN);
8348 LHSVal = NewLHS;
8349 }
Chris Lattnercd62f112006-11-08 19:29:23 +00008350
8351 if (RHSVal == 0) {
8352 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8353 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8354 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00008355 InsertNewInstBefore(NewRHS, PN);
8356 RHSVal = NewRHS;
8357 }
8358
Chris Lattnercd62f112006-11-08 19:29:23 +00008359 // Add all operands to the new PHIs.
8360 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8361 if (NewLHS) {
8362 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8363 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8364 }
8365 if (NewRHS) {
8366 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8367 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8368 }
8369 }
8370
Chris Lattnercadac0c2006-11-01 04:51:18 +00008371 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00008372 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00008373 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8374 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8375 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00008376 else {
8377 assert(isa<GetElementPtrInst>(FirstInst));
8378 return new GetElementPtrInst(LHSVal, RHSVal);
8379 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00008380}
8381
Chris Lattner14f82c72006-11-01 07:13:54 +00008382/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8383/// of the block that defines it. This means that it must be obvious the value
8384/// of the load is not changed from the point of the load to the end of the
8385/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00008386///
8387/// Finally, it is safe, but not profitable, to sink a load targetting a
8388/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8389/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00008390static bool isSafeToSinkLoad(LoadInst *L) {
8391 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8392
8393 for (++BBI; BBI != E; ++BBI)
8394 if (BBI->mayWriteToMemory())
8395 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00008396
8397 // Check for non-address taken alloca. If not address-taken already, it isn't
8398 // profitable to do this xform.
8399 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8400 bool isAddressTaken = false;
8401 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8402 UI != E; ++UI) {
8403 if (isa<LoadInst>(UI)) continue;
8404 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8405 // If storing TO the alloca, then the address isn't taken.
8406 if (SI->getOperand(1) == AI) continue;
8407 }
8408 isAddressTaken = true;
8409 break;
8410 }
8411
8412 if (!isAddressTaken)
8413 return false;
8414 }
8415
Chris Lattner14f82c72006-11-01 07:13:54 +00008416 return true;
8417}
8418
Chris Lattner970c33a2003-06-19 17:00:31 +00008419
Chris Lattner7515cab2004-11-14 19:13:23 +00008420// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8421// operator and they all are only used by the PHI, PHI together their
8422// inputs, and do the operation once, to the result of the PHI.
8423Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8424 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8425
8426 // Scan the instruction, looking for input operations that can be folded away.
8427 // If all input operands to the phi are the same instruction (e.g. a cast from
8428 // the same type or "+42") we can pull the operation through the PHI, reducing
8429 // code size and simplifying code.
8430 Constant *ConstantOp = 0;
8431 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00008432 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00008433 if (isa<CastInst>(FirstInst)) {
8434 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00008435 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008436 // Can fold binop, compare or shift here if the RHS is a constant,
8437 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00008438 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00008439 if (ConstantOp == 0)
8440 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00008441 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8442 isVolatile = LI->isVolatile();
8443 // We can't sink the load if the loaded value could be modified between the
8444 // load and the PHI.
8445 if (LI->getParent() != PN.getIncomingBlock(0) ||
8446 !isSafeToSinkLoad(LI))
8447 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00008448 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00008449 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00008450 return FoldPHIArgBinOpIntoPHI(PN);
8451 // Can't handle general GEPs yet.
8452 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008453 } else {
8454 return 0; // Cannot fold this operation.
8455 }
8456
8457 // Check to see if all arguments are the same operation.
8458 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8459 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8460 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00008461 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00008462 return 0;
8463 if (CastSrcTy) {
8464 if (I->getOperand(0)->getType() != CastSrcTy)
8465 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00008466 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008467 // We can't sink the load if the loaded value could be modified between
8468 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00008469 if (LI->isVolatile() != isVolatile ||
8470 LI->getParent() != PN.getIncomingBlock(i) ||
8471 !isSafeToSinkLoad(LI))
8472 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008473 } else if (I->getOperand(1) != ConstantOp) {
8474 return 0;
8475 }
8476 }
8477
8478 // Okay, they are all the same operation. Create a new PHI node of the
8479 // correct type, and PHI together all of the LHS's of the instructions.
8480 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8481 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00008482 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00008483
8484 Value *InVal = FirstInst->getOperand(0);
8485 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00008486
8487 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00008488 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8489 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8490 if (NewInVal != InVal)
8491 InVal = 0;
8492 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8493 }
8494
8495 Value *PhiVal;
8496 if (InVal) {
8497 // The new PHI unions all of the same values together. This is really
8498 // common, so we handle it intelligently here for compile-time speed.
8499 PhiVal = InVal;
8500 delete NewPN;
8501 } else {
8502 InsertNewInstBefore(NewPN, PN);
8503 PhiVal = NewPN;
8504 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008505
Chris Lattner7515cab2004-11-14 19:13:23 +00008506 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008507 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8508 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00008509 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00008510 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00008511 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00008512 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00008513 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8514 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8515 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00008516 else
Reid Spencer2341c222007-02-02 02:16:23 +00008517 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00008518 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00008519}
Chris Lattner48a44f72002-05-02 17:06:02 +00008520
Chris Lattner71536432005-01-17 05:10:15 +00008521/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8522/// that is dead.
8523static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
8524 if (PN->use_empty()) return true;
8525 if (!PN->hasOneUse()) return false;
8526
8527 // Remember this node, and if we find the cycle, return.
8528 if (!PotentiallyDeadPHIs.insert(PN).second)
8529 return true;
8530
8531 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8532 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008533
Chris Lattner71536432005-01-17 05:10:15 +00008534 return false;
8535}
8536
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008537// PHINode simplification
8538//
Chris Lattner113f4f42002-06-25 16:13:24 +00008539Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00008540 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00008541 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00008542
Owen Andersonae8aa642006-07-10 22:03:18 +00008543 if (Value *V = PN.hasConstantValue())
8544 return ReplaceInstUsesWith(PN, V);
8545
Owen Andersonae8aa642006-07-10 22:03:18 +00008546 // If all PHI operands are the same operation, pull them through the PHI,
8547 // reducing code size.
8548 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8549 PN.getIncomingValue(0)->hasOneUse())
8550 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8551 return Result;
8552
8553 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8554 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8555 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008556 if (PN.hasOneUse()) {
8557 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8558 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00008559 std::set<PHINode*> PotentiallyDeadPHIs;
8560 PotentiallyDeadPHIs.insert(&PN);
8561 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8562 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8563 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00008564
8565 // If this phi has a single use, and if that use just computes a value for
8566 // the next iteration of a loop, delete the phi. This occurs with unused
8567 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8568 // common case here is good because the only other things that catch this
8569 // are induction variable analysis (sometimes) and ADCE, which is only run
8570 // late.
8571 if (PHIUser->hasOneUse() &&
8572 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8573 PHIUser->use_back() == &PN) {
8574 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8575 }
8576 }
Owen Andersonae8aa642006-07-10 22:03:18 +00008577
Chris Lattner91daeb52003-12-19 05:58:40 +00008578 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00008579}
8580
Reid Spencer13bc5d72006-12-12 09:18:51 +00008581static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8582 Instruction *InsertPoint,
8583 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00008584 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8585 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008586 // We must cast correctly to the pointer type. Ensure that we
8587 // sign extend the integer value if it is smaller as this is
8588 // used for address computation.
8589 Instruction::CastOps opcode =
8590 (VTySize < PtrSize ? Instruction::SExt :
8591 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8592 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00008593}
8594
Chris Lattner48a44f72002-05-02 17:06:02 +00008595
Chris Lattner113f4f42002-06-25 16:13:24 +00008596Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008597 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00008598 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00008599 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008600 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00008601 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008602
Chris Lattner81a7a232004-10-16 18:11:37 +00008603 if (isa<UndefValue>(GEP.getOperand(0)))
8604 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8605
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008606 bool HasZeroPointerIndex = false;
8607 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8608 HasZeroPointerIndex = C->isNullValue();
8609
8610 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00008611 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00008612
Chris Lattner69193f92004-04-05 01:30:19 +00008613 // Eliminate unneeded casts for indices.
8614 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00008615 gep_type_iterator GTI = gep_type_begin(GEP);
8616 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
8617 if (isa<SequentialType>(*GTI)) {
8618 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00008619 if (CI->getOpcode() == Instruction::ZExt ||
8620 CI->getOpcode() == Instruction::SExt) {
8621 const Type *SrcTy = CI->getOperand(0)->getType();
8622 // We can eliminate a cast from i32 to i64 iff the target
8623 // is a 32-bit pointer target.
8624 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8625 MadeChange = true;
8626 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00008627 }
8628 }
8629 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00008630 // If we are using a wider index than needed for this platform, shrink it
8631 // to what we need. If the incoming value needs a cast instruction,
8632 // insert it. This explicit cast can make subsequent optimizations more
8633 // obvious.
8634 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008635 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008636 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00008637 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00008638 MadeChange = true;
8639 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008640 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8641 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00008642 GEP.setOperand(i, Op);
8643 MadeChange = true;
8644 }
Chris Lattner69193f92004-04-05 01:30:19 +00008645 }
8646 if (MadeChange) return &GEP;
8647
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008648 // Combine Indices - If the source pointer to this getelementptr instruction
8649 // is a getelementptr instruction, combine the indices of the two
8650 // getelementptr instructions into a single instruction.
8651 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00008652 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00008653 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00008654 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00008655
8656 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00008657 // Note that if our source is a gep chain itself that we wait for that
8658 // chain to be resolved before we perform this transformation. This
8659 // avoids us creating a TON of code in some cases.
8660 //
8661 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8662 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8663 return 0; // Wait until our source is folded to completion.
8664
Chris Lattneraf6094f2007-02-15 22:48:32 +00008665 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00008666
8667 // Find out whether the last index in the source GEP is a sequential idx.
8668 bool EndsWithSequential = false;
8669 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8670 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00008671 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008672
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008673 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00008674 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00008675 // Replace: gep (gep %P, long B), long A, ...
8676 // With: T = long A+B; gep %P, T, ...
8677 //
Chris Lattner5f667a62004-05-07 22:09:22 +00008678 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00008679 if (SO1 == Constant::getNullValue(SO1->getType())) {
8680 Sum = GO1;
8681 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8682 Sum = SO1;
8683 } else {
8684 // If they aren't the same type, convert both to an integer of the
8685 // target's pointer size.
8686 if (SO1->getType() != GO1->getType()) {
8687 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008688 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008689 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008690 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00008691 } else {
8692 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008693 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008694 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008695 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008696
Reid Spencer7a9c62b2007-01-12 07:05:14 +00008697 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008698 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008699 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008700 } else {
8701 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008702 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8703 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008704 }
8705 }
8706 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008707 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8708 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8709 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008710 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8711 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008712 }
Chris Lattner69193f92004-04-05 01:30:19 +00008713 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008714
8715 // Recycle the GEP we already have if possible.
8716 if (SrcGEPOperands.size() == 2) {
8717 GEP.setOperand(0, SrcGEPOperands[0]);
8718 GEP.setOperand(1, Sum);
8719 return &GEP;
8720 } else {
8721 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8722 SrcGEPOperands.end()-1);
8723 Indices.push_back(Sum);
8724 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8725 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008726 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008727 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008728 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008729 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008730 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8731 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008732 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8733 }
8734
8735 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008736 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8737 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008738
Chris Lattner5f667a62004-05-07 22:09:22 +00008739 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008740 // GEP of global variable. If all of the indices for this GEP are
8741 // constants, we can promote this to a constexpr instead of an instruction.
8742
8743 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008744 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008745 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8746 for (; I != E && isa<Constant>(*I); ++I)
8747 Indices.push_back(cast<Constant>(*I));
8748
8749 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008750 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8751 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008752
8753 // Replace all uses of the GEP with the new constexpr...
8754 return ReplaceInstUsesWith(GEP, CE);
8755 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008756 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008757 if (!isa<PointerType>(X->getType())) {
8758 // Not interesting. Source pointer must be a cast from pointer.
8759 } else if (HasZeroPointerIndex) {
8760 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8761 // into : GEP [10 x ubyte]* X, long 0, ...
8762 //
8763 // This occurs when the program declares an array extern like "int X[];"
8764 //
8765 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8766 const PointerType *XTy = cast<PointerType>(X->getType());
8767 if (const ArrayType *XATy =
8768 dyn_cast<ArrayType>(XTy->getElementType()))
8769 if (const ArrayType *CATy =
8770 dyn_cast<ArrayType>(CPTy->getElementType()))
8771 if (CATy->getElementType() == XATy->getElementType()) {
8772 // At this point, we know that the cast source type is a pointer
8773 // to an array of the same type as the destination pointer
8774 // array. Because the array type is never stepped over (there
8775 // is a leading zero) we can fold the cast into this GEP.
8776 GEP.setOperand(0, X);
8777 return &GEP;
8778 }
8779 } else if (GEP.getNumOperands() == 2) {
8780 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008781 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8782 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008783 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8784 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8785 if (isa<ArrayType>(SrcElTy) &&
8786 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8787 TD->getTypeSize(ResElTy)) {
8788 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008789 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008790 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008791 // V and GEP are both pointer types --> BitCast
8792 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008793 }
Chris Lattner2a893292005-09-13 18:36:04 +00008794
8795 // Transform things like:
8796 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8797 // (where tmp = 8*tmp2) into:
8798 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8799
8800 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008801 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008802 uint64_t ArrayEltSize =
8803 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8804
8805 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8806 // allow either a mul, shift, or constant here.
8807 Value *NewIdx = 0;
8808 ConstantInt *Scale = 0;
8809 if (ArrayEltSize == 1) {
8810 NewIdx = GEP.getOperand(1);
8811 Scale = ConstantInt::get(NewIdx->getType(), 1);
8812 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008813 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008814 Scale = CI;
8815 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8816 if (Inst->getOpcode() == Instruction::Shl &&
8817 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008818 unsigned ShAmt =
8819 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00008820 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00008821 NewIdx = Inst->getOperand(0);
8822 } else if (Inst->getOpcode() == Instruction::Mul &&
8823 isa<ConstantInt>(Inst->getOperand(1))) {
8824 Scale = cast<ConstantInt>(Inst->getOperand(1));
8825 NewIdx = Inst->getOperand(0);
8826 }
8827 }
8828
8829 // If the index will be to exactly the right offset with the scale taken
8830 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008831 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008832 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008833 Scale = ConstantInt::get(Scale->getType(),
8834 Scale->getZExtValue() / ArrayEltSize);
8835 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008836 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8837 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008838 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8839 NewIdx = InsertNewInstBefore(Sc, GEP);
8840 }
8841
8842 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008843 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008844 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008845 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008846 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8847 // The NewGEP must be pointer typed, so must the old one -> BitCast
8848 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008849 }
8850 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008851 }
Chris Lattnerca081252001-12-14 16:52:21 +00008852 }
8853
Chris Lattnerca081252001-12-14 16:52:21 +00008854 return 0;
8855}
8856
Chris Lattner1085bdf2002-11-04 16:18:53 +00008857Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8858 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8859 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008860 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8861 const Type *NewTy =
8862 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008863 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008864
8865 // Create and insert the replacement instruction...
8866 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008867 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008868 else {
8869 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008870 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008871 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008872
8873 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008874
Chris Lattner1085bdf2002-11-04 16:18:53 +00008875 // Scan to the end of the allocation instructions, to skip over a block of
8876 // allocas if possible...
8877 //
8878 BasicBlock::iterator It = New;
8879 while (isa<AllocationInst>(*It)) ++It;
8880
8881 // Now that I is pointing to the first non-allocation-inst in the block,
8882 // insert our getelementptr instruction...
8883 //
Reid Spencerc635f472006-12-31 05:48:39 +00008884 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008885 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8886 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008887
8888 // Now make everything use the getelementptr instead of the original
8889 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008890 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008891 } else if (isa<UndefValue>(AI.getArraySize())) {
8892 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008893 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008894
8895 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8896 // Note that we only do this for alloca's, because malloc should allocate and
8897 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008898 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008899 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008900 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8901
Chris Lattner1085bdf2002-11-04 16:18:53 +00008902 return 0;
8903}
8904
Chris Lattner8427bff2003-12-07 01:24:23 +00008905Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8906 Value *Op = FI.getOperand(0);
8907
8908 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8909 if (CastInst *CI = dyn_cast<CastInst>(Op))
8910 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8911 FI.setOperand(0, CI->getOperand(0));
8912 return &FI;
8913 }
8914
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008915 // free undef -> unreachable.
8916 if (isa<UndefValue>(Op)) {
8917 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008918 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008919 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008920 return EraseInstFromFunction(FI);
8921 }
8922
Chris Lattnerf3a36602004-02-28 04:57:37 +00008923 // If we have 'free null' delete the instruction. This can happen in stl code
8924 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008925 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008926 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008927
Chris Lattner8427bff2003-12-07 01:24:23 +00008928 return 0;
8929}
8930
8931
Chris Lattner72684fe2005-01-31 05:51:45 +00008932/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008933static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8934 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008935 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008936
8937 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008938 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008939 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008940
Reid Spencer31a4ef42007-01-22 05:51:25 +00008941 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008942 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008943 // If the source is an array, the code below will not succeed. Check to
8944 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8945 // constants.
8946 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8947 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8948 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008949 Value *Idxs[2];
8950 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8951 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008952 SrcTy = cast<PointerType>(CastOp->getType());
8953 SrcPTy = SrcTy->getElementType();
8954 }
8955
Reid Spencer31a4ef42007-01-22 05:51:25 +00008956 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008957 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008958 // Do not allow turning this into a load of an integer, which is then
8959 // casted to a pointer, this pessimizes pointer analysis a lot.
8960 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008961 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8962 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008963
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008964 // Okay, we are casting from one integer or pointer type to another of
8965 // the same size. Instead of casting the pointer before the load, cast
8966 // the result of the loaded value.
8967 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8968 CI->getName(),
8969 LI.isVolatile()),LI);
8970 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008971 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008972 }
Chris Lattner35e24772004-07-13 01:49:43 +00008973 }
8974 }
8975 return 0;
8976}
8977
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008978/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008979/// from this value cannot trap. If it is not obviously safe to load from the
8980/// specified pointer, we do a quick local scan of the basic block containing
8981/// ScanFrom, to determine if the address is already accessed.
8982static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8983 // If it is an alloca or global variable, it is always safe to load from.
8984 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8985
8986 // Otherwise, be a little bit agressive by scanning the local block where we
8987 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008988 // from/to. If so, the previous load or store would have already trapped,
8989 // so there is no harm doing an extra load (also, CSE will later eliminate
8990 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008991 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8992
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008993 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008994 --BBI;
8995
8996 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8997 if (LI->getOperand(0) == V) return true;
8998 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8999 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009000
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00009001 }
Chris Lattnere6f13092004-09-19 19:18:10 +00009002 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009003}
9004
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009005Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9006 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00009007
Chris Lattnera9d84e32005-05-01 04:24:53 +00009008 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00009009 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00009010 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9011 return Res;
9012
9013 // None of the following transforms are legal for volatile loads.
9014 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00009015
Chris Lattnerb990f7d2005-09-12 22:00:15 +00009016 if (&LI.getParent()->front() != &LI) {
9017 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00009018 // If the instruction immediately before this is a store to the same
9019 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00009020 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9021 if (SI->getOperand(1) == LI.getOperand(0))
9022 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00009023 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9024 if (LIB->getOperand(0) == LI.getOperand(0))
9025 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00009026 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00009027
9028 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9029 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
9030 isa<UndefValue>(GEPI->getOperand(0))) {
9031 // Insert a new store to null instruction before the load to indicate
9032 // that this code is not reachable. We do this instead of inserting
9033 // an unreachable instruction directly because we cannot modify the
9034 // CFG.
9035 new StoreInst(UndefValue::get(LI.getType()),
9036 Constant::getNullValue(Op->getType()), &LI);
9037 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9038 }
9039
Chris Lattner81a7a232004-10-16 18:11:37 +00009040 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00009041 // load null/undef -> undef
9042 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009043 // Insert a new store to null instruction before the load to indicate that
9044 // this code is not reachable. We do this instead of inserting an
9045 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00009046 new StoreInst(UndefValue::get(LI.getType()),
9047 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00009048 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00009049 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009050
Chris Lattner81a7a232004-10-16 18:11:37 +00009051 // Instcombine load (constant global) into the value loaded.
9052 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009053 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00009054 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00009055
Chris Lattner81a7a232004-10-16 18:11:37 +00009056 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9057 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9058 if (CE->getOpcode() == Instruction::GetElementPtr) {
9059 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00009060 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00009061 if (Constant *V =
9062 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00009063 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00009064 if (CE->getOperand(0)->isNullValue()) {
9065 // Insert a new store to null instruction before the load to indicate
9066 // that this code is not reachable. We do this instead of inserting
9067 // an unreachable instruction directly because we cannot modify the
9068 // CFG.
9069 new StoreInst(UndefValue::get(LI.getType()),
9070 Constant::getNullValue(Op->getType()), &LI);
9071 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9072 }
9073
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009074 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00009075 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9076 return Res;
9077 }
9078 }
Chris Lattnere228ee52004-04-08 20:39:49 +00009079
Chris Lattnera9d84e32005-05-01 04:24:53 +00009080 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009081 // Change select and PHI nodes to select values instead of addresses: this
9082 // helps alias analysis out a lot, allows many others simplifications, and
9083 // exposes redundancy in the code.
9084 //
9085 // Note that we cannot do the transformation unless we know that the
9086 // introduced loads cannot trap! Something like this is valid as long as
9087 // the condition is always false: load (select bool %C, int* null, int* %G),
9088 // but it would not be valid if we transformed it to load from null
9089 // unconditionally.
9090 //
9091 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9092 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00009093 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9094 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009095 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00009096 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009097 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00009098 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009099 return new SelectInst(SI->getCondition(), V1, V2);
9100 }
9101
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00009102 // load (select (cond, null, P)) -> load P
9103 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9104 if (C->isNullValue()) {
9105 LI.setOperand(0, SI->getOperand(2));
9106 return &LI;
9107 }
9108
9109 // load (select (cond, P, null)) -> load P
9110 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9111 if (C->isNullValue()) {
9112 LI.setOperand(0, SI->getOperand(1));
9113 return &LI;
9114 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00009115 }
9116 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00009117 return 0;
9118}
9119
Reid Spencere928a152007-01-19 21:20:31 +00009120/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00009121/// when possible.
9122static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9123 User *CI = cast<User>(SI.getOperand(1));
9124 Value *CastOp = CI->getOperand(0);
9125
9126 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9127 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9128 const Type *SrcPTy = SrcTy->getElementType();
9129
Reid Spencer31a4ef42007-01-22 05:51:25 +00009130 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009131 // If the source is an array, the code below will not succeed. Check to
9132 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9133 // constants.
9134 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9135 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9136 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00009137 Value* Idxs[2];
9138 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9139 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00009140 SrcTy = cast<PointerType>(CastOp->getType());
9141 SrcPTy = SrcTy->getElementType();
9142 }
9143
Reid Spencer9a4bed02007-01-20 23:35:48 +00009144 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9145 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9146 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00009147
9148 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00009149 // the same size. Instead of casting the pointer before
9150 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00009151 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009152 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00009153 Instruction::CastOps opcode = Instruction::BitCast;
9154 const Type* CastSrcTy = SIOp0->getType();
9155 const Type* CastDstTy = SrcPTy;
9156 if (isa<PointerType>(CastDstTy)) {
9157 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009158 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00009159 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00009160 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00009161 opcode = Instruction::PtrToInt;
9162 }
9163 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00009164 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00009165 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009166 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00009167 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9168 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00009169 return new StoreInst(NewCast, CastOp);
9170 }
9171 }
9172 }
9173 return 0;
9174}
9175
Chris Lattner31f486c2005-01-31 05:36:43 +00009176Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9177 Value *Val = SI.getOperand(0);
9178 Value *Ptr = SI.getOperand(1);
9179
9180 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00009181 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009182 ++NumCombined;
9183 return 0;
9184 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00009185
9186 // If the RHS is an alloca with a single use, zapify the store, making the
9187 // alloca dead.
9188 if (Ptr->hasOneUse()) {
9189 if (isa<AllocaInst>(Ptr)) {
9190 EraseInstFromFunction(SI);
9191 ++NumCombined;
9192 return 0;
9193 }
9194
9195 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9196 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9197 GEP->getOperand(0)->hasOneUse()) {
9198 EraseInstFromFunction(SI);
9199 ++NumCombined;
9200 return 0;
9201 }
9202 }
Chris Lattner31f486c2005-01-31 05:36:43 +00009203
Chris Lattner5997cf92006-02-08 03:25:32 +00009204 // Do really simple DSE, to catch cases where there are several consequtive
9205 // stores to the same location, separated by a few arithmetic operations. This
9206 // situation often occurs with bitfield accesses.
9207 BasicBlock::iterator BBI = &SI;
9208 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9209 --ScanInsts) {
9210 --BBI;
9211
9212 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9213 // Prev store isn't volatile, and stores to the same location?
9214 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9215 ++NumDeadStore;
9216 ++BBI;
9217 EraseInstFromFunction(*PrevSI);
9218 continue;
9219 }
9220 break;
9221 }
9222
Chris Lattnerdab43b22006-05-26 19:19:20 +00009223 // If this is a load, we have to stop. However, if the loaded value is from
9224 // the pointer we're loading and is producing the pointer we're storing,
9225 // then *this* store is dead (X = load P; store X -> P).
9226 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9227 if (LI == Val && LI->getOperand(0) == Ptr) {
9228 EraseInstFromFunction(SI);
9229 ++NumCombined;
9230 return 0;
9231 }
9232 // Otherwise, this is a load from some other location. Stores before it
9233 // may not be dead.
9234 break;
9235 }
9236
Chris Lattner5997cf92006-02-08 03:25:32 +00009237 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00009238 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00009239 break;
9240 }
9241
9242
9243 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00009244
9245 // store X, null -> turns into 'unreachable' in SimplifyCFG
9246 if (isa<ConstantPointerNull>(Ptr)) {
9247 if (!isa<UndefValue>(Val)) {
9248 SI.setOperand(0, UndefValue::get(Val->getType()));
9249 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009250 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00009251 ++NumCombined;
9252 }
9253 return 0; // Do not modify these!
9254 }
9255
9256 // store undef, Ptr -> noop
9257 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00009258 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00009259 ++NumCombined;
9260 return 0;
9261 }
9262
Chris Lattner72684fe2005-01-31 05:51:45 +00009263 // If the pointer destination is a cast, see if we can fold the cast into the
9264 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00009265 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00009266 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9267 return Res;
9268 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00009269 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00009270 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9271 return Res;
9272
Chris Lattner219175c2005-09-12 23:23:25 +00009273
9274 // If this store is the last instruction in the basic block, and if the block
9275 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00009276 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00009277 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9278 if (BI->isUnconditional()) {
9279 // Check to see if the successor block has exactly two incoming edges. If
9280 // so, see if the other predecessor contains a store to the same location.
9281 // if so, insert a PHI node (if needed) and move the stores down.
9282 BasicBlock *Dest = BI->getSuccessor(0);
9283
9284 pred_iterator PI = pred_begin(Dest);
9285 BasicBlock *Other = 0;
9286 if (*PI != BI->getParent())
9287 Other = *PI;
9288 ++PI;
9289 if (PI != pred_end(Dest)) {
9290 if (*PI != BI->getParent())
9291 if (Other)
9292 Other = 0;
9293 else
9294 Other = *PI;
9295 if (++PI != pred_end(Dest))
9296 Other = 0;
9297 }
9298 if (Other) { // If only one other pred...
9299 BBI = Other->getTerminator();
9300 // Make sure this other block ends in an unconditional branch and that
9301 // there is an instruction before the branch.
9302 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
9303 BBI != Other->begin()) {
9304 --BBI;
9305 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
9306
9307 // If this instruction is a store to the same location.
9308 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
9309 // Okay, we know we can perform this transformation. Insert a PHI
9310 // node now if we need it.
9311 Value *MergedVal = OtherStore->getOperand(0);
9312 if (MergedVal != SI.getOperand(0)) {
9313 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9314 PN->reserveOperandSpace(2);
9315 PN->addIncoming(SI.getOperand(0), SI.getParent());
9316 PN->addIncoming(OtherStore->getOperand(0), Other);
9317 MergedVal = InsertNewInstBefore(PN, Dest->front());
9318 }
9319
9320 // Advance to a place where it is safe to insert the new store and
9321 // insert it.
9322 BBI = Dest->begin();
9323 while (isa<PHINode>(BBI)) ++BBI;
9324 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9325 OtherStore->isVolatile()), *BBI);
9326
9327 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00009328 EraseInstFromFunction(SI);
9329 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00009330 ++NumCombined;
9331 return 0;
9332 }
9333 }
9334 }
9335 }
9336
Chris Lattner31f486c2005-01-31 05:36:43 +00009337 return 0;
9338}
9339
9340
Chris Lattner9eef8a72003-06-04 04:46:00 +00009341Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9342 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00009343 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00009344 BasicBlock *TrueDest;
9345 BasicBlock *FalseDest;
9346 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9347 !isa<Constant>(X)) {
9348 // Swap Destinations and condition...
9349 BI.setCondition(X);
9350 BI.setSuccessor(0, FalseDest);
9351 BI.setSuccessor(1, TrueDest);
9352 return &BI;
9353 }
9354
Reid Spencer266e42b2006-12-23 06:05:41 +00009355 // Cannonicalize fcmp_one -> fcmp_oeq
9356 FCmpInst::Predicate FPred; Value *Y;
9357 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9358 TrueDest, FalseDest)))
9359 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9360 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9361 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009362 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009363 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9364 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00009365 // Swap Destinations and condition...
9366 BI.setCondition(NewSCC);
9367 BI.setSuccessor(0, FalseDest);
9368 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009369 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009370 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009371 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00009372 return &BI;
9373 }
9374
9375 // Cannonicalize icmp_ne -> icmp_eq
9376 ICmpInst::Predicate IPred;
9377 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9378 TrueDest, FalseDest)))
9379 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9380 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9381 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9382 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00009383 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009384 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9385 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00009386 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00009387 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009388 BI.setSuccessor(0, FalseDest);
9389 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009390 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00009391 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009392 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00009393 return &BI;
9394 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00009395
Chris Lattner9eef8a72003-06-04 04:46:00 +00009396 return 0;
9397}
Chris Lattner1085bdf2002-11-04 16:18:53 +00009398
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009399Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9400 Value *Cond = SI.getCondition();
9401 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9402 if (I->getOpcode() == Instruction::Add)
9403 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9404 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9405 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00009406 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009407 AddRHS));
9408 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009409 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00009410 return &SI;
9411 }
9412 }
9413 return 0;
9414}
9415
Chris Lattner6bc98652006-03-05 00:22:33 +00009416/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9417/// is to leave as a vector operation.
9418static bool CheapToScalarize(Value *V, bool isConstant) {
9419 if (isa<ConstantAggregateZero>(V))
9420 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009421 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009422 if (isConstant) return true;
9423 // If all elts are the same, we can extract.
9424 Constant *Op0 = C->getOperand(0);
9425 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9426 if (C->getOperand(i) != Op0)
9427 return false;
9428 return true;
9429 }
9430 Instruction *I = dyn_cast<Instruction>(V);
9431 if (!I) return false;
9432
9433 // Insert element gets simplified to the inserted element or is deleted if
9434 // this is constant idx extract element and its a constant idx insertelt.
9435 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9436 isa<ConstantInt>(I->getOperand(2)))
9437 return true;
9438 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9439 return true;
9440 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9441 if (BO->hasOneUse() &&
9442 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9443 CheapToScalarize(BO->getOperand(1), isConstant)))
9444 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00009445 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9446 if (CI->hasOneUse() &&
9447 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9448 CheapToScalarize(CI->getOperand(1), isConstant)))
9449 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00009450
9451 return false;
9452}
9453
Chris Lattner945e4372007-02-14 05:52:17 +00009454/// Read and decode a shufflevector mask.
9455///
9456/// It turns undef elements into values that are larger than the number of
9457/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00009458static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9459 unsigned NElts = SVI->getType()->getNumElements();
9460 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9461 return std::vector<unsigned>(NElts, 0);
9462 if (isa<UndefValue>(SVI->getOperand(2)))
9463 return std::vector<unsigned>(NElts, 2*NElts);
9464
9465 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00009466 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00009467 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9468 if (isa<UndefValue>(CP->getOperand(i)))
9469 Result.push_back(NElts*2); // undef -> 8
9470 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00009471 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00009472 return Result;
9473}
9474
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009475/// FindScalarElement - Given a vector and an element number, see if the scalar
9476/// value is already around as a register, for example if it were inserted then
9477/// extracted from the vector.
9478static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009479 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9480 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00009481 unsigned Width = PTy->getNumElements();
9482 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009483 return UndefValue::get(PTy->getElementType());
9484
9485 if (isa<UndefValue>(V))
9486 return UndefValue::get(PTy->getElementType());
9487 else if (isa<ConstantAggregateZero>(V))
9488 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00009489 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009490 return CP->getOperand(EltNo);
9491 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9492 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009493 if (!isa<ConstantInt>(III->getOperand(2)))
9494 return 0;
9495 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009496
9497 // If this is an insert to the element we are looking for, return the
9498 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009499 if (EltNo == IIElt)
9500 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009501
9502 // Otherwise, the insertelement doesn't modify the value, recurse on its
9503 // vector input.
9504 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00009505 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00009506 unsigned InEl = getShuffleMask(SVI)[EltNo];
9507 if (InEl < Width)
9508 return FindScalarElement(SVI->getOperand(0), InEl);
9509 else if (InEl < Width*2)
9510 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9511 else
9512 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009513 }
9514
9515 // Otherwise, we don't know.
9516 return 0;
9517}
9518
Robert Bocchinoa8352962006-01-13 22:48:06 +00009519Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009520
Chris Lattner92346c32006-03-31 18:25:14 +00009521 // If packed val is undef, replace extract with scalar undef.
9522 if (isa<UndefValue>(EI.getOperand(0)))
9523 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9524
9525 // If packed val is constant 0, replace extract with scalar 0.
9526 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9527 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9528
Reid Spencerd84d35b2007-02-15 02:26:10 +00009529 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009530 // If packed val is constant with uniform operands, replace EI
9531 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00009532 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009533 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00009534 if (C->getOperand(i) != op0) {
9535 op0 = 0;
9536 break;
9537 }
9538 if (op0)
9539 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009540 }
Chris Lattner6bc98652006-03-05 00:22:33 +00009541
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009542 // If extracting a specified index from the vector, see if we can recursively
9543 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009544 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00009545 // This instruction only demands the single element from the input vector.
9546 // If the input vector has a single use, simplify it based on this use
9547 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009548 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00009549 if (EI.getOperand(0)->hasOneUse()) {
9550 uint64_t UndefElts;
9551 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00009552 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00009553 UndefElts)) {
9554 EI.setOperand(0, V);
9555 return &EI;
9556 }
9557 }
9558
Reid Spencere0fc4df2006-10-20 07:07:24 +00009559 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009560 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00009561 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00009562
Chris Lattner83f65782006-05-25 22:53:38 +00009563 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00009564 if (I->hasOneUse()) {
9565 // Push extractelement into predecessor operation if legal and
9566 // profitable to do so
9567 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00009568 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9569 if (CheapToScalarize(BO, isConstantElt)) {
9570 ExtractElementInst *newEI0 =
9571 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9572 EI.getName()+".lhs");
9573 ExtractElementInst *newEI1 =
9574 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9575 EI.getName()+".rhs");
9576 InsertNewInstBefore(newEI0, EI);
9577 InsertNewInstBefore(newEI1, EI);
9578 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9579 }
Reid Spencerde46e482006-11-02 20:25:50 +00009580 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00009581 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00009582 PointerType::get(EI.getType()), EI);
9583 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00009584 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00009585 InsertNewInstBefore(GEP, EI);
9586 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00009587 }
9588 }
9589 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9590 // Extracting the inserted element?
9591 if (IE->getOperand(2) == EI.getOperand(1))
9592 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9593 // If the inserted and extracted elements are constants, they must not
9594 // be the same value, extract from the pre-inserted value instead.
9595 if (isa<Constant>(IE->getOperand(2)) &&
9596 isa<Constant>(EI.getOperand(1))) {
9597 AddUsesToWorkList(EI);
9598 EI.setOperand(0, IE->getOperand(0));
9599 return &EI;
9600 }
9601 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9602 // If this is extracting an element from a shufflevector, figure out where
9603 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00009604 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9605 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00009606 Value *Src;
9607 if (SrcIdx < SVI->getType()->getNumElements())
9608 Src = SVI->getOperand(0);
9609 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9610 SrcIdx -= SVI->getType()->getNumElements();
9611 Src = SVI->getOperand(1);
9612 } else {
9613 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00009614 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00009615 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00009616 }
9617 }
Chris Lattner83f65782006-05-25 22:53:38 +00009618 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00009619 return 0;
9620}
9621
Chris Lattner90951862006-04-16 00:51:47 +00009622/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9623/// elements from either LHS or RHS, return the shuffle mask and true.
9624/// Otherwise, return false.
9625static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9626 std::vector<Constant*> &Mask) {
9627 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9628 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009629 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00009630
9631 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009632 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00009633 return true;
9634 } else if (V == LHS) {
9635 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009636 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00009637 return true;
9638 } else if (V == RHS) {
9639 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009640 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00009641 return true;
9642 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9643 // If this is an insert of an extract from some other vector, include it.
9644 Value *VecOp = IEI->getOperand(0);
9645 Value *ScalarOp = IEI->getOperand(1);
9646 Value *IdxOp = IEI->getOperand(2);
9647
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009648 if (!isa<ConstantInt>(IdxOp))
9649 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00009650 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009651
9652 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9653 // Okay, we can handle this if the vector we are insertinting into is
9654 // transitively ok.
9655 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9656 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00009657 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00009658 return true;
9659 }
9660 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9661 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00009662 EI->getOperand(0)->getType() == V->getType()) {
9663 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009664 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00009665
9666 // This must be extracting from either LHS or RHS.
9667 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9668 // Okay, we can handle this if the vector we are insertinting into is
9669 // transitively ok.
9670 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9671 // If so, update the mask to reflect the inserted value.
9672 if (EI->getOperand(0) == LHS) {
9673 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009674 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00009675 } else {
9676 assert(EI->getOperand(0) == RHS);
9677 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009678 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00009679
9680 }
9681 return true;
9682 }
9683 }
9684 }
9685 }
9686 }
9687 // TODO: Handle shufflevector here!
9688
9689 return false;
9690}
9691
9692/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9693/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9694/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00009695static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00009696 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00009697 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009698 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009699 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009700 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009701
9702 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009703 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009704 return V;
9705 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009706 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009707 return V;
9708 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9709 // If this is an insert of an extract from some other vector, include it.
9710 Value *VecOp = IEI->getOperand(0);
9711 Value *ScalarOp = IEI->getOperand(1);
9712 Value *IdxOp = IEI->getOperand(2);
9713
9714 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9715 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9716 EI->getOperand(0)->getType() == V->getType()) {
9717 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009718 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9719 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009720
9721 // Either the extracted from or inserted into vector must be RHSVec,
9722 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009723 if (EI->getOperand(0) == RHS || RHS == 0) {
9724 RHS = EI->getOperand(0);
9725 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009726 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009727 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009728 return V;
9729 }
9730
Chris Lattner90951862006-04-16 00:51:47 +00009731 if (VecOp == RHS) {
9732 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009733 // Everything but the extracted element is replaced with the RHS.
9734 for (unsigned i = 0; i != NumElts; ++i) {
9735 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009736 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009737 }
9738 return V;
9739 }
Chris Lattner90951862006-04-16 00:51:47 +00009740
9741 // If this insertelement is a chain that comes from exactly these two
9742 // vectors, return the vector and the effective shuffle.
9743 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9744 return EI->getOperand(0);
9745
Chris Lattner39fac442006-04-15 01:39:45 +00009746 }
9747 }
9748 }
Chris Lattner90951862006-04-16 00:51:47 +00009749 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009750
9751 // Otherwise, can't do anything fancy. Return an identity vector.
9752 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009753 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009754 return V;
9755}
9756
9757Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9758 Value *VecOp = IE.getOperand(0);
9759 Value *ScalarOp = IE.getOperand(1);
9760 Value *IdxOp = IE.getOperand(2);
9761
9762 // If the inserted element was extracted from some other vector, and if the
9763 // indexes are constant, try to turn this into a shufflevector operation.
9764 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9765 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9766 EI->getOperand(0)->getType() == IE.getType()) {
9767 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009768 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9769 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009770
9771 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9772 return ReplaceInstUsesWith(IE, VecOp);
9773
9774 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9775 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9776
9777 // If we are extracting a value from a vector, then inserting it right
9778 // back into the same place, just use the input vector.
9779 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9780 return ReplaceInstUsesWith(IE, VecOp);
9781
9782 // We could theoretically do this for ANY input. However, doing so could
9783 // turn chains of insertelement instructions into a chain of shufflevector
9784 // instructions, and right now we do not merge shufflevectors. As such,
9785 // only do this in a situation where it is clear that there is benefit.
9786 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9787 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9788 // the values of VecOp, except then one read from EIOp0.
9789 // Build a new shuffle mask.
9790 std::vector<Constant*> Mask;
9791 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009792 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009793 else {
9794 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009795 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009796 NumVectorElts));
9797 }
Reid Spencerc635f472006-12-31 05:48:39 +00009798 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009799 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009800 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009801 }
9802
9803 // If this insertelement isn't used by some other insertelement, turn it
9804 // (and any insertelements it points to), into one big shuffle.
9805 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9806 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009807 Value *RHS = 0;
9808 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9809 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9810 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009811 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009812 }
9813 }
9814 }
9815
9816 return 0;
9817}
9818
9819
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009820Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9821 Value *LHS = SVI.getOperand(0);
9822 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009823 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009824
9825 bool MadeChange = false;
9826
Chris Lattner2deeaea2006-10-05 06:55:50 +00009827 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009828 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009829 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9830
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009831 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009832 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009833 if (isa<UndefValue>(SVI.getOperand(1))) {
9834 // Scan to see if there are any references to the RHS. If so, replace them
9835 // with undef element refs and set MadeChange to true.
9836 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9837 if (Mask[i] >= e && Mask[i] != 2*e) {
9838 Mask[i] = 2*e;
9839 MadeChange = true;
9840 }
9841 }
9842
9843 if (MadeChange) {
9844 // Remap any references to RHS to use LHS.
9845 std::vector<Constant*> Elts;
9846 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9847 if (Mask[i] == 2*e)
9848 Elts.push_back(UndefValue::get(Type::Int32Ty));
9849 else
9850 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9851 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009852 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009853 }
9854 }
Chris Lattner39fac442006-04-15 01:39:45 +00009855
Chris Lattner12249be2006-05-25 23:48:38 +00009856 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9857 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9858 if (LHS == RHS || isa<UndefValue>(LHS)) {
9859 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009860 // shuffle(undef,undef,mask) -> undef.
9861 return ReplaceInstUsesWith(SVI, LHS);
9862 }
9863
Chris Lattner12249be2006-05-25 23:48:38 +00009864 // Remap any references to RHS to use LHS.
9865 std::vector<Constant*> Elts;
9866 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009867 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009868 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009869 else {
9870 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9871 (Mask[i] < e && isa<UndefValue>(LHS)))
9872 Mask[i] = 2*e; // Turn into undef.
9873 else
9874 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009875 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009876 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009877 }
Chris Lattner12249be2006-05-25 23:48:38 +00009878 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009879 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009880 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009881 LHS = SVI.getOperand(0);
9882 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009883 MadeChange = true;
9884 }
9885
Chris Lattner0e477162006-05-26 00:29:06 +00009886 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009887 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009888
Chris Lattner12249be2006-05-25 23:48:38 +00009889 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9890 if (Mask[i] >= e*2) continue; // Ignore undef values.
9891 // Is this an identity shuffle of the LHS value?
9892 isLHSID &= (Mask[i] == i);
9893
9894 // Is this an identity shuffle of the RHS value?
9895 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009896 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009897
Chris Lattner12249be2006-05-25 23:48:38 +00009898 // Eliminate identity shuffles.
9899 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9900 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009901
Chris Lattner0e477162006-05-26 00:29:06 +00009902 // If the LHS is a shufflevector itself, see if we can combine it with this
9903 // one without producing an unusual shuffle. Here we are really conservative:
9904 // we are absolutely afraid of producing a shuffle mask not in the input
9905 // program, because the code gen may not be smart enough to turn a merged
9906 // shuffle into two specific shuffles: it may produce worse code. As such,
9907 // we only merge two shuffles if the result is one of the two input shuffle
9908 // masks. In this case, merging the shuffles just removes one instruction,
9909 // which we know is safe. This is good for things like turning:
9910 // (splat(splat)) -> splat.
9911 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9912 if (isa<UndefValue>(RHS)) {
9913 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9914
9915 std::vector<unsigned> NewMask;
9916 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9917 if (Mask[i] >= 2*e)
9918 NewMask.push_back(2*e);
9919 else
9920 NewMask.push_back(LHSMask[Mask[i]]);
9921
9922 // If the result mask is equal to the src shuffle or this shuffle mask, do
9923 // the replacement.
9924 if (NewMask == LHSMask || NewMask == Mask) {
9925 std::vector<Constant*> Elts;
9926 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9927 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009928 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009929 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009930 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009931 }
9932 }
9933 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9934 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009935 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009936 }
9937 }
9938 }
Chris Lattner4284f642007-01-30 22:32:46 +00009939
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009940 return MadeChange ? &SVI : 0;
9941}
9942
9943
Robert Bocchinoa8352962006-01-13 22:48:06 +00009944
Chris Lattner39c98bb2004-12-08 23:43:58 +00009945
9946/// TryToSinkInstruction - Try to move the specified instruction from its
9947/// current block into the beginning of DestBlock, which can only happen if it's
9948/// safe to move the instruction past all of the instructions between it and the
9949/// end of its block.
9950static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9951 assert(I->hasOneUse() && "Invariants didn't hold!");
9952
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009953 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9954 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009955
Chris Lattner39c98bb2004-12-08 23:43:58 +00009956 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009957 if (isa<AllocaInst>(I) && I->getParent() ==
9958 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009959 return false;
9960
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009961 // We can only sink load instructions if there is nothing between the load and
9962 // the end of block that could change the value.
9963 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009964 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9965 Scan != E; ++Scan)
9966 if (Scan->mayWriteToMemory())
9967 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009968 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009969
9970 BasicBlock::iterator InsertPos = DestBlock->begin();
9971 while (isa<PHINode>(InsertPos)) ++InsertPos;
9972
Chris Lattner9f269e42005-08-08 19:11:57 +00009973 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009974 ++NumSunkInst;
9975 return true;
9976}
9977
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009978
9979/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9980/// all reachable code to the worklist.
9981///
9982/// This has a couple of tricks to make the code faster and more powerful. In
9983/// particular, we constant fold and DCE instructions as we go, to avoid adding
9984/// them to the worklist (this significantly speeds up instcombine on code where
9985/// many instructions are dead or constant). Additionally, if we find a branch
9986/// whose condition is a known constant, we only visit the reachable successors.
9987///
9988static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009989 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009990 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009991 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009992 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009993 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009994
9995 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9996 Instruction *Inst = BBI++;
9997
9998 // DCE instruction if trivially dead.
9999 if (isInstructionTriviallyDead(Inst)) {
10000 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010001 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010002 Inst->eraseFromParent();
10003 continue;
10004 }
10005
10006 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +000010007 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010008 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010009 Inst->replaceAllUsesWith(C);
10010 ++NumConstProp;
10011 Inst->eraseFromParent();
10012 continue;
10013 }
10014
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010015 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010016 }
10017
10018 // Recursively visit successors. If this is a branch or switch on a constant,
10019 // only visit the reachable successor.
10020 TerminatorInst *TI = BB->getTerminator();
10021 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +000010022 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +000010023 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010024 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010025 return;
10026 }
10027 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10028 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10029 // See if this is an explicit destination.
10030 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10031 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010032 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010033 return;
10034 }
10035
10036 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010037 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010038 return;
10039 }
10040 }
10041
10042 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010043 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010044}
10045
Chris Lattner960a5432007-03-03 02:04:50 +000010046bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +000010047 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000010048 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +000010049
10050 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10051 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +000010052
Chris Lattner4ed40f72005-07-07 20:40:38 +000010053 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010054 // Do a depth-first traversal of the function, populate the worklist with
10055 // the reachable instructions. Ignore blocks that are not reachable. Keep
10056 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +000010057 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010058 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000010059
Chris Lattner4ed40f72005-07-07 20:40:38 +000010060 // Do a quick scan over the function. If we find any blocks that are
10061 // unreachable, remove any instructions inside of them. This prevents
10062 // the instcombine code from having to deal with some bad special cases.
10063 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10064 if (!Visited.count(BB)) {
10065 Instruction *Term = BB->getTerminator();
10066 while (Term != BB->begin()) { // Remove instrs bottom-up
10067 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +000010068
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010069 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +000010070 ++NumDeadInst;
10071
10072 if (!I->use_empty())
10073 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10074 I->eraseFromParent();
10075 }
10076 }
10077 }
Chris Lattnerca081252001-12-14 16:52:21 +000010078
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010079 while (!Worklist.empty()) {
10080 Instruction *I = RemoveOneFromWorkList();
10081 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +000010082
Chris Lattner1443bc52006-05-11 17:11:52 +000010083 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +000010084 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +000010085 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010086 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +000010087 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +000010088 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010089
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010090 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010091
10092 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010093 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010094 continue;
10095 }
Chris Lattner99f48c62002-09-02 04:59:56 +000010096
Chris Lattner1443bc52006-05-11 17:11:52 +000010097 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +000010098 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010099 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +000010100
Chris Lattner1443bc52006-05-11 17:11:52 +000010101 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +000010102 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +000010103 ReplaceInstUsesWith(*I, C);
10104
Chris Lattner99f48c62002-09-02 04:59:56 +000010105 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +000010106 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010107 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010108 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +000010109 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010110
Chris Lattner39c98bb2004-12-08 23:43:58 +000010111 // See if we can trivially sink this instruction to a successor basic block.
10112 if (I->hasOneUse()) {
10113 BasicBlock *BB = I->getParent();
10114 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10115 if (UserParent != BB) {
10116 bool UserIsSuccessor = false;
10117 // See if the user is one of our successors.
10118 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10119 if (*SI == UserParent) {
10120 UserIsSuccessor = true;
10121 break;
10122 }
10123
10124 // If the user is one of our immediate successors, and if that successor
10125 // only has us as a predecessors (we'd have to split the critical edge
10126 // otherwise), we can keep going.
10127 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10128 next(pred_begin(UserParent)) == pred_end(UserParent))
10129 // Okay, the CFG is simple enough, try to sink this instruction.
10130 Changed |= TryToSinkInstruction(I, UserParent);
10131 }
10132 }
10133
Chris Lattnerca081252001-12-14 16:52:21 +000010134 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010135 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +000010136 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +000010137 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +000010138 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010139 DOUT << "IC: Old = " << *I
10140 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010141
Chris Lattner396dbfe2004-06-09 05:08:07 +000010142 // Everything uses the new instruction now.
10143 I->replaceAllUsesWith(Result);
10144
10145 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010146 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +000010147 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010148
Chris Lattner6e0123b2007-02-11 01:23:03 +000010149 // Move the name to the new instruction first.
10150 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010151
10152 // Insert the new instruction into the basic block...
10153 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +000010154 BasicBlock::iterator InsertPos = I;
10155
10156 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10157 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10158 ++InsertPos;
10159
10160 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010161
Chris Lattner63d75af2004-05-01 23:27:23 +000010162 // Make sure that we reprocess all operands now that we reduced their
10163 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010164 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +000010165
Chris Lattner396dbfe2004-06-09 05:08:07 +000010166 // Instructions can end up on the worklist more than once. Make sure
10167 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010168 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +000010169
10170 // Erase the old instruction.
10171 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +000010172 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +000010173 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +000010174
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010175 // If the instruction was modified, it's possible that it is now dead.
10176 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +000010177 if (isInstructionTriviallyDead(I)) {
10178 // Make sure we process all operands now that we are reducing their
10179 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +000010180 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +000010181
Chris Lattner63d75af2004-05-01 23:27:23 +000010182 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +000010183 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000010184 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +000010185 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +000010186 } else {
Chris Lattner960a5432007-03-03 02:04:50 +000010187 AddToWorkList(I);
10188 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +000010189 }
Chris Lattner053c0932002-05-14 15:24:07 +000010190 }
Chris Lattner260ab202002-04-18 17:39:14 +000010191 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +000010192 }
10193 }
10194
Chris Lattner960a5432007-03-03 02:04:50 +000010195 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +000010196 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +000010197}
10198
Chris Lattner960a5432007-03-03 02:04:50 +000010199
10200bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +000010201 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10202
Chris Lattner960a5432007-03-03 02:04:50 +000010203 bool EverMadeChange = false;
10204
10205 // Iterate while there is work to do.
10206 unsigned Iteration = 0;
10207 while (DoOneIteration(F, Iteration++))
10208 EverMadeChange = true;
10209 return EverMadeChange;
10210}
10211
Brian Gaeke38b79e82004-07-27 17:43:21 +000010212FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +000010213 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +000010214}
Brian Gaeke960707c2003-11-11 22:41:34 +000010215