blob: d26fbced5b1fb71aebb8fc719868aeaf531e5ae6 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer755d0e72007-03-26 17:44:01 +000059#include <sstream>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnera74deaf2007-04-03 17:43:25 +0000186 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
187 Instruction *LHS,
188 ConstantInt *RHS);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000189
Reid Spencer266e42b2006-12-23 06:05:41 +0000190 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
191 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000192 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000193 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000194 Instruction *commonCastTransforms(CastInst &CI);
195 Instruction *commonIntCastTransforms(CastInst &CI);
196 Instruction *visitTrunc(CastInst &CI);
197 Instruction *visitZExt(CastInst &CI);
198 Instruction *visitSExt(CastInst &CI);
199 Instruction *visitFPTrunc(CastInst &CI);
200 Instruction *visitFPExt(CastInst &CI);
201 Instruction *visitFPToUI(CastInst &CI);
202 Instruction *visitFPToSI(CastInst &CI);
203 Instruction *visitUIToFP(CastInst &CI);
204 Instruction *visitSIToFP(CastInst &CI);
205 Instruction *visitPtrToInt(CastInst &CI);
206 Instruction *visitIntToPtr(CastInst &CI);
207 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000208 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
209 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000210 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000211 Instruction *visitCallInst(CallInst &CI);
212 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000213 Instruction *visitPHINode(PHINode &PN);
214 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000215 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000216 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000217 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000218 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000219 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000220 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000221 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000222 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000223 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000224
225 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000226 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000227
Chris Lattner970c33a2003-06-19 17:00:31 +0000228 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000229 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000230 bool transformConstExprCastCall(CallSite CS);
231
Chris Lattner69193f92004-04-05 01:30:19 +0000232 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000233 // InsertNewInstBefore - insert an instruction New before instruction Old
234 // in the program. Add the new instruction to the worklist.
235 //
Chris Lattner623826c2004-09-28 21:48:02 +0000236 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000237 assert(New && New->getParent() == 0 &&
238 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000239 BasicBlock *BB = Old.getParent();
240 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000241 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000242 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000243 }
244
Chris Lattner7e794272004-09-24 15:21:34 +0000245 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
246 /// This also adds the cast to the worklist. Finally, this returns the
247 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000248 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
249 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000250 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000251
Chris Lattnere79d2492006-04-06 19:19:17 +0000252 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000253 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000254
Reid Spencer13bc5d72006-12-12 09:18:51 +0000255 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000256 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000257 return C;
258 }
259
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000260 // ReplaceInstUsesWith - This method is to be used when an instruction is
261 // found to be dead, replacable with another preexisting expression. Here
262 // we add all uses of I to the worklist, replace all uses of I with the new
263 // value, then return I, so that the inst combiner will know that I was
264 // modified.
265 //
266 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000267 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000268 if (&I != V) {
269 I.replaceAllUsesWith(V);
270 return &I;
271 } else {
272 // If we are replacing the instruction with itself, this must be in a
273 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000274 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000275 return &I;
276 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000277 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000278
Chris Lattner2590e512006-02-07 06:56:34 +0000279 // UpdateValueUsesWith - This method is to be used when an value is
280 // found to be replacable with another preexisting expression or was
281 // updated. Here we add all uses of I to the worklist, replace all uses of
282 // I with the new value (unless the instruction was just updated), then
283 // return true, so that the inst combiner will know that I was modified.
284 //
285 bool UpdateValueUsesWith(Value *Old, Value *New) {
286 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
287 if (Old != New)
288 Old->replaceAllUsesWith(New);
289 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000290 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000291 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000292 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000293 return true;
294 }
295
Chris Lattner51ea1272004-02-28 05:22:00 +0000296 // EraseInstFromFunction - When dealing with an instruction that has side
297 // effects or produces a void value, we can't rely on DCE to delete the
298 // instruction. Instead, visit methods should return the value returned by
299 // this function.
300 Instruction *EraseInstFromFunction(Instruction &I) {
301 assert(I.use_empty() && "Cannot erase instruction that is used!");
302 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000303 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000304 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000305 return 0; // Don't do anything with FI
306 }
307
Chris Lattner3ac7c262003-08-13 20:16:26 +0000308 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000309 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
310 /// InsertBefore instruction. This is specialized a bit to avoid inserting
311 /// casts that are known to not do anything...
312 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000313 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
314 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000315 Instruction *InsertBefore);
316
Reid Spencer266e42b2006-12-23 06:05:41 +0000317 /// SimplifyCommutative - This performs a few simplifications for
318 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000319 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000320
Reid Spencer266e42b2006-12-23 06:05:41 +0000321 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
322 /// most-complex to least-complex order.
323 bool SimplifyCompare(CmpInst &I);
324
Reid Spencer959a21d2007-03-23 21:24:59 +0000325 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
326 /// on the demanded bits.
Reid Spencer1791f232007-03-12 17:25:59 +0000327 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
328 APInt& KnownZero, APInt& KnownOne,
329 unsigned Depth = 0);
330
Chris Lattner2deeaea2006-10-05 06:55:50 +0000331 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
332 uint64_t &UndefElts, unsigned Depth = 0);
333
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000334 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
335 // PHI node as operand #0, see if we can fold the instruction into the PHI
336 // (which is only possible if all operands to the PHI are constants).
337 Instruction *FoldOpIntoPhi(Instruction &I);
338
Chris Lattner7515cab2004-11-14 19:13:23 +0000339 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
340 // operator and they all are only used by the PHI, PHI together their
341 // inputs, and do the operation once, to the result of the PHI.
342 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000343 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
344
345
Zhou Sheng75b871f2007-01-11 12:24:14 +0000346 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
347 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000348
Zhou Sheng75b871f2007-01-11 12:24:14 +0000349 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000350 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000351 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000352 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000353 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000354 Instruction *MatchBSwap(BinaryOperator &I);
355
Reid Spencer74a528b2006-12-13 18:21:21 +0000356 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000357 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000358
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000359 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000360}
361
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000362// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000363// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364static unsigned getComplexity(Value *V) {
365 if (isa<Instruction>(V)) {
366 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000367 return 3;
368 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000369 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000370 if (isa<Argument>(V)) return 3;
371 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000372}
Chris Lattner260ab202002-04-18 17:39:14 +0000373
Chris Lattner7fb29e12003-03-11 00:12:48 +0000374// isOnlyUse - Return true if this instruction will be deleted if we stop using
375// it.
376static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000377 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000378}
379
Chris Lattnere79e8542004-02-23 06:38:22 +0000380// getPromotedType - Return the specified type promoted as it would be to pass
381// though a va_arg area...
382static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000383 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
384 if (ITy->getBitWidth() < 32)
385 return Type::Int32Ty;
386 } else if (Ty == Type::FloatTy)
387 return Type::DoubleTy;
388 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000389}
390
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000391/// getBitCastOperand - If the specified operand is a CastInst or a constant
392/// expression bitcast, return the operand value, otherwise return null.
393static Value *getBitCastOperand(Value *V) {
394 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000395 return I->getOperand(0);
396 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000398 return CE->getOperand(0);
399 return 0;
400}
401
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000402/// This function is a wrapper around CastInst::isEliminableCastPair. It
403/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000404static Instruction::CastOps
405isEliminableCastPair(
406 const CastInst *CI, ///< The first cast instruction
407 unsigned opcode, ///< The opcode of the second cast instruction
408 const Type *DstTy, ///< The target type for the second cast instruction
409 TargetData *TD ///< The target data for pointer size
410) {
411
412 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
413 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000415 // Get the opcodes of the two Cast instructions
416 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
417 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000418
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000419 return Instruction::CastOps(
420 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
421 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000422}
423
424/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
425/// in any code being generated. It does not require codegen if V is simple
426/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000427static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
428 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 if (V->getType() == Ty || isa<Constant>(V)) return false;
430
Chris Lattner99155be2006-05-25 23:24:33 +0000431 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000432 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000433 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000434 return false;
435 return true;
436}
437
438/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
439/// InsertBefore instruction. This is specialized a bit to avoid inserting
440/// casts that are known to not do anything...
441///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000442Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
443 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000444 Instruction *InsertBefore) {
445 if (V->getType() == DestTy) return V;
446 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000447 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000448
Reid Spencer13bc5d72006-12-12 09:18:51 +0000449 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000450}
451
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452// SimplifyCommutative - This performs a few simplifications for commutative
453// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000454//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455// 1. Order operands such that they are listed from right (least complex) to
456// left (most complex). This puts constants before unary operators before
457// binary operators.
458//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000459// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
460// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000461//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000462bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000463 bool Changed = false;
464 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
465 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000467 if (!I.isAssociative()) return Changed;
468 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000469 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
470 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
471 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000472 Constant *Folded = ConstantExpr::get(I.getOpcode(),
473 cast<Constant>(I.getOperand(1)),
474 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000475 I.setOperand(0, Op->getOperand(0));
476 I.setOperand(1, Folded);
477 return true;
478 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
479 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
480 isOnlyUse(Op) && isOnlyUse(Op1)) {
481 Constant *C1 = cast<Constant>(Op->getOperand(1));
482 Constant *C2 = cast<Constant>(Op1->getOperand(1));
483
484 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000485 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
487 Op1->getOperand(0),
488 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000489 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 I.setOperand(0, New);
491 I.setOperand(1, Folded);
492 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000493 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000494 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000495 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000496}
Chris Lattnerca081252001-12-14 16:52:21 +0000497
Reid Spencer266e42b2006-12-23 06:05:41 +0000498/// SimplifyCompare - For a CmpInst this function just orders the operands
499/// so that theyare listed from right (least complex) to left (most complex).
500/// This puts constants before unary operators before binary operators.
501bool InstCombiner::SimplifyCompare(CmpInst &I) {
502 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
503 return false;
504 I.swapOperands();
505 // Compare instructions are not associative so there's nothing else we can do.
506 return true;
507}
508
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
510// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000511//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000512static inline Value *dyn_castNegVal(Value *V) {
513 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000514 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515
Chris Lattner9ad0d552004-12-14 20:08:06 +0000516 // Constants can be considered to be negated values if they can be folded.
517 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
518 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000520}
521
Chris Lattnerbb74e222003-03-10 23:06:50 +0000522static inline Value *dyn_castNotVal(Value *V) {
523 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000524 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525
526 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000527 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000528 return ConstantInt::get(~C->getValue());
Chris Lattnerbb74e222003-03-10 23:06:50 +0000529 return 0;
530}
531
Chris Lattner7fb29e12003-03-11 00:12:48 +0000532// dyn_castFoldableMul - If this value is a multiply that can be folded into
533// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534// non-constant operand of the multiply, and set CST to point to the multiplier.
535// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000536//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000537static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000538 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000539 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000540 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000541 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000543 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000544 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 // The multiplier is really 1 << CST.
Zhou Sheng4961cf12007-03-29 01:57:21 +0000546 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +0000547 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng4961cf12007-03-29 01:57:21 +0000548 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 return I->getOperand(0);
550 }
551 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000552 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000553}
Chris Lattner31ae8632002-08-14 17:51:49 +0000554
Chris Lattner0798af32005-01-13 20:14:25 +0000555/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
556/// expression, return it.
557static User *dyn_castGetElementPtr(Value *V) {
558 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
559 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
560 if (CE->getOpcode() == Instruction::GetElementPtr)
561 return cast<User>(V);
562 return false;
563}
564
Reid Spencer80263aa2007-03-25 05:33:51 +0000565/// AddOne - Add one to a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000566static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000567 APInt Val(C->getValue());
568 return ConstantInt::get(++Val);
Chris Lattner623826c2004-09-28 21:48:02 +0000569}
Reid Spencer80263aa2007-03-25 05:33:51 +0000570/// SubOne - Subtract one from a ConstantInt
Chris Lattner6862fbd2004-09-29 17:40:11 +0000571static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer624766f2007-03-25 19:55:33 +0000572 APInt Val(C->getValue());
573 return ConstantInt::get(--Val);
Reid Spencer80263aa2007-03-25 05:33:51 +0000574}
575/// Add - Add two ConstantInts together
576static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
577 return ConstantInt::get(C1->getValue() + C2->getValue());
578}
579/// And - Bitwise AND two ConstantInts together
580static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
581 return ConstantInt::get(C1->getValue() & C2->getValue());
582}
583/// Subtract - Subtract one ConstantInt from another
584static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
585 return ConstantInt::get(C1->getValue() - C2->getValue());
586}
587/// Multiply - Multiply two ConstantInts together
588static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
589 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner623826c2004-09-28 21:48:02 +0000590}
591
Chris Lattner4534dd592006-02-09 07:38:58 +0000592/// ComputeMaskedBits - Determine which of the bits specified in Mask are
593/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spenceraa696402007-03-08 01:46:38 +0000594/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
595/// processing.
596/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
597/// we cannot optimize based on the assumption that it is zero without changing
598/// it to be an explicit zero. If we don't change it to zero, other code could
599/// optimized based on the contradictory assumption that it is non-zero.
600/// Because instcombine aggressively folds operations with undef args anyway,
601/// this won't lose us code quality.
Reid Spencer52830322007-03-25 21:11:44 +0000602static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spenceraa696402007-03-08 01:46:38 +0000603 APInt& KnownOne, unsigned Depth = 0) {
Zhou Shengaf4341d2007-03-13 02:23:10 +0000604 assert(V && "No Value?");
605 assert(Depth <= 6 && "Limit Search Depth");
Reid Spenceraa696402007-03-08 01:46:38 +0000606 uint32_t BitWidth = Mask.getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000607 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Shengaf4341d2007-03-13 02:23:10 +0000608 KnownZero.getBitWidth() == BitWidth &&
Reid Spenceraa696402007-03-08 01:46:38 +0000609 KnownOne.getBitWidth() == BitWidth &&
Zhou Sheng57e3f732007-03-28 02:19:03 +0000610 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spenceraa696402007-03-08 01:46:38 +0000611 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
612 // We know all of the bits for a constant!
Zhou Shengaf4341d2007-03-13 02:23:10 +0000613 KnownOne = CI->getValue() & Mask;
Reid Spenceraa696402007-03-08 01:46:38 +0000614 KnownZero = ~KnownOne & Mask;
615 return;
616 }
617
Reid Spenceraa696402007-03-08 01:46:38 +0000618 if (Depth == 6 || Mask == 0)
619 return; // Limit search depth.
620
621 Instruction *I = dyn_cast<Instruction>(V);
622 if (!I) return;
623
Zhou Shengaf4341d2007-03-13 02:23:10 +0000624 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spenceraa696402007-03-08 01:46:38 +0000625 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spenceraa696402007-03-08 01:46:38 +0000626
627 switch (I->getOpcode()) {
Reid Spencerd8aad612007-03-25 02:03:12 +0000628 case Instruction::And: {
Reid Spenceraa696402007-03-08 01:46:38 +0000629 // If either the LHS or the RHS are Zero, the result is zero.
630 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000631 APInt Mask2(Mask & ~KnownZero);
632 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Output known-1 bits are only known if set in both the LHS & RHS.
637 KnownOne &= KnownOne2;
638 // Output known-0 are known to be clear if zero in either the LHS | RHS.
639 KnownZero |= KnownZero2;
640 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000641 }
642 case Instruction::Or: {
Reid Spenceraa696402007-03-08 01:46:38 +0000643 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencerd8aad612007-03-25 02:03:12 +0000644 APInt Mask2(Mask & ~KnownOne);
645 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000646 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
647 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
648
649 // Output known-0 bits are only known if clear in both the LHS & RHS.
650 KnownZero &= KnownZero2;
651 // Output known-1 are known to be set if set in either the LHS | RHS.
652 KnownOne |= KnownOne2;
653 return;
Reid Spencerd8aad612007-03-25 02:03:12 +0000654 }
Reid Spenceraa696402007-03-08 01:46:38 +0000655 case Instruction::Xor: {
656 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
657 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
658 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
659 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
660
661 // Output known-0 bits are known if clear or set in both the LHS & RHS.
662 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
663 // Output known-1 are known to be set if set in only one of the LHS, RHS.
664 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
665 KnownZero = KnownZeroOut;
666 return;
667 }
668 case Instruction::Select:
669 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
671 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
673
674 // Only known if known in both the LHS and RHS.
675 KnownOne &= KnownOne2;
676 KnownZero &= KnownZero2;
677 return;
678 case Instruction::FPTrunc:
679 case Instruction::FPExt:
680 case Instruction::FPToUI:
681 case Instruction::FPToSI:
682 case Instruction::SIToFP:
683 case Instruction::PtrToInt:
684 case Instruction::UIToFP:
685 case Instruction::IntToPtr:
686 return; // Can't work with floating point or pointers
Zhou Shengaf4341d2007-03-13 02:23:10 +0000687 case Instruction::Trunc: {
Reid Spenceraa696402007-03-08 01:46:38 +0000688 // All these have integer operands
Zhou Shengaf4341d2007-03-13 02:23:10 +0000689 uint32_t SrcBitWidth =
690 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng57e3f732007-03-28 02:19:03 +0000691 APInt MaskIn(Mask);
692 MaskIn.zext(SrcBitWidth);
693 KnownZero.zext(SrcBitWidth);
694 KnownOne.zext(SrcBitWidth);
695 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Shengaf4341d2007-03-13 02:23:10 +0000696 KnownZero.trunc(BitWidth);
697 KnownOne.trunc(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000698 return;
Zhou Shengaf4341d2007-03-13 02:23:10 +0000699 }
Reid Spenceraa696402007-03-08 01:46:38 +0000700 case Instruction::BitCast: {
701 const Type *SrcTy = I->getOperand(0)->getType();
702 if (SrcTy->isInteger()) {
703 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
704 return;
705 }
706 break;
707 }
708 case Instruction::ZExt: {
709 // Compute the bits in the result that are not present in the input.
710 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000711 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000712
Zhou Sheng57e3f732007-03-28 02:19:03 +0000713 APInt MaskIn(Mask);
714 MaskIn.trunc(SrcBitWidth);
715 KnownZero.trunc(SrcBitWidth);
716 KnownOne.trunc(SrcBitWidth);
717 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 // The top bits are known to be zero.
Zhou Shengaf4341d2007-03-13 02:23:10 +0000720 KnownZero.zext(BitWidth);
721 KnownOne.zext(BitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000722 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000723 return;
724 }
725 case Instruction::SExt: {
726 // Compute the bits in the result that are not present in the input.
727 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Shengaf4341d2007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencercd99fbd2007-03-25 04:26:16 +0000729
Zhou Sheng57e3f732007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.trunc(SrcBitWidth);
732 KnownZero.trunc(SrcBitWidth);
733 KnownOne.trunc(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengaf4341d2007-03-13 02:23:10 +0000736 KnownZero.zext(BitWidth);
737 KnownOne.zext(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000738
739 // If the sign bit of the input is known set or clear, then we know the
740 // top bits of the result.
Zhou Sheng57e3f732007-03-28 02:19:03 +0000741 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng117477e2007-03-28 17:38:21 +0000742 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000743 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng117477e2007-03-28 17:38:21 +0000744 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000745 return;
746 }
747 case Instruction::Shl:
748 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
749 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +0000750 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencerd8aad612007-03-25 02:03:12 +0000751 APInt Mask2(Mask.lshr(ShiftAmt));
752 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000753 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Shengb3e00c42007-03-12 05:44:52 +0000754 KnownZero <<= ShiftAmt;
755 KnownOne <<= ShiftAmt;
Reid Spencer624766f2007-03-25 19:55:33 +0000756 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spenceraa696402007-03-08 01:46:38 +0000757 return;
758 }
759 break;
760 case Instruction::LShr:
761 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
762 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
763 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000764 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000765
766 // Unsigned shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000767 APInt Mask2(Mask.shl(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000769 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
770 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
771 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Sheng57e3f732007-03-28 02:19:03 +0000772 // high bits known zero.
773 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spenceraa696402007-03-08 01:46:38 +0000774 return;
775 }
776 break;
777 case Instruction::AShr:
Zhou Sheng57e3f732007-03-28 02:19:03 +0000778 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spenceraa696402007-03-08 01:46:38 +0000779 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780 // Compute the new bits that are at the top now.
Zhou Shengb25806f2007-03-30 09:29:48 +0000781 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spenceraa696402007-03-08 01:46:38 +0000782
783 // Signed shift right.
Reid Spencerd8aad612007-03-25 02:03:12 +0000784 APInt Mask2(Mask.shl(ShiftAmt));
785 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spenceraa696402007-03-08 01:46:38 +0000786 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
787 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
789
Zhou Sheng57e3f732007-03-28 02:19:03 +0000790 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
791 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spenceraa696402007-03-08 01:46:38 +0000792 KnownZero |= HighBits;
Zhou Sheng57e3f732007-03-28 02:19:03 +0000793 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spenceraa696402007-03-08 01:46:38 +0000794 KnownOne |= HighBits;
Reid Spenceraa696402007-03-08 01:46:38 +0000795 return;
796 }
797 break;
798 }
799}
800
Reid Spencerbb5741f2007-03-08 01:52:58 +0000801/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
802/// this predicate to simplify operations downstream. Mask is known to be zero
803/// for bits that V cannot have.
804static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengbe171ee2007-03-12 16:54:56 +0000805 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencerbb5741f2007-03-08 01:52:58 +0000806 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
807 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
808 return (KnownZero & Mask) == Mask;
809}
810
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811/// ShrinkDemandedConstant - Check to see if the specified operand of the
812/// specified instruction is a constant integer. If so, check to see if there
813/// are any bits set in the constant that are not demanded. If so, shrink the
814/// constant and return true.
815static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencerd9281782007-03-12 17:15:10 +0000816 APInt Demanded) {
817 assert(I && "No instruction?");
818 assert(OpNo < I->getNumOperands() && "Operand index too large");
819
820 // If the operand is not a constant integer, nothing to do.
821 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
822 if (!OpC) return false;
823
824 // If there are no bits set that aren't demanded, nothing to do.
825 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
826 if ((~Demanded & OpC->getValue()) == 0)
827 return false;
828
829 // This instruction is producing bits that are not demanded. Shrink the RHS.
830 Demanded &= OpC->getValue();
831 I->setOperand(OpNo, ConstantInt::get(Demanded));
832 return true;
833}
834
Chris Lattneree0f2802006-02-12 02:07:56 +0000835// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
836// set of known zero and one bits, compute the maximum and minimum values that
837// could have the specified known zero and known one bits, returning them in
838// min/max.
839static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000840 const APInt& KnownZero,
841 const APInt& KnownOne,
842 APInt& Min, APInt& Max) {
843 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
844 assert(KnownZero.getBitWidth() == BitWidth &&
845 KnownOne.getBitWidth() == BitWidth &&
846 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
847 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000848 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000849
Chris Lattneree0f2802006-02-12 02:07:56 +0000850 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
851 // bit if it is unknown.
852 Min = KnownOne;
853 Max = KnownOne|UnknownBits;
854
Zhou Shengc2d33092007-03-28 05:15:57 +0000855 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng9bc8ab12007-04-02 13:45:30 +0000856 Min.set(BitWidth-1);
857 Max.clear(BitWidth-1);
Chris Lattneree0f2802006-02-12 02:07:56 +0000858 }
Chris Lattneree0f2802006-02-12 02:07:56 +0000859}
860
861// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
862// a set of known zero and one bits, compute the maximum and minimum values that
863// could have the specified known zero and known one bits, returning them in
864// min/max.
865static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencerc3e3b8a2007-03-22 20:36:03 +0000866 const APInt& KnownZero,
867 const APInt& KnownOne,
868 APInt& Min,
869 APInt& Max) {
870 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
871 assert(KnownZero.getBitWidth() == BitWidth &&
872 KnownOne.getBitWidth() == BitWidth &&
873 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
874 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencercd99fbd2007-03-25 04:26:16 +0000875 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattneree0f2802006-02-12 02:07:56 +0000876
877 // The minimum value is when the unknown bits are all zeros.
878 Min = KnownOne;
879 // The maximum value is when the unknown bits are all ones.
880 Max = KnownOne|UnknownBits;
881}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882
Reid Spencer1791f232007-03-12 17:25:59 +0000883/// SimplifyDemandedBits - This function attempts to replace V with a simpler
884/// value based on the demanded bits. When this function is called, it is known
885/// that only the bits set in DemandedMask of the result of V are ever used
886/// downstream. Consequently, depending on the mask and V, it may be possible
887/// to replace V with a constant or one of its operands. In such cases, this
888/// function does the replacement and returns true. In all other cases, it
889/// returns false after analyzing the expression and setting KnownOne and known
890/// to be one in the expression. KnownZero contains all the bits that are known
891/// to be zero in the expression. These are provided to potentially allow the
892/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
893/// the expression. KnownOne and KnownZero always follow the invariant that
894/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
895/// the bits in KnownOne and KnownZero may only be accurate for those bits set
896/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
897/// and KnownOne must all be the same.
898bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
899 APInt& KnownZero, APInt& KnownOne,
900 unsigned Depth) {
901 assert(V != 0 && "Null pointer of Value???");
902 assert(Depth <= 6 && "Limit Search Depth");
903 uint32_t BitWidth = DemandedMask.getBitWidth();
904 const IntegerType *VTy = cast<IntegerType>(V->getType());
905 assert(VTy->getBitWidth() == BitWidth &&
906 KnownZero.getBitWidth() == BitWidth &&
907 KnownOne.getBitWidth() == BitWidth &&
908 "Value *V, DemandedMask, KnownZero and KnownOne \
909 must have same BitWidth");
910 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
911 // We know all of the bits for a constant!
912 KnownOne = CI->getValue() & DemandedMask;
913 KnownZero = ~KnownOne & DemandedMask;
914 return false;
915 }
916
Zhou Shengb9128442007-03-14 03:21:24 +0000917 KnownZero.clear();
918 KnownOne.clear();
Reid Spencer1791f232007-03-12 17:25:59 +0000919 if (!V->hasOneUse()) { // Other users may use these bits.
920 if (Depth != 0) { // Not at the root.
921 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
922 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
923 return false;
924 }
925 // If this is the root being simplified, allow it to have multiple uses,
926 // just set the DemandedMask to all bits.
927 DemandedMask = APInt::getAllOnesValue(BitWidth);
928 } else if (DemandedMask == 0) { // Not demanding any bits from V.
929 if (V != UndefValue::get(VTy))
930 return UpdateValueUsesWith(V, UndefValue::get(VTy));
931 return false;
932 } else if (Depth == 6) { // Limit search depth.
933 return false;
934 }
935
936 Instruction *I = dyn_cast<Instruction>(V);
937 if (!I) return false; // Only analyze instructions.
938
Reid Spencer1791f232007-03-12 17:25:59 +0000939 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
940 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
941 switch (I->getOpcode()) {
942 default: break;
943 case Instruction::And:
944 // If either the LHS or the RHS are Zero, the result is zero.
945 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1))
947 return true;
948 assert((RHSKnownZero & RHSKnownOne) == 0 &&
949 "Bits known to be one AND zero?");
950
951 // If something is known zero on the RHS, the bits aren't demanded on the
952 // LHS.
953 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
954 LHSKnownZero, LHSKnownOne, Depth+1))
955 return true;
956 assert((LHSKnownZero & LHSKnownOne) == 0 &&
957 "Bits known to be one AND zero?");
958
959 // If all of the demanded bits are known 1 on one side, return the other.
960 // These bits cannot contribute to the result of the 'and'.
961 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
962 (DemandedMask & ~LHSKnownZero))
963 return UpdateValueUsesWith(I, I->getOperand(0));
964 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
965 (DemandedMask & ~RHSKnownZero))
966 return UpdateValueUsesWith(I, I->getOperand(1));
967
968 // If all of the demanded bits in the inputs are known zeros, return zero.
969 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
970 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
971
972 // If the RHS is a constant, see if we can simplify it.
973 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
974 return UpdateValueUsesWith(I, I);
975
976 // Output known-1 bits are only known if set in both the LHS & RHS.
977 RHSKnownOne &= LHSKnownOne;
978 // Output known-0 are known to be clear if zero in either the LHS | RHS.
979 RHSKnownZero |= LHSKnownZero;
980 break;
981 case Instruction::Or:
982 // If either the LHS or the RHS are One, the result is One.
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 RHSKnownZero, RHSKnownOne, Depth+1))
985 return true;
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988 // If something is known one on the RHS, the bits aren't demanded on the
989 // LHS.
990 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
991 LHSKnownZero, LHSKnownOne, Depth+1))
992 return true;
993 assert((LHSKnownZero & LHSKnownOne) == 0 &&
994 "Bits known to be one AND zero?");
995
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'or'.
998 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
999 (DemandedMask & ~LHSKnownOne))
1000 return UpdateValueUsesWith(I, I->getOperand(0));
1001 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1002 (DemandedMask & ~RHSKnownOne))
1003 return UpdateValueUsesWith(I, I->getOperand(1));
1004
1005 // If all of the potentially set bits on one side are known to be set on
1006 // the other side, just use the 'other' side.
1007 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1008 (DemandedMask & (~RHSKnownZero)))
1009 return UpdateValueUsesWith(I, I->getOperand(0));
1010 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1011 (DemandedMask & (~LHSKnownZero)))
1012 return UpdateValueUsesWith(I, I->getOperand(1));
1013
1014 // If the RHS is a constant, see if we can simplify it.
1015 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1016 return UpdateValueUsesWith(I, I);
1017
1018 // Output known-0 bits are only known if clear in both the LHS & RHS.
1019 RHSKnownZero &= LHSKnownZero;
1020 // Output known-1 are known to be set if set in either the LHS | RHS.
1021 RHSKnownOne |= LHSKnownOne;
1022 break;
1023 case Instruction::Xor: {
1024 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1025 RHSKnownZero, RHSKnownOne, Depth+1))
1026 return true;
1027 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1028 "Bits known to be one AND zero?");
1029 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1030 LHSKnownZero, LHSKnownOne, Depth+1))
1031 return true;
1032 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1033 "Bits known to be one AND zero?");
1034
1035 // If all of the demanded bits are known zero on one side, return the other.
1036 // These bits cannot contribute to the result of the 'xor'.
1037 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1038 return UpdateValueUsesWith(I, I->getOperand(0));
1039 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1040 return UpdateValueUsesWith(I, I->getOperand(1));
1041
1042 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1043 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1044 (RHSKnownOne & LHSKnownOne);
1045 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1046 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1047 (RHSKnownOne & LHSKnownZero);
1048
1049 // If all of the demanded bits are known to be zero on one side or the
1050 // other, turn this into an *inclusive* or.
1051 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1052 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1053 Instruction *Or =
1054 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1055 I->getName());
1056 InsertNewInstBefore(Or, *I);
1057 return UpdateValueUsesWith(I, Or);
1058 }
1059
1060 // If all of the demanded bits on one side are known, and all of the set
1061 // bits on that side are also known to be set on the other side, turn this
1062 // into an AND, as we know the bits will be cleared.
1063 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1064 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1065 // all known
1066 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1067 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1068 Instruction *And =
1069 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1070 InsertNewInstBefore(And, *I);
1071 return UpdateValueUsesWith(I, And);
1072 }
1073 }
1074
1075 // If the RHS is a constant, see if we can simplify it.
1076 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1077 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1078 return UpdateValueUsesWith(I, I);
1079
1080 RHSKnownZero = KnownZeroOut;
1081 RHSKnownOne = KnownOneOut;
1082 break;
1083 }
1084 case Instruction::Select:
1085 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1086 RHSKnownZero, RHSKnownOne, Depth+1))
1087 return true;
1088 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1089 LHSKnownZero, LHSKnownOne, Depth+1))
1090 return true;
1091 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1092 "Bits known to be one AND zero?");
1093 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1094 "Bits known to be one AND zero?");
1095
1096 // If the operands are constants, see if we can simplify them.
1097 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1098 return UpdateValueUsesWith(I, I);
1099 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1100 return UpdateValueUsesWith(I, I);
1101
1102 // Only known if known in both the LHS and RHS.
1103 RHSKnownOne &= LHSKnownOne;
1104 RHSKnownZero &= LHSKnownZero;
1105 break;
1106 case Instruction::Trunc: {
1107 uint32_t truncBf =
1108 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shenga4475572007-03-29 02:26:30 +00001109 DemandedMask.zext(truncBf);
1110 RHSKnownZero.zext(truncBf);
1111 RHSKnownOne.zext(truncBf);
1112 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1113 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001114 return true;
1115 DemandedMask.trunc(BitWidth);
1116 RHSKnownZero.trunc(BitWidth);
1117 RHSKnownOne.trunc(BitWidth);
1118 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1119 "Bits known to be one AND zero?");
1120 break;
1121 }
1122 case Instruction::BitCast:
1123 if (!I->getOperand(0)->getType()->isInteger())
1124 return false;
1125
1126 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1127 RHSKnownZero, RHSKnownOne, Depth+1))
1128 return true;
1129 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1130 "Bits known to be one AND zero?");
1131 break;
1132 case Instruction::ZExt: {
1133 // Compute the bits in the result that are not present in the input.
1134 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001135 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001136
Zhou Sheng444af492007-03-29 04:45:55 +00001137 DemandedMask.trunc(SrcBitWidth);
1138 RHSKnownZero.trunc(SrcBitWidth);
1139 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001140 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001142 return true;
1143 DemandedMask.zext(BitWidth);
1144 RHSKnownZero.zext(BitWidth);
1145 RHSKnownOne.zext(BitWidth);
1146 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1147 "Bits known to be one AND zero?");
1148 // The top bits are known to be zero.
Zhou Shenga4475572007-03-29 02:26:30 +00001149 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001150 break;
1151 }
1152 case Instruction::SExt: {
1153 // Compute the bits in the result that are not present in the input.
1154 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencercd99fbd2007-03-25 04:26:16 +00001155 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer1791f232007-03-12 17:25:59 +00001156
Reid Spencer1791f232007-03-12 17:25:59 +00001157 APInt InputDemandedBits = DemandedMask &
Zhou Shenga4475572007-03-29 02:26:30 +00001158 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001159
Zhou Shenga4475572007-03-29 02:26:30 +00001160 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer1791f232007-03-12 17:25:59 +00001161 // If any of the sign extended bits are demanded, we know that the sign
1162 // bit is demanded.
1163 if ((NewBits & DemandedMask) != 0)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00001164 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer1791f232007-03-12 17:25:59 +00001165
Zhou Sheng444af492007-03-29 04:45:55 +00001166 InputDemandedBits.trunc(SrcBitWidth);
1167 RHSKnownZero.trunc(SrcBitWidth);
1168 RHSKnownOne.trunc(SrcBitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001169 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1170 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer1791f232007-03-12 17:25:59 +00001171 return true;
1172 InputDemandedBits.zext(BitWidth);
1173 RHSKnownZero.zext(BitWidth);
1174 RHSKnownOne.zext(BitWidth);
1175 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1176 "Bits known to be one AND zero?");
1177
1178 // If the sign bit of the input is known set or clear, then we know the
1179 // top bits of the result.
1180
1181 // If the input sign bit is known zero, or if the NewBits are not demanded
1182 // convert this into a zero extension.
Zhou Shenga4475572007-03-29 02:26:30 +00001183 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer1791f232007-03-12 17:25:59 +00001184 {
1185 // Convert to ZExt cast
1186 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1187 return UpdateValueUsesWith(I, NewCast);
Zhou Shenga4475572007-03-29 02:26:30 +00001188 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer1791f232007-03-12 17:25:59 +00001189 RHSKnownOne |= NewBits;
Reid Spencer1791f232007-03-12 17:25:59 +00001190 }
1191 break;
1192 }
1193 case Instruction::Add: {
1194 // Figure out what the input bits are. If the top bits of the and result
1195 // are not demanded, then the add doesn't demand them from its input
1196 // either.
Reid Spencer52830322007-03-25 21:11:44 +00001197 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer1791f232007-03-12 17:25:59 +00001198
1199 // If there is a constant on the RHS, there are a variety of xformations
1200 // we can do.
1201 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1202 // If null, this should be simplified elsewhere. Some of the xforms here
1203 // won't work if the RHS is zero.
1204 if (RHS->isZero())
1205 break;
1206
1207 // If the top bit of the output is demanded, demand everything from the
1208 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Shenga4475572007-03-29 02:26:30 +00001209 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001210
1211 // Find information about known zero/one bits in the input.
1212 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1213 LHSKnownZero, LHSKnownOne, Depth+1))
1214 return true;
1215
1216 // If the RHS of the add has bits set that can't affect the input, reduce
1217 // the constant.
1218 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1219 return UpdateValueUsesWith(I, I);
1220
1221 // Avoid excess work.
1222 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1223 break;
1224
1225 // Turn it into OR if input bits are zero.
1226 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1227 Instruction *Or =
1228 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1229 I->getName());
1230 InsertNewInstBefore(Or, *I);
1231 return UpdateValueUsesWith(I, Or);
1232 }
1233
1234 // We can say something about the output known-zero and known-one bits,
1235 // depending on potential carries from the input constant and the
1236 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1237 // bits set and the RHS constant is 0x01001, then we know we have a known
1238 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1239
1240 // To compute this, we first compute the potential carry bits. These are
1241 // the bits which may be modified. I'm not aware of a better way to do
1242 // this scan.
Zhou Sheng4f164022007-03-31 02:38:39 +00001243 const APInt& RHSVal = RHS->getValue();
1244 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer1791f232007-03-12 17:25:59 +00001245
1246 // Now that we know which bits have carries, compute the known-1/0 sets.
1247
1248 // Bits are known one if they are known zero in one operand and one in the
1249 // other, and there is no input carry.
1250 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1251 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1252
1253 // Bits are known zero if they are known zero in both operands and there
1254 // is no input carry.
1255 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1256 } else {
1257 // If the high-bits of this ADD are not demanded, then it does not demand
1258 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001259 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001260 // Right fill the mask of bits for this ADD to demand the most
1261 // significant bit and all those below it.
Zhou Shenga4475572007-03-29 02:26:30 +00001262 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001263 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1265 return true;
1266 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1267 LHSKnownZero, LHSKnownOne, Depth+1))
1268 return true;
1269 }
1270 }
1271 break;
1272 }
1273 case Instruction::Sub:
1274 // If the high-bits of this SUB are not demanded, then it does not demand
1275 // the high bits of its LHS or RHS.
Zhou Shenga4475572007-03-29 02:26:30 +00001276 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer1791f232007-03-12 17:25:59 +00001277 // Right fill the mask of bits for this SUB to demand the most
1278 // significant bit and all those below it.
Zhou Sheng56cda952007-04-02 08:20:41 +00001279 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Shenga4475572007-03-29 02:26:30 +00001280 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer1791f232007-03-12 17:25:59 +00001281 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1282 LHSKnownZero, LHSKnownOne, Depth+1))
1283 return true;
1284 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1285 LHSKnownZero, LHSKnownOne, Depth+1))
1286 return true;
1287 }
1288 break;
1289 case Instruction::Shl:
1290 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001291 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Shenga4475572007-03-29 02:26:30 +00001292 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1293 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001294 RHSKnownZero, RHSKnownOne, Depth+1))
1295 return true;
1296 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1297 "Bits known to be one AND zero?");
1298 RHSKnownZero <<= ShiftAmt;
1299 RHSKnownOne <<= ShiftAmt;
1300 // low bits known zero.
Zhou Shengd8c645b2007-03-14 09:07:33 +00001301 if (ShiftAmt)
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00001302 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer1791f232007-03-12 17:25:59 +00001303 }
1304 break;
1305 case Instruction::LShr:
1306 // For a logical shift right
1307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00001308 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001309
Reid Spencer1791f232007-03-12 17:25:59 +00001310 // Unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001311 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1312 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001313 RHSKnownZero, RHSKnownOne, Depth+1))
1314 return true;
1315 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1316 "Bits known to be one AND zero?");
Reid Spencer1791f232007-03-12 17:25:59 +00001317 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengd8c645b2007-03-14 09:07:33 +00001319 if (ShiftAmt) {
1320 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001321 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengd8c645b2007-03-14 09:07:33 +00001322 RHSKnownZero |= HighBits; // high bits known zero.
1323 }
Reid Spencer1791f232007-03-12 17:25:59 +00001324 }
1325 break;
1326 case Instruction::AShr:
1327 // If this is an arithmetic shift right and only the low-bit is set, we can
1328 // always convert this into a logical shr, even if the shift amount is
1329 // variable. The low bit of the shift cannot be an input sign bit unless
1330 // the shift amount is >= the size of the datatype, which is undefined.
1331 if (DemandedMask == 1) {
1332 // Perform the logical shift right.
1333 Value *NewVal = BinaryOperator::createLShr(
1334 I->getOperand(0), I->getOperand(1), I->getName());
1335 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1336 return UpdateValueUsesWith(I, NewVal);
1337 }
1338
1339 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00001340 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer1791f232007-03-12 17:25:59 +00001341
Reid Spencer1791f232007-03-12 17:25:59 +00001342 // Signed shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001343 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001344 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Shenga4475572007-03-29 02:26:30 +00001345 DemandedMaskIn,
Reid Spencer1791f232007-03-12 17:25:59 +00001346 RHSKnownZero, RHSKnownOne, Depth+1))
1347 return true;
1348 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350 // Compute the new bits that are at the top now.
Zhou Shenga4475572007-03-29 02:26:30 +00001351 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer1791f232007-03-12 17:25:59 +00001352 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1353 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1354
1355 // Handle the sign bits.
1356 APInt SignBit(APInt::getSignBit(BitWidth));
1357 // Adjust to where it is now in the mask.
1358 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1359
1360 // If the input sign bit is known to be zero, or if none of the top bits
1361 // are demanded, turn this into an unsigned shift right.
Zhou Shenga4475572007-03-29 02:26:30 +00001362 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer1791f232007-03-12 17:25:59 +00001363 (HighBits & ~DemandedMask) == HighBits) {
1364 // Perform the logical shift right.
1365 Value *NewVal = BinaryOperator::createLShr(
1366 I->getOperand(0), SA, I->getName());
1367 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1368 return UpdateValueUsesWith(I, NewVal);
1369 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1370 RHSKnownOne |= HighBits;
1371 }
1372 }
1373 break;
1374 }
1375
1376 // If the client is only demanding bits that we know, return the known
1377 // constant.
1378 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1379 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1380 return false;
1381}
1382
Chris Lattner2deeaea2006-10-05 06:55:50 +00001383
1384/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1385/// 64 or fewer elements. DemandedElts contains the set of elements that are
1386/// actually used by the caller. This method analyzes which elements of the
1387/// operand are undef and returns that information in UndefElts.
1388///
1389/// If the information about demanded elements can be used to simplify the
1390/// operation, the operation is simplified, then the resultant value is
1391/// returned. This returns null if no change was made.
1392Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1393 uint64_t &UndefElts,
1394 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001395 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001396 assert(VWidth <= 64 && "Vector too wide to analyze!");
1397 uint64_t EltMask = ~0ULL >> (64-VWidth);
1398 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1399 "Invalid DemandedElts!");
1400
1401 if (isa<UndefValue>(V)) {
1402 // If the entire vector is undefined, just return this info.
1403 UndefElts = EltMask;
1404 return 0;
1405 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1406 UndefElts = EltMask;
1407 return UndefValue::get(V->getType());
1408 }
1409
1410 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001411 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1412 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001413 Constant *Undef = UndefValue::get(EltTy);
1414
1415 std::vector<Constant*> Elts;
1416 for (unsigned i = 0; i != VWidth; ++i)
1417 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1418 Elts.push_back(Undef);
1419 UndefElts |= (1ULL << i);
1420 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1421 Elts.push_back(Undef);
1422 UndefElts |= (1ULL << i);
1423 } else { // Otherwise, defined.
1424 Elts.push_back(CP->getOperand(i));
1425 }
1426
1427 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001428 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001429 return NewCP != CP ? NewCP : 0;
1430 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001431 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001432 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001433 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001434 Constant *Zero = Constant::getNullValue(EltTy);
1435 Constant *Undef = UndefValue::get(EltTy);
1436 std::vector<Constant*> Elts;
1437 for (unsigned i = 0; i != VWidth; ++i)
1438 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1439 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001440 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001441 }
1442
1443 if (!V->hasOneUse()) { // Other users may use these bits.
1444 if (Depth != 0) { // Not at the root.
1445 // TODO: Just compute the UndefElts information recursively.
1446 return false;
1447 }
1448 return false;
1449 } else if (Depth == 10) { // Limit search depth.
1450 return false;
1451 }
1452
1453 Instruction *I = dyn_cast<Instruction>(V);
1454 if (!I) return false; // Only analyze instructions.
1455
1456 bool MadeChange = false;
1457 uint64_t UndefElts2;
1458 Value *TmpV;
1459 switch (I->getOpcode()) {
1460 default: break;
1461
1462 case Instruction::InsertElement: {
1463 // If this is a variable index, we don't know which element it overwrites.
1464 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001465 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001466 if (Idx == 0) {
1467 // Note that we can't propagate undef elt info, because we don't know
1468 // which elt is getting updated.
1469 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1470 UndefElts2, Depth+1);
1471 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1472 break;
1473 }
1474
1475 // If this is inserting an element that isn't demanded, remove this
1476 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001477 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001478 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1479 return AddSoonDeadInstToWorklist(*I, 0);
1480
1481 // Otherwise, the element inserted overwrites whatever was there, so the
1482 // input demanded set is simpler than the output set.
1483 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1484 DemandedElts & ~(1ULL << IdxNo),
1485 UndefElts, Depth+1);
1486 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1487
1488 // The inserted element is defined.
1489 UndefElts |= 1ULL << IdxNo;
1490 break;
1491 }
1492
1493 case Instruction::And:
1494 case Instruction::Or:
1495 case Instruction::Xor:
1496 case Instruction::Add:
1497 case Instruction::Sub:
1498 case Instruction::Mul:
1499 // div/rem demand all inputs, because they don't want divide by zero.
1500 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1501 UndefElts, Depth+1);
1502 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1503 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1504 UndefElts2, Depth+1);
1505 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1506
1507 // Output elements are undefined if both are undefined. Consider things
1508 // like undef&0. The result is known zero, not undef.
1509 UndefElts &= UndefElts2;
1510 break;
1511
1512 case Instruction::Call: {
1513 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1514 if (!II) break;
1515 switch (II->getIntrinsicID()) {
1516 default: break;
1517
1518 // Binary vector operations that work column-wise. A dest element is a
1519 // function of the corresponding input elements from the two inputs.
1520 case Intrinsic::x86_sse_sub_ss:
1521 case Intrinsic::x86_sse_mul_ss:
1522 case Intrinsic::x86_sse_min_ss:
1523 case Intrinsic::x86_sse_max_ss:
1524 case Intrinsic::x86_sse2_sub_sd:
1525 case Intrinsic::x86_sse2_mul_sd:
1526 case Intrinsic::x86_sse2_min_sd:
1527 case Intrinsic::x86_sse2_max_sd:
1528 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1529 UndefElts, Depth+1);
1530 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1531 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1532 UndefElts2, Depth+1);
1533 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1534
1535 // If only the low elt is demanded and this is a scalarizable intrinsic,
1536 // scalarize it now.
1537 if (DemandedElts == 1) {
1538 switch (II->getIntrinsicID()) {
1539 default: break;
1540 case Intrinsic::x86_sse_sub_ss:
1541 case Intrinsic::x86_sse_mul_ss:
1542 case Intrinsic::x86_sse2_sub_sd:
1543 case Intrinsic::x86_sse2_mul_sd:
1544 // TODO: Lower MIN/MAX/ABS/etc
1545 Value *LHS = II->getOperand(1);
1546 Value *RHS = II->getOperand(2);
1547 // Extract the element as scalars.
1548 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1549 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1550
1551 switch (II->getIntrinsicID()) {
1552 default: assert(0 && "Case stmts out of sync!");
1553 case Intrinsic::x86_sse_sub_ss:
1554 case Intrinsic::x86_sse2_sub_sd:
1555 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1556 II->getName()), *II);
1557 break;
1558 case Intrinsic::x86_sse_mul_ss:
1559 case Intrinsic::x86_sse2_mul_sd:
1560 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1561 II->getName()), *II);
1562 break;
1563 }
1564
1565 Instruction *New =
1566 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1567 II->getName());
1568 InsertNewInstBefore(New, *II);
1569 AddSoonDeadInstToWorklist(*II, 0);
1570 return New;
1571 }
1572 }
1573
1574 // Output elements are undefined if both are undefined. Consider things
1575 // like undef&0. The result is known zero, not undef.
1576 UndefElts &= UndefElts2;
1577 break;
1578 }
1579 break;
1580 }
1581 }
1582 return MadeChange ? I : 0;
1583}
1584
Reid Spencer266e42b2006-12-23 06:05:41 +00001585/// @returns true if the specified compare instruction is
1586/// true when both operands are equal...
1587/// @brief Determine if the ICmpInst returns true if both operands are equal
1588static bool isTrueWhenEqual(ICmpInst &ICI) {
1589 ICmpInst::Predicate pred = ICI.getPredicate();
1590 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1591 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1592 pred == ICmpInst::ICMP_SLE;
1593}
1594
Chris Lattnerb8b97502003-08-13 19:01:45 +00001595/// AssociativeOpt - Perform an optimization on an associative operator. This
1596/// function is designed to check a chain of associative operators for a
1597/// potential to apply a certain optimization. Since the optimization may be
1598/// applicable if the expression was reassociated, this checks the chain, then
1599/// reassociates the expression as necessary to expose the optimization
1600/// opportunity. This makes use of a special Functor, which must define
1601/// 'shouldApply' and 'apply' methods.
1602///
1603template<typename Functor>
1604Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1605 unsigned Opcode = Root.getOpcode();
1606 Value *LHS = Root.getOperand(0);
1607
1608 // Quick check, see if the immediate LHS matches...
1609 if (F.shouldApply(LHS))
1610 return F.apply(Root);
1611
1612 // Otherwise, if the LHS is not of the same opcode as the root, return.
1613 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001614 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001615 // Should we apply this transform to the RHS?
1616 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1617
1618 // If not to the RHS, check to see if we should apply to the LHS...
1619 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1620 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1621 ShouldApply = true;
1622 }
1623
1624 // If the functor wants to apply the optimization to the RHS of LHSI,
1625 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1626 if (ShouldApply) {
1627 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001628
Chris Lattnerb8b97502003-08-13 19:01:45 +00001629 // Now all of the instructions are in the current basic block, go ahead
1630 // and perform the reassociation.
1631 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1632
1633 // First move the selected RHS to the LHS of the root...
1634 Root.setOperand(0, LHSI->getOperand(1));
1635
1636 // Make what used to be the LHS of the root be the user of the root...
1637 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001638 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001639 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1640 return 0;
1641 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001642 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001643 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001644 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1645 BasicBlock::iterator ARI = &Root; ++ARI;
1646 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1647 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001648
1649 // Now propagate the ExtraOperand down the chain of instructions until we
1650 // get to LHSI.
1651 while (TmpLHSI != LHSI) {
1652 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001653 // Move the instruction to immediately before the chain we are
1654 // constructing to avoid breaking dominance properties.
1655 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1656 BB->getInstList().insert(ARI, NextLHSI);
1657 ARI = NextLHSI;
1658
Chris Lattnerb8b97502003-08-13 19:01:45 +00001659 Value *NextOp = NextLHSI->getOperand(1);
1660 NextLHSI->setOperand(1, ExtraOperand);
1661 TmpLHSI = NextLHSI;
1662 ExtraOperand = NextOp;
1663 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001664
Chris Lattnerb8b97502003-08-13 19:01:45 +00001665 // Now that the instructions are reassociated, have the functor perform
1666 // the transformation...
1667 return F.apply(Root);
1668 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001669
Chris Lattnerb8b97502003-08-13 19:01:45 +00001670 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1671 }
1672 return 0;
1673}
1674
1675
1676// AddRHS - Implements: X + X --> X << 1
1677struct AddRHS {
1678 Value *RHS;
1679 AddRHS(Value *rhs) : RHS(rhs) {}
1680 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1681 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001682 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001683 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001684 }
1685};
1686
1687// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1688// iff C1&C2 == 0
1689struct AddMaskingAnd {
1690 Constant *C2;
1691 AddMaskingAnd(Constant *c) : C2(c) {}
1692 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001693 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001694 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001695 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001696 }
1697 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001698 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001699 }
1700};
1701
Chris Lattner86102b82005-01-01 16:22:27 +00001702static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001703 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001704 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001705 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001706 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001707
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708 return IC->InsertNewInstBefore(CastInst::create(
1709 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001710 }
1711
Chris Lattner183b3362004-04-09 19:05:30 +00001712 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001713 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1714 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001715
Chris Lattner183b3362004-04-09 19:05:30 +00001716 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1717 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001718 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1719 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001720 }
1721
1722 Value *Op0 = SO, *Op1 = ConstOperand;
1723 if (!ConstIsRHS)
1724 std::swap(Op0, Op1);
1725 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001726 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1727 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001728 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1729 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1730 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001731 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001732 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001733 abort();
1734 }
Chris Lattner86102b82005-01-01 16:22:27 +00001735 return IC->InsertNewInstBefore(New, I);
1736}
1737
1738// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1739// constant as the other operand, try to fold the binary operator into the
1740// select arguments. This also works for Cast instructions, which obviously do
1741// not have a second operand.
1742static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1743 InstCombiner *IC) {
1744 // Don't modify shared select instructions
1745 if (!SI->hasOneUse()) return 0;
1746 Value *TV = SI->getOperand(1);
1747 Value *FV = SI->getOperand(2);
1748
1749 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001750 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001751 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001752
Chris Lattner86102b82005-01-01 16:22:27 +00001753 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1754 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1755
1756 return new SelectInst(SI->getCondition(), SelectTrueVal,
1757 SelectFalseVal);
1758 }
1759 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001760}
1761
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001762
1763/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1764/// node as operand #0, see if we can fold the instruction into the PHI (which
1765/// is only possible if all operands to the PHI are constants).
1766Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1767 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001768 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001769 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001770
Chris Lattner04689872006-09-09 22:02:56 +00001771 // Check to see if all of the operands of the PHI are constants. If there is
1772 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001773 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001774 BasicBlock *NonConstBB = 0;
1775 for (unsigned i = 0; i != NumPHIValues; ++i)
1776 if (!isa<Constant>(PN->getIncomingValue(i))) {
1777 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001778 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001779 NonConstBB = PN->getIncomingBlock(i);
1780
1781 // If the incoming non-constant value is in I's block, we have an infinite
1782 // loop.
1783 if (NonConstBB == I.getParent())
1784 return 0;
1785 }
1786
1787 // If there is exactly one non-constant value, we can insert a copy of the
1788 // operation in that block. However, if this is a critical edge, we would be
1789 // inserting the computation one some other paths (e.g. inside a loop). Only
1790 // do this if the pred block is unconditionally branching into the phi block.
1791 if (NonConstBB) {
1792 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1793 if (!BI || !BI->isUnconditional()) return 0;
1794 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001795
1796 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001797 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001798 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001799 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001800 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001801
1802 // Next, add all of the operands to the PHI.
1803 if (I.getNumOperands() == 2) {
1804 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001805 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001806 Value *InV;
1807 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001808 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1809 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1810 else
1811 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001812 } else {
1813 assert(PN->getIncomingBlock(i) == NonConstBB);
1814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1815 InV = BinaryOperator::create(BO->getOpcode(),
1816 PN->getIncomingValue(i), C, "phitmp",
1817 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001818 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1819 InV = CmpInst::create(CI->getOpcode(),
1820 CI->getPredicate(),
1821 PN->getIncomingValue(i), C, "phitmp",
1822 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001823 else
1824 assert(0 && "Unknown binop!");
1825
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001826 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001827 }
1828 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001829 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001830 } else {
1831 CastInst *CI = cast<CastInst>(&I);
1832 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001833 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001834 Value *InV;
1835 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001836 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001837 } else {
1838 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001839 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1840 I.getType(), "phitmp",
1841 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001842 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001843 }
1844 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001845 }
1846 }
1847 return ReplaceInstUsesWith(I, NewPN);
1848}
1849
Chris Lattner113f4f42002-06-25 16:13:24 +00001850Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001851 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001852 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001853
Chris Lattnercf4a9962004-04-10 22:01:55 +00001854 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001855 // X + undef -> undef
1856 if (isa<UndefValue>(RHS))
1857 return ReplaceInstUsesWith(I, RHS);
1858
Chris Lattnercf4a9962004-04-10 22:01:55 +00001859 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001860 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001861 if (RHSC->isNullValue())
1862 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001863 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1864 if (CFP->isExactlyValue(-0.0))
1865 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001866 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001867
Chris Lattnercf4a9962004-04-10 22:01:55 +00001868 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001869 // X + (signbit) --> X ^ signbit
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001870 const APInt& Val = CI->getValue();
Zhou Sheng56cda952007-04-02 08:20:41 +00001871 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer959a21d2007-03-23 21:24:59 +00001872 if (Val == APInt::getSignBit(BitWidth))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001873 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001874
1875 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1876 // (X & 254)+1 -> (X&254)|1
Reid Spencer959a21d2007-03-23 21:24:59 +00001877 if (!isa<VectorType>(I.getType())) {
1878 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1879 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1880 KnownZero, KnownOne))
1881 return &I;
1882 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001883 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001884
1885 if (isa<PHINode>(LHS))
1886 if (Instruction *NV = FoldOpIntoPhi(I))
1887 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001888
Chris Lattner330628a2006-01-06 17:59:59 +00001889 ConstantInt *XorRHS = 0;
1890 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001891 if (isa<ConstantInt>(RHSC) &&
1892 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng56cda952007-04-02 08:20:41 +00001893 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001894 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner0b3557f2005-09-24 23:43:33 +00001895
Zhou Sheng56cda952007-04-02 08:20:41 +00001896 uint32_t Size = TySizeBits / 2;
Reid Spencer959a21d2007-03-23 21:24:59 +00001897 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1898 APInt CFF80Val(-C0080Val);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001899 do {
1900 if (TySizeBits > Size) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001901 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1902 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer959a21d2007-03-23 21:24:59 +00001903 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1904 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001905 // This is a sign extend if the top bits are known zero.
Zhou Shengb3a80b12007-03-29 08:15:12 +00001906 if (!MaskedValueIsZero(XorLHS,
1907 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001908 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer959a21d2007-03-23 21:24:59 +00001909 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001910 }
1911 }
1912 Size >>= 1;
Reid Spencer959a21d2007-03-23 21:24:59 +00001913 C0080Val = APIntOps::lshr(C0080Val, Size);
1914 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1915 } while (Size >= 1);
Chris Lattner0b3557f2005-09-24 23:43:33 +00001916
Reid Spencera5c18bf2007-03-28 01:36:16 +00001917 // FIXME: This shouldn't be necessary. When the backends can handle types
1918 // with funny bit widths then this whole cascade of if statements should
1919 // be removed. It is just here to get the size of the "middle" type back
1920 // up to something that the back ends can handle.
1921 const Type *MiddleType = 0;
1922 switch (Size) {
1923 default: break;
1924 case 32: MiddleType = Type::Int32Ty; break;
1925 case 16: MiddleType = Type::Int16Ty; break;
1926 case 8: MiddleType = Type::Int8Ty; break;
1927 }
1928 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001929 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001930 InsertNewInstBefore(NewTrunc, I);
Reid Spencera5c18bf2007-03-28 01:36:16 +00001931 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001932 }
1933 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001934 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001935
Chris Lattnerb8b97502003-08-13 19:01:45 +00001936 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001937 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001938 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001939
1940 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1941 if (RHSI->getOpcode() == Instruction::Sub)
1942 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1943 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1944 }
1945 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1946 if (LHSI->getOpcode() == Instruction::Sub)
1947 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1948 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1949 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001950 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001951
Chris Lattner147e9752002-05-08 22:46:53 +00001952 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001953 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001955
1956 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001957 if (!isa<Constant>(RHS))
1958 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001959 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001960
Misha Brukmanb1c93172005-04-21 23:48:37 +00001961
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001962 ConstantInt *C2;
1963 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1964 if (X == RHS) // X*C + X --> X * (C+1)
1965 return BinaryOperator::createMul(RHS, AddOne(C2));
1966
1967 // X*C1 + X*C2 --> X * (C1+C2)
1968 ConstantInt *C1;
1969 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer80263aa2007-03-25 05:33:51 +00001970 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001971 }
1972
1973 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001974 if (dyn_castFoldableMul(RHS, C2) == LHS)
1975 return BinaryOperator::createMul(LHS, AddOne(C2));
1976
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001977 // X + ~X --> -1 since ~X = -X-1
1978 if (dyn_castNotVal(LHS) == RHS ||
1979 dyn_castNotVal(RHS) == LHS)
1980 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1981
Chris Lattner57c8d992003-02-18 19:57:07 +00001982
Chris Lattnerb8b97502003-08-13 19:01:45 +00001983 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001984 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001985 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1986 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001987
Chris Lattnerb9cde762003-10-02 15:11:26 +00001988 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001989 Value *X = 0;
Reid Spencer80263aa2007-03-25 05:33:51 +00001990 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1991 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattnerd4252a72004-07-30 07:50:03 +00001992
Chris Lattnerbff91d92004-10-08 05:07:56 +00001993 // (X & FF00) + xx00 -> (X+xx00) & FF00
1994 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer80263aa2007-03-25 05:33:51 +00001995 Constant *Anded = And(CRHS, C2);
Chris Lattnerbff91d92004-10-08 05:07:56 +00001996 if (Anded == CRHS) {
1997 // See if all bits from the first bit set in the Add RHS up are included
1998 // in the mask. First, get the rightmost bit.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00001999 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00002000
2001 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002002 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerbff91d92004-10-08 05:07:56 +00002003
2004 // See if the and mask includes all of these bits.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002005 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002006
Chris Lattnerbff91d92004-10-08 05:07:56 +00002007 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2008 // Okay, the xform is safe. Insert the new add pronto.
2009 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2010 LHS->getName()), I);
2011 return BinaryOperator::createAnd(NewAdd, C2);
2012 }
2013 }
2014 }
2015
Chris Lattnerd4252a72004-07-30 07:50:03 +00002016 // Try to fold constant add into select arguments.
2017 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00002018 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00002019 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00002020 }
2021
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002022 // add (cast *A to intptrtype) B ->
2023 // cast (GEP (cast *A to sbyte*) B) ->
2024 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002025 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002026 CastInst *CI = dyn_cast<CastInst>(LHS);
2027 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002028 if (!CI) {
2029 CI = dyn_cast<CastInst>(RHS);
2030 Other = LHS;
2031 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002032 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00002033 (CI->getType()->getPrimitiveSizeInBits() ==
2034 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002035 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00002036 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00002037 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00002038 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002039 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00002040 }
2041 }
2042
Chris Lattner113f4f42002-06-25 16:13:24 +00002043 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002044}
2045
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002046// isSignBit - Return true if the value represented by the constant only has the
2047// highest order bit set.
2048static bool isSignBit(ConstantInt *CI) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002049 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer450434e2007-03-19 20:58:18 +00002050 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002051}
2052
Chris Lattner113f4f42002-06-25 16:13:24 +00002053Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002055
Chris Lattnere6794492002-08-12 21:17:25 +00002056 if (Op0 == Op1) // sub X, X -> 0
2057 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00002058
Chris Lattnere6794492002-08-12 21:17:25 +00002059 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00002060 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002061 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00002062
Chris Lattner81a7a232004-10-16 18:11:37 +00002063 if (isa<UndefValue>(Op0))
2064 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2065 if (isa<UndefValue>(Op1))
2066 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2067
Chris Lattner8f2f5982003-11-05 01:06:05 +00002068 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2069 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002070 if (C->isAllOnesValue())
2071 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00002072
Chris Lattner8f2f5982003-11-05 01:06:05 +00002073 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002074 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002075 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer80263aa2007-03-25 05:33:51 +00002076 return BinaryOperator::createAdd(X, AddOne(C));
2077
Chris Lattner27df1db2007-01-15 07:02:54 +00002078 // -(X >>u 31) -> (X >>s 31)
2079 // -(X >>s 31) -> (X >>u 31)
Zhou Shengfd28a332007-03-30 17:20:39 +00002080 if (C->isZero()) {
Reid Spencer2341c222007-02-02 02:16:23 +00002081 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00002082 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002083 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002084 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002085 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencere0fc4df2006-10-20 07:07:24 +00002086 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002087 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00002088 return BinaryOperator::create(Instruction::AShr,
2089 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002090 }
2091 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002092 }
2093 else if (SI->getOpcode() == Instruction::AShr) {
2094 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2095 // Check to see if we are shifting out everything but the sign bit.
Zhou Shengfd28a332007-03-30 17:20:39 +00002096 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerfdff9382006-11-08 06:47:33 +00002097 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002098 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002099 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002100 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002101 }
2102 }
2103 }
Chris Lattner022167f2004-03-13 00:11:49 +00002104 }
Chris Lattner183b3362004-04-09 19:05:30 +00002105
2106 // Try to fold constant sub into select arguments.
2107 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002108 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002109 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002110
2111 if (isa<PHINode>(Op0))
2112 if (Instruction *NV = FoldOpIntoPhi(I))
2113 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002114 }
2115
Chris Lattnera9be4492005-04-07 16:15:25 +00002116 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2117 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002118 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002119 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002120 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002121 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002122 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002123 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2124 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2125 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer80263aa2007-03-25 05:33:51 +00002126 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002127 Op1I->getOperand(0));
2128 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002129 }
2130
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002131 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002132 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2133 // is not used by anyone else...
2134 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002135 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002136 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002137 // Swap the two operands of the subexpr...
2138 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2139 Op1I->setOperand(0, IIOp1);
2140 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002141
Chris Lattner3082c5a2003-02-18 19:28:33 +00002142 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002143 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002144 }
2145
2146 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2147 //
2148 if (Op1I->getOpcode() == Instruction::And &&
2149 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2150 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2151
Chris Lattner396dbfe2004-06-09 05:08:07 +00002152 Value *NewNot =
2153 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002154 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002155 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002156
Reid Spencer3c514952006-10-16 23:08:08 +00002157 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002158 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002159 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002160 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002161 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002162 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002163 ConstantExpr::getNeg(DivRHS));
2164
Chris Lattner57c8d992003-02-18 19:57:07 +00002165 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002166 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002167 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002168 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002169 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002170 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002171 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002172 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002173
Chris Lattner7a002fe2006-12-02 00:13:08 +00002174 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002175 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2176 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002177 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2178 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2179 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2180 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002181 } else if (Op0I->getOpcode() == Instruction::Sub) {
2182 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2183 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002184 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002185
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002186 ConstantInt *C1;
2187 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer80263aa2007-03-25 05:33:51 +00002188 if (X == Op1) // X*C - X --> X * (C-1)
2189 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattner57c8d992003-02-18 19:57:07 +00002190
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002191 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2192 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer80263aa2007-03-25 05:33:51 +00002193 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002194 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002195 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002196}
2197
Reid Spencer266e42b2006-12-23 06:05:41 +00002198/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002199/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002200static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2201 switch (pred) {
2202 case ICmpInst::ICMP_SLT:
2203 // True if LHS s< RHS and RHS == 0
2204 return RHS->isNullValue();
2205 case ICmpInst::ICMP_SLE:
2206 // True if LHS s<= RHS and RHS == -1
2207 return RHS->isAllOnesValue();
2208 case ICmpInst::ICMP_UGE:
2209 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
Reid Spencera962d182007-03-24 00:42:08 +00002210 return RHS->getValue() ==
2211 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002212 case ICmpInst::ICMP_UGT:
2213 // True if LHS u> RHS and RHS == high-bit-mask - 1
Reid Spencera962d182007-03-24 00:42:08 +00002214 return RHS->getValue() ==
2215 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
Reid Spencer266e42b2006-12-23 06:05:41 +00002216 default:
2217 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002218 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002219}
2220
Chris Lattner113f4f42002-06-25 16:13:24 +00002221Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002222 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002223 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002224
Chris Lattner81a7a232004-10-16 18:11:37 +00002225 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2227
Chris Lattnere6794492002-08-12 21:17:25 +00002228 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002229 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2230 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002231
2232 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002233 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002234 if (SI->getOpcode() == Instruction::Shl)
2235 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002236 return BinaryOperator::createMul(SI->getOperand(0),
2237 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002238
Chris Lattnercce81be2003-09-11 22:24:54 +00002239 if (CI->isNullValue())
2240 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2241 if (CI->equalsInt(1)) // X * 1 == X
2242 return ReplaceInstUsesWith(I, Op0);
2243 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002244 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002245
Zhou Sheng4961cf12007-03-29 01:57:21 +00002246 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002247 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencer0d5f9232007-02-02 14:08:20 +00002248 return BinaryOperator::createShl(Op0,
Reid Spencer6d392062007-03-23 20:05:17 +00002249 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattner22d00a82005-08-02 19:16:58 +00002250 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002251 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002252 if (Op1F->isNullValue())
2253 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002254
Chris Lattner3082c5a2003-02-18 19:28:33 +00002255 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2256 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2257 if (Op1F->getValue() == 1.0)
2258 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2259 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002260
2261 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2262 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2263 isa<ConstantInt>(Op0I->getOperand(1))) {
2264 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2265 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2266 Op1, "tmp");
2267 InsertNewInstBefore(Add, I);
2268 Value *C1C2 = ConstantExpr::getMul(Op1,
2269 cast<Constant>(Op0I->getOperand(1)));
2270 return BinaryOperator::createAdd(Add, C1C2);
2271
2272 }
Chris Lattner183b3362004-04-09 19:05:30 +00002273
2274 // Try to fold constant mul into select arguments.
2275 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002276 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002277 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002278
2279 if (isa<PHINode>(Op0))
2280 if (Instruction *NV = FoldOpIntoPhi(I))
2281 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002282 }
2283
Chris Lattner934a64cf2003-03-10 23:23:04 +00002284 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2285 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002286 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002287
Chris Lattner2635b522004-02-23 05:39:21 +00002288 // If one of the operands of the multiply is a cast from a boolean value, then
2289 // we know the bool is either zero or one, so this is a 'masking' multiply.
2290 // See if we can simplify things based on how the boolean was originally
2291 // formed.
2292 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002293 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002294 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002295 BoolCast = CI;
2296 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002297 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002298 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002299 BoolCast = CI;
2300 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002301 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002302 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2303 const Type *SCOpTy = SCIOp0->getType();
2304
Reid Spencer266e42b2006-12-23 06:05:41 +00002305 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002306 // multiply into a shift/and combination.
2307 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002308 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002309 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002310 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002311 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002312 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002313 InsertNewInstBefore(
2314 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002315 BoolCast->getOperand(0)->getName()+
2316 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002317
2318 // If the multiply type is not the same as the source type, sign extend
2319 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002320 if (I.getType() != V->getType()) {
Zhou Sheng56cda952007-04-02 08:20:41 +00002321 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2322 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002323 Instruction::CastOps opcode =
2324 (SrcBits == DstBits ? Instruction::BitCast :
2325 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2326 V = InsertCastBefore(opcode, V, I.getType(), I);
2327 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002328
Chris Lattner2635b522004-02-23 05:39:21 +00002329 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002330 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002331 }
2332 }
2333 }
2334
Chris Lattner113f4f42002-06-25 16:13:24 +00002335 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002336}
2337
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338/// This function implements the transforms on div instructions that work
2339/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2340/// used by the visitors to those instructions.
2341/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002342Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002344
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002345 // undef / X -> 0
2346 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002347 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002348
2349 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002350 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002351 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002352
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002353 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002354 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2355 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002356 // same basic block, then we replace the select with Y, and the condition
2357 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002358 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002359 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002360 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2361 if (ST->isNullValue()) {
2362 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2363 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002364 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002365 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2366 I.setOperand(1, SI->getOperand(2));
2367 else
2368 UpdateValueUsesWith(SI, SI->getOperand(2));
2369 return &I;
2370 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002371
Chris Lattnerd79dc792006-09-09 20:26:32 +00002372 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2373 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2374 if (ST->isNullValue()) {
2375 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2376 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002377 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002378 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2379 I.setOperand(1, SI->getOperand(1));
2380 else
2381 UpdateValueUsesWith(SI, SI->getOperand(1));
2382 return &I;
2383 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002384 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002385
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 return 0;
2387}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002388
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002389/// This function implements the transforms common to both integer division
2390/// instructions (udiv and sdiv). It is called by the visitors to those integer
2391/// division instructions.
2392/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002393Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002394 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2395
2396 if (Instruction *Common = commonDivTransforms(I))
2397 return Common;
2398
2399 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2400 // div X, 1 == X
2401 if (RHS->equalsInt(1))
2402 return ReplaceInstUsesWith(I, Op0);
2403
2404 // (X / C1) / C2 -> X / (C1*C2)
2405 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2406 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2407 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2408 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer80263aa2007-03-25 05:33:51 +00002409 Multiply(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002410 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002411
Reid Spencer6d392062007-03-23 20:05:17 +00002412 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2415 return R;
2416 if (isa<PHINode>(Op0))
2417 if (Instruction *NV = FoldOpIntoPhi(I))
2418 return NV;
2419 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002420 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002421
Chris Lattner3082c5a2003-02-18 19:28:33 +00002422 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002423 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002424 if (LHS->equalsInt(0))
2425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2426
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002427 return 0;
2428}
2429
2430Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2431 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2432
2433 // Handle the integer div common cases
2434 if (Instruction *Common = commonIDivTransforms(I))
2435 return Common;
2436
2437 // X udiv C^2 -> X >> C
2438 // Check to see if this is an unsigned division with an exact power of 2,
2439 // if so, convert to a right shift.
2440 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer54d5b1b2007-03-26 23:58:26 +00002441 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencer6d392062007-03-23 20:05:17 +00002442 return BinaryOperator::createLShr(Op0,
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002443 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002444 }
2445
2446 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002447 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002448 if (RHSI->getOpcode() == Instruction::Shl &&
2449 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002450 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002451 if (C1.isPowerOf2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002452 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002453 const Type *NTy = N->getType();
Reid Spencer959a21d2007-03-23 21:24:59 +00002454 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002455 Constant *C2V = ConstantInt::get(NTy, C2);
2456 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002457 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002458 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002459 }
2460 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002461 }
2462
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002463 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2464 // where C1&C2 are powers of two.
Reid Spencer3939b1a2007-03-05 23:36:13 +00002465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002466 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencer3939b1a2007-03-05 23:36:13 +00002467 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002468 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencer6d392062007-03-23 20:05:17 +00002469 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencer3939b1a2007-03-05 23:36:13 +00002470 // Compute the shift amounts
Reid Spencer6d392062007-03-23 20:05:17 +00002471 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencer3939b1a2007-03-05 23:36:13 +00002472 // Construct the "on true" case of the select
2473 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2474 Instruction *TSI = BinaryOperator::createLShr(
2475 Op0, TC, SI->getName()+".t");
2476 TSI = InsertNewInstBefore(TSI, I);
2477
2478 // Construct the "on false" case of the select
2479 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2480 Instruction *FSI = BinaryOperator::createLShr(
2481 Op0, FC, SI->getName()+".f");
2482 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002483
Reid Spencer3939b1a2007-03-05 23:36:13 +00002484 // construct the select instruction and return it.
2485 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002486 }
Reid Spencer3939b1a2007-03-05 23:36:13 +00002487 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002488 return 0;
2489}
2490
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002491Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2492 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2493
2494 // Handle the integer div common cases
2495 if (Instruction *Common = commonIDivTransforms(I))
2496 return Common;
2497
2498 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2499 // sdiv X, -1 == -X
2500 if (RHS->isAllOnesValue())
2501 return BinaryOperator::createNeg(Op0);
2502
2503 // -X/C -> X/-C
2504 if (Value *LHSNeg = dyn_castNegVal(Op0))
2505 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2506 }
2507
2508 // If the sign bits of both operands are zero (i.e. we can prove they are
2509 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002510 if (I.getType()->isInteger()) {
Reid Spencer6d392062007-03-23 20:05:17 +00002511 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002512 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2513 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2514 }
2515 }
2516
2517 return 0;
2518}
2519
2520Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2521 return commonDivTransforms(I);
2522}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002523
Chris Lattner85dda9a2006-03-02 06:50:58 +00002524/// GetFactor - If we can prove that the specified value is at least a multiple
2525/// of some factor, return that factor.
2526static Constant *GetFactor(Value *V) {
2527 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2528 return CI;
2529
2530 // Unless we can be tricky, we know this is a multiple of 1.
2531 Constant *Result = ConstantInt::get(V->getType(), 1);
2532
2533 Instruction *I = dyn_cast<Instruction>(V);
2534 if (!I) return Result;
2535
2536 if (I->getOpcode() == Instruction::Mul) {
2537 // Handle multiplies by a constant, etc.
2538 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2539 GetFactor(I->getOperand(1)));
2540 } else if (I->getOpcode() == Instruction::Shl) {
2541 // (X<<C) -> X * (1 << C)
2542 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2543 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2544 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2545 }
2546 } else if (I->getOpcode() == Instruction::And) {
2547 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2548 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencera962d182007-03-24 00:42:08 +00002549 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner85dda9a2006-03-02 06:50:58 +00002550 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2551 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002552 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002553 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002554 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002555 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002556 if (!CI->isIntegerCast())
2557 return Result;
2558 Value *Op = CI->getOperand(0);
2559 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002560 }
2561 return Result;
2562}
2563
Reid Spencer7eb55b32006-11-02 01:53:59 +00002564/// This function implements the transforms on rem instructions that work
2565/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2566/// is used by the visitors to those instructions.
2567/// @brief Transforms common to all three rem instructions
2568Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002570
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002571 // 0 % X == 0, we don't need to preserve faults!
2572 if (Constant *LHS = dyn_cast<Constant>(Op0))
2573 if (LHS->isNullValue())
2574 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2575
2576 if (isa<UndefValue>(Op0)) // undef % X -> 0
2577 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2578 if (isa<UndefValue>(Op1))
2579 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002580
2581 // Handle cases involving: rem X, (select Cond, Y, Z)
2582 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2583 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2584 // the same basic block, then we replace the select with Y, and the
2585 // condition of the select with false (if the cond value is in the same
2586 // BB). If the select has uses other than the div, this allows them to be
2587 // simplified also.
2588 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2589 if (ST->isNullValue()) {
2590 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2591 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002592 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002593 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2594 I.setOperand(1, SI->getOperand(2));
2595 else
2596 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002597 return &I;
2598 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002599 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2600 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2601 if (ST->isNullValue()) {
2602 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2603 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002604 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002605 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2606 I.setOperand(1, SI->getOperand(1));
2607 else
2608 UpdateValueUsesWith(SI, SI->getOperand(1));
2609 return &I;
2610 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002611 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002612
Reid Spencer7eb55b32006-11-02 01:53:59 +00002613 return 0;
2614}
2615
2616/// This function implements the transforms common to both integer remainder
2617/// instructions (urem and srem). It is called by the visitors to those integer
2618/// remainder instructions.
2619/// @brief Common integer remainder transforms
2620Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2621 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2622
2623 if (Instruction *common = commonRemTransforms(I))
2624 return common;
2625
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002626 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002627 // X % 0 == undef, we don't need to preserve faults!
2628 if (RHS->equalsInt(0))
2629 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2630
Chris Lattner3082c5a2003-02-18 19:28:33 +00002631 if (RHS->equalsInt(1)) // X % 1 == 0
2632 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2633
Chris Lattnerb70f1412006-02-28 05:49:21 +00002634 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2635 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2636 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2637 return R;
2638 } else if (isa<PHINode>(Op0I)) {
2639 if (Instruction *NV = FoldOpIntoPhi(I))
2640 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002641 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002642 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2643 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002644 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002645 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002646 }
2647
Reid Spencer7eb55b32006-11-02 01:53:59 +00002648 return 0;
2649}
2650
2651Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2653
2654 if (Instruction *common = commonIRemTransforms(I))
2655 return common;
2656
2657 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2658 // X urem C^2 -> X and C
2659 // Check to see if this is an unsigned remainder with an exact power of 2,
2660 // if so, convert to a bitwise and.
2661 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencer6d392062007-03-23 20:05:17 +00002662 if (C->getValue().isPowerOf2())
Reid Spencer7eb55b32006-11-02 01:53:59 +00002663 return BinaryOperator::createAnd(Op0, SubOne(C));
2664 }
2665
Chris Lattner2e90b732006-02-05 07:54:04 +00002666 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002667 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2668 if (RHSI->getOpcode() == Instruction::Shl &&
2669 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002670 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner2e90b732006-02-05 07:54:04 +00002671 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2672 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2673 "tmp"), I);
2674 return BinaryOperator::createAnd(Op0, Add);
2675 }
2676 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002677 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002678
Reid Spencer7eb55b32006-11-02 01:53:59 +00002679 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2680 // where C1&C2 are powers of two.
2681 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2682 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2683 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2684 // STO == 0 and SFO == 0 handled above.
Reid Spencer6d392062007-03-23 20:05:17 +00002685 if ((STO->getValue().isPowerOf2()) &&
2686 (SFO->getValue().isPowerOf2())) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002687 Value *TrueAnd = InsertNewInstBefore(
2688 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2689 Value *FalseAnd = InsertNewInstBefore(
2690 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2691 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2692 }
2693 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002694 }
2695
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002696 return 0;
2697}
2698
Reid Spencer7eb55b32006-11-02 01:53:59 +00002699Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2701
2702 if (Instruction *common = commonIRemTransforms(I))
2703 return common;
2704
2705 if (Value *RHSNeg = dyn_castNegVal(Op1))
2706 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng222d5eb2007-03-25 05:01:29 +00002707 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002708 // X % -Y -> X % Y
2709 AddUsesToWorkList(I);
2710 I.setOperand(1, RHSNeg);
2711 return &I;
2712 }
2713
2714 // If the top bits of both operands are zero (i.e. we can prove they are
2715 // unsigned inputs), turn this into a urem.
Reid Spencer6d392062007-03-23 20:05:17 +00002716 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer7eb55b32006-11-02 01:53:59 +00002717 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2718 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2719 return BinaryOperator::createURem(Op0, Op1, I.getName());
2720 }
2721
2722 return 0;
2723}
2724
2725Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002726 return commonRemTransforms(I);
2727}
2728
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002729// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002730static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spenceref599b02007-03-19 21:10:28 +00002731 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00002732 if (isSigned) {
2733 // Calculate 0111111111..11111
Reid Spenceref599b02007-03-19 21:10:28 +00002734 APInt Val(APInt::getSignedMaxValue(TypeBits));
2735 return C->getValue() == Val-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002736 }
Reid Spenceref599b02007-03-19 21:10:28 +00002737 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002738}
2739
2740// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002741static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2742 if (isSigned) {
2743 // Calculate 1111111111000000000000
Reid Spencer3b93db72007-03-19 21:08:07 +00002744 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2745 APInt Val(APInt::getSignedMinValue(TypeBits));
2746 return C->getValue() == Val+1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002747 }
Reid Spencer3b93db72007-03-19 21:08:07 +00002748 return C->getValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002749}
2750
Chris Lattner35167c32004-06-09 07:59:58 +00002751// isOneBitSet - Return true if there is exactly one bit set in the specified
2752// constant.
2753static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer66827212007-03-20 00:16:52 +00002754 return CI->getValue().isPowerOf2();
Chris Lattner35167c32004-06-09 07:59:58 +00002755}
2756
Chris Lattner8fc5af42004-09-23 21:46:38 +00002757// isHighOnes - Return true if the constant is of the form 1+0+.
2758// This is the same as lowones(~X).
2759static bool isHighOnes(const ConstantInt *CI) {
Zhou Shengb3949342007-03-20 12:49:06 +00002760 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002761}
2762
Reid Spencer266e42b2006-12-23 06:05:41 +00002763/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002764/// are carefully arranged to allow folding of expressions such as:
2765///
2766/// (A < B) | (A > B) --> (A != B)
2767///
Reid Spencer266e42b2006-12-23 06:05:41 +00002768/// Note that this is only valid if the first and second predicates have the
2769/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002770///
Reid Spencer266e42b2006-12-23 06:05:41 +00002771/// Three bits are used to represent the condition, as follows:
2772/// 0 A > B
2773/// 1 A == B
2774/// 2 A < B
2775///
2776/// <=> Value Definition
2777/// 000 0 Always false
2778/// 001 1 A > B
2779/// 010 2 A == B
2780/// 011 3 A >= B
2781/// 100 4 A < B
2782/// 101 5 A != B
2783/// 110 6 A <= B
2784/// 111 7 Always true
2785///
2786static unsigned getICmpCode(const ICmpInst *ICI) {
2787 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002788 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002789 case ICmpInst::ICMP_UGT: return 1; // 001
2790 case ICmpInst::ICMP_SGT: return 1; // 001
2791 case ICmpInst::ICMP_EQ: return 2; // 010
2792 case ICmpInst::ICMP_UGE: return 3; // 011
2793 case ICmpInst::ICMP_SGE: return 3; // 011
2794 case ICmpInst::ICMP_ULT: return 4; // 100
2795 case ICmpInst::ICMP_SLT: return 4; // 100
2796 case ICmpInst::ICMP_NE: return 5; // 101
2797 case ICmpInst::ICMP_ULE: return 6; // 110
2798 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002799 // True -> 7
2800 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002801 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002802 return 0;
2803 }
2804}
2805
Reid Spencer266e42b2006-12-23 06:05:41 +00002806/// getICmpValue - This is the complement of getICmpCode, which turns an
2807/// opcode and two operands into either a constant true or false, or a brand
2808/// new /// ICmp instruction. The sign is passed in to determine which kind
2809/// of predicate to use in new icmp instructions.
2810static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2811 switch (code) {
2812 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002813 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002814 case 1:
2815 if (sign)
2816 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2817 else
2818 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2819 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2820 case 3:
2821 if (sign)
2822 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2823 else
2824 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2825 case 4:
2826 if (sign)
2827 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2828 else
2829 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2830 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2831 case 6:
2832 if (sign)
2833 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2834 else
2835 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002836 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002837 }
2838}
2839
Reid Spencer266e42b2006-12-23 06:05:41 +00002840static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2841 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2842 (ICmpInst::isSignedPredicate(p1) &&
2843 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2844 (ICmpInst::isSignedPredicate(p2) &&
2845 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2846}
2847
2848namespace {
2849// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2850struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002851 InstCombiner &IC;
2852 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002853 ICmpInst::Predicate pred;
2854 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2855 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2856 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002857 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002858 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2859 if (PredicatesFoldable(pred, ICI->getPredicate()))
2860 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2861 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002862 return false;
2863 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002864 Instruction *apply(Instruction &Log) const {
2865 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2866 if (ICI->getOperand(0) != LHS) {
2867 assert(ICI->getOperand(1) == LHS);
2868 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002869 }
2870
Chris Lattnerd1bce952007-03-13 14:27:42 +00002871 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002872 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerd1bce952007-03-13 14:27:42 +00002873 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002874 unsigned Code;
2875 switch (Log.getOpcode()) {
2876 case Instruction::And: Code = LHSCode & RHSCode; break;
2877 case Instruction::Or: Code = LHSCode | RHSCode; break;
2878 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002879 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002880 }
2881
Chris Lattnerd1bce952007-03-13 14:27:42 +00002882 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2883 ICmpInst::isSignedPredicate(ICI->getPredicate());
2884
2885 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002886 if (Instruction *I = dyn_cast<Instruction>(RV))
2887 return I;
2888 // Otherwise, it's a constant boolean value...
2889 return IC.ReplaceInstUsesWith(Log, RV);
2890 }
2891};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002892} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002893
Chris Lattnerba1cb382003-09-19 17:17:26 +00002894// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2895// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002896// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002897Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002898 ConstantInt *OpRHS,
2899 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002900 BinaryOperator &TheAnd) {
2901 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002902 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002903 if (!Op->isShift())
Reid Spencer80263aa2007-03-25 05:33:51 +00002904 Together = And(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002905
Chris Lattnerba1cb382003-09-19 17:17:26 +00002906 switch (Op->getOpcode()) {
2907 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002908 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002909 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002910 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002911 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002912 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002913 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002914 }
2915 break;
2916 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002917 if (Together == AndRHS) // (X | C) & C --> C
2918 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002919
Chris Lattner86102b82005-01-01 16:22:27 +00002920 if (Op->hasOneUse() && Together != OpRHS) {
2921 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002922 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002923 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002924 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002925 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002926 }
2927 break;
2928 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002929 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002930 // Adding a one to a single bit bit-field should be turned into an XOR
2931 // of the bit. First thing to check is to see if this AND is with a
2932 // single bit constant.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002933 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002934
2935 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002936 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002937 // Ok, at this point, we know that we are masking the result of the
2938 // ADD down to exactly one bit. If the constant we are adding has
2939 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00002940 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002941
Chris Lattnerba1cb382003-09-19 17:17:26 +00002942 // Check to see if any bits below the one bit set in AndRHSV are set.
2943 if ((AddRHS & (AndRHSV-1)) == 0) {
2944 // If not, the only thing that can effect the output of the AND is
2945 // the bit specified by AndRHSV. If that bit is set, the effect of
2946 // the XOR is to toggle the bit. If it is clear, then the ADD has
2947 // no effect.
2948 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2949 TheAnd.setOperand(0, X);
2950 return &TheAnd;
2951 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002952 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002953 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002954 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002955 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002956 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002957 }
2958 }
2959 }
2960 }
2961 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002962
2963 case Instruction::Shl: {
2964 // We know that the AND will not produce any of the bits shifted in, so if
2965 // the anded constant includes them, clear them now!
2966 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00002967 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00002968 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00002969 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
2970 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002971
Zhou Shengb3a80b12007-03-29 08:15:12 +00002972 if (CI->getValue() == ShlMask) {
2973 // Masking out bits that the shift already masks
Chris Lattner7e794272004-09-24 15:21:34 +00002974 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2975 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002976 TheAnd.setOperand(1, CI);
2977 return &TheAnd;
2978 }
2979 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002980 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002981 case Instruction::LShr:
2982 {
Chris Lattner2da29172003-09-19 19:05:02 +00002983 // We know that the AND will not produce any of the bits shifted in, so if
2984 // the anded constant includes them, clear them now! This only applies to
2985 // unsigned shifts, because a signed shr may bring in set bits!
2986 //
Zhou Shengb3a80b12007-03-29 08:15:12 +00002987 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00002988 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00002989 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
2990 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002991
Zhou Shengb3a80b12007-03-29 08:15:12 +00002992 if (CI->getValue() == ShrMask) {
2993 // Masking out bits that the shift already masks.
Reid Spencerfdff9382006-11-08 06:47:33 +00002994 return ReplaceInstUsesWith(TheAnd, Op);
2995 } else if (CI != AndRHS) {
2996 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2997 return &TheAnd;
2998 }
2999 break;
3000 }
3001 case Instruction::AShr:
3002 // Signed shr.
3003 // See if this is shifting in some sign extension, then masking it out
3004 // with an and.
3005 if (Op->hasOneUse()) {
Zhou Shengb3a80b12007-03-29 08:15:12 +00003006 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Shengb25806f2007-03-30 09:29:48 +00003007 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Shengb3a80b12007-03-29 08:15:12 +00003008 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3009 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer2a499b02006-12-13 17:19:09 +00003010 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00003011 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00003012 // Make the argument unsigned.
3013 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00003014 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00003015 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00003016 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00003017 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00003018 }
Chris Lattner2da29172003-09-19 19:05:02 +00003019 }
3020 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00003021 }
3022 return 0;
3023}
3024
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003025
Chris Lattner6862fbd2004-09-29 17:40:11 +00003026/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3027/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00003028/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3029/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00003030/// insert new instructions.
3031Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00003032 bool isSigned, bool Inside,
3033 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00003034 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00003035 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00003036 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003037
Chris Lattner6862fbd2004-09-29 17:40:11 +00003038 if (Inside) {
3039 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00003040 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003041
Reid Spencer266e42b2006-12-23 06:05:41 +00003042 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00003043 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencerf4071162007-03-21 23:19:50 +00003044 ICmpInst::Predicate pred = (isSigned ?
Reid Spencer266e42b2006-12-23 06:05:41 +00003045 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3046 return new ICmpInst(pred, V, Hi);
3047 }
3048
3049 // Emit V-Lo <u Hi-Lo
3050 Constant *NegLo = ConstantExpr::getNeg(Lo);
3051 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003052 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003053 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3054 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003055 }
3056
3057 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003058 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003059
Reid Spencerf4071162007-03-21 23:19:50 +00003060 // V < Min || V >= Hi -> V > Hi-1
Chris Lattner6862fbd2004-09-29 17:40:11 +00003061 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00003062 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003063 ICmpInst::Predicate pred = (isSigned ?
3064 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3065 return new ICmpInst(pred, V, Hi);
3066 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003067
Reid Spencerf4071162007-03-21 23:19:50 +00003068 // Emit V-Lo >u Hi-1-Lo
3069 // Note that Hi has already had one subtracted from it, above.
3070 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencer266e42b2006-12-23 06:05:41 +00003071 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003072 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003073 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3074 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003075}
3076
Chris Lattnerb4b25302005-09-18 07:22:02 +00003077// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3078// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3079// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3080// not, since all 1s are not contiguous.
Zhou Sheng56cda952007-04-02 08:20:41 +00003081static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003082 const APInt& V = Val->getValue();
Reid Spencera962d182007-03-24 00:42:08 +00003083 uint32_t BitWidth = Val->getType()->getBitWidth();
3084 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003085
3086 // look for the first zero bit after the run of ones
Reid Spencera962d182007-03-24 00:42:08 +00003087 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003088 // look for the first non-zero bit
Reid Spencera962d182007-03-24 00:42:08 +00003089 ME = V.getActiveBits();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003090 return true;
3091}
3092
Chris Lattnerb4b25302005-09-18 07:22:02 +00003093/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3094/// where isSub determines whether the operator is a sub. If we can fold one of
3095/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003096///
3097/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3098/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3099/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3100///
3101/// return (A +/- B).
3102///
3103Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003104 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003105 Instruction &I) {
3106 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3107 if (!LHSI || LHSI->getNumOperands() != 2 ||
3108 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3109
3110 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3111
3112 switch (LHSI->getOpcode()) {
3113 default: return 0;
3114 case Instruction::And:
Reid Spencer80263aa2007-03-25 05:33:51 +00003115 if (And(N, Mask) == Mask) {
Chris Lattnerb4b25302005-09-18 07:22:02 +00003116 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003117 if ((Mask->getValue().countLeadingZeros() +
3118 Mask->getValue().countPopulation()) ==
3119 Mask->getValue().getBitWidth())
Chris Lattnerb4b25302005-09-18 07:22:02 +00003120 break;
3121
3122 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3123 // part, we don't need any explicit masks to take them out of A. If that
3124 // is all N is, ignore it.
Zhou Sheng56cda952007-04-02 08:20:41 +00003125 uint32_t MB = 0, ME = 0;
Chris Lattnerb4b25302005-09-18 07:22:02 +00003126 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencer6274c722007-03-23 18:46:34 +00003127 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Shengb3a80b12007-03-29 08:15:12 +00003128 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003129 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003130 break;
3131 }
3132 }
Chris Lattneraf517572005-09-18 04:24:45 +00003133 return 0;
3134 case Instruction::Or:
3135 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003136 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Shenge9ebd3f2007-03-24 15:34:37 +00003137 if ((Mask->getValue().countLeadingZeros() +
3138 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003139 && And(N, Mask)->isZero())
Chris Lattneraf517572005-09-18 04:24:45 +00003140 break;
3141 return 0;
3142 }
3143
3144 Instruction *New;
3145 if (isSub)
3146 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3147 else
3148 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3149 return InsertNewInstBefore(New, I);
3150}
3151
Chris Lattner113f4f42002-06-25 16:13:24 +00003152Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003153 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003154 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003155
Chris Lattner81a7a232004-10-16 18:11:37 +00003156 if (isa<UndefValue>(Op1)) // X & undef -> 0
3157 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3158
Chris Lattner86102b82005-01-01 16:22:27 +00003159 // and X, X = X
3160 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003161 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003162
Chris Lattner5b2edb12006-02-12 08:02:11 +00003163 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003164 // purpose is to compute bits we don't care about.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003165 if (!isa<VectorType>(I.getType())) {
Reid Spencerb722f2b2007-03-22 22:19:58 +00003166 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3167 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3168 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner120ab032007-01-18 22:16:33 +00003169 KnownZero, KnownOne))
Reid Spencer54d5b1b2007-03-26 23:58:26 +00003170 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003171 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003172 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003173 if (CP->isAllOnesValue())
3174 return ReplaceInstUsesWith(I, I.getOperand(0));
3175 }
3176 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003177
Zhou Sheng75b871f2007-01-11 12:24:14 +00003178 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00003179 const APInt& AndRHSMask = AndRHS->getValue();
3180 APInt NotAndRHS(~AndRHSMask);
Chris Lattner86102b82005-01-01 16:22:27 +00003181
Chris Lattnerba1cb382003-09-19 17:17:26 +00003182 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003183 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003184 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003185 Value *Op0LHS = Op0I->getOperand(0);
3186 Value *Op0RHS = Op0I->getOperand(1);
3187 switch (Op0I->getOpcode()) {
3188 case Instruction::Xor:
3189 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003190 // If the mask is only needed on one incoming arm, push it up.
3191 if (Op0I->hasOneUse()) {
3192 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3193 // Not masking anything out for the LHS, move to RHS.
3194 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3195 Op0RHS->getName()+".masked");
3196 InsertNewInstBefore(NewRHS, I);
3197 return BinaryOperator::create(
3198 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003199 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003200 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003201 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3202 // Not masking anything out for the RHS, move to LHS.
3203 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3204 Op0LHS->getName()+".masked");
3205 InsertNewInstBefore(NewLHS, I);
3206 return BinaryOperator::create(
3207 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3208 }
3209 }
3210
Chris Lattner86102b82005-01-01 16:22:27 +00003211 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003212 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003213 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3214 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3215 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3216 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3217 return BinaryOperator::createAnd(V, AndRHS);
3218 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3219 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003220 break;
3221
3222 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003223 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3224 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3225 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3226 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3227 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003228 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003229 }
3230
Chris Lattner16464b32003-07-23 19:25:52 +00003231 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003232 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003233 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003234 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003235 // If this is an integer truncation or change from signed-to-unsigned, and
3236 // if the source is an and/or with immediate, transform it. This
3237 // frequently occurs for bitfield accesses.
3238 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003239 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003240 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003241 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003242 if (CastOp->getOpcode() == Instruction::And) {
3243 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003244 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3245 // This will fold the two constants together, which may allow
3246 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003247 Instruction *NewCast = CastInst::createTruncOrBitCast(
3248 CastOp->getOperand(0), I.getType(),
3249 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003250 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003251 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003252 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003253 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003254 return BinaryOperator::createAnd(NewCast, C3);
3255 } else if (CastOp->getOpcode() == Instruction::Or) {
3256 // Change: and (cast (or X, C1) to T), C2
3257 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003258 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003259 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3260 return ReplaceInstUsesWith(I, AndRHS);
3261 }
3262 }
Chris Lattner33217db2003-07-23 19:36:21 +00003263 }
Chris Lattner183b3362004-04-09 19:05:30 +00003264
3265 // Try to fold constant and into select arguments.
3266 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003267 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003268 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003269 if (isa<PHINode>(Op0))
3270 if (Instruction *NV = FoldOpIntoPhi(I))
3271 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003272 }
3273
Chris Lattnerbb74e222003-03-10 23:06:50 +00003274 Value *Op0NotVal = dyn_castNotVal(Op0);
3275 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003276
Chris Lattner023a4832004-06-18 06:07:51 +00003277 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3278 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3279
Misha Brukman9c003d82004-07-30 12:50:08 +00003280 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003281 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003282 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3283 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003284 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003285 return BinaryOperator::createNot(Or);
3286 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003287
3288 {
3289 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003290 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3291 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3292 return ReplaceInstUsesWith(I, Op1);
3293 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3294 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3295 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003296
3297 if (Op0->hasOneUse() &&
3298 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3299 if (A == Op1) { // (A^B)&A -> A&(A^B)
3300 I.swapOperands(); // Simplify below
3301 std::swap(Op0, Op1);
3302 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3303 cast<BinaryOperator>(Op0)->swapOperands();
3304 I.swapOperands(); // Simplify below
3305 std::swap(Op0, Op1);
3306 }
3307 }
3308 if (Op1->hasOneUse() &&
3309 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3310 if (B == Op0) { // B&(A^B) -> B&(B^A)
3311 cast<BinaryOperator>(Op1)->swapOperands();
3312 std::swap(A, B);
3313 }
3314 if (A == Op0) { // A&(A^B) -> A & ~B
3315 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3316 InsertNewInstBefore(NotB, I);
3317 return BinaryOperator::createAnd(A, NotB);
3318 }
3319 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003320 }
3321
Reid Spencer266e42b2006-12-23 06:05:41 +00003322 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3323 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3324 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003325 return R;
3326
Chris Lattner623826c2004-09-28 21:48:02 +00003327 Value *LHSVal, *RHSVal;
3328 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003329 ICmpInst::Predicate LHSCC, RHSCC;
3330 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3331 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3332 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3333 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3334 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3335 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3336 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3337 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003338 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003339 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3340 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3341 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3342 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003343 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003344 std::swap(LHS, RHS);
3345 std::swap(LHSCst, RHSCst);
3346 std::swap(LHSCC, RHSCC);
3347 }
3348
Reid Spencer266e42b2006-12-23 06:05:41 +00003349 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003350 // comparing a value against two constants and and'ing the result
3351 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003352 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3353 // (from the FoldICmpLogical check above), that the two constants
3354 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003355 assert(LHSCst != RHSCst && "Compares not folded above?");
3356
3357 switch (LHSCC) {
3358 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003359 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003360 switch (RHSCC) {
3361 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003362 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3363 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3364 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003365 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003366 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3367 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3368 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003369 return ReplaceInstUsesWith(I, LHS);
3370 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003371 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003372 switch (RHSCC) {
3373 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003374 case ICmpInst::ICMP_ULT:
3375 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3376 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3377 break; // (X != 13 & X u< 15) -> no change
3378 case ICmpInst::ICMP_SLT:
3379 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3380 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3381 break; // (X != 13 & X s< 15) -> no change
3382 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3383 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3384 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003385 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003386 case ICmpInst::ICMP_NE:
3387 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003388 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3389 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3390 LHSVal->getName()+".off");
3391 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003392 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3393 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003394 }
3395 break; // (X != 13 & X != 15) -> no change
3396 }
3397 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003398 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003399 switch (RHSCC) {
3400 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003401 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3402 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003403 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003404 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3405 break;
3406 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3407 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003408 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003409 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3410 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003411 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003412 break;
3413 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003414 switch (RHSCC) {
3415 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003416 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3417 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003418 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003419 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3420 break;
3421 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3422 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003423 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003424 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3425 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003426 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003427 break;
3428 case ICmpInst::ICMP_UGT:
3429 switch (RHSCC) {
3430 default: assert(0 && "Unknown integer condition code!");
3431 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3432 return ReplaceInstUsesWith(I, LHS);
3433 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3434 return ReplaceInstUsesWith(I, RHS);
3435 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3436 break;
3437 case ICmpInst::ICMP_NE:
3438 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3439 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3440 break; // (X u> 13 & X != 15) -> no change
3441 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3442 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3443 true, I);
3444 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3445 break;
3446 }
3447 break;
3448 case ICmpInst::ICMP_SGT:
3449 switch (RHSCC) {
3450 default: assert(0 && "Unknown integer condition code!");
3451 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3452 return ReplaceInstUsesWith(I, LHS);
3453 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3454 return ReplaceInstUsesWith(I, RHS);
3455 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3456 break;
3457 case ICmpInst::ICMP_NE:
3458 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3459 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3460 break; // (X s> 13 & X != 15) -> no change
3461 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3462 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3463 true, I);
3464 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3465 break;
3466 }
3467 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003468 }
3469 }
3470 }
3471
Chris Lattner3af10532006-05-05 06:39:07 +00003472 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003473 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3474 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3475 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3476 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003477 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003478 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003479 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3480 I.getType(), TD) &&
3481 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3482 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003483 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3484 Op1C->getOperand(0),
3485 I.getName());
3486 InsertNewInstBefore(NewOp, I);
3487 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3488 }
Chris Lattner3af10532006-05-05 06:39:07 +00003489 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003490
3491 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003492 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3493 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3494 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003495 SI0->getOperand(1) == SI1->getOperand(1) &&
3496 (SI0->hasOneUse() || SI1->hasOneUse())) {
3497 Instruction *NewOp =
3498 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3499 SI1->getOperand(0),
3500 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003501 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3502 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003503 }
Chris Lattner3af10532006-05-05 06:39:07 +00003504 }
3505
Chris Lattner113f4f42002-06-25 16:13:24 +00003506 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003507}
3508
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003509/// CollectBSwapParts - Look to see if the specified value defines a single byte
3510/// in the result. If it does, and if the specified byte hasn't been filled in
3511/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003512static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003513 Instruction *I = dyn_cast<Instruction>(V);
3514 if (I == 0) return true;
3515
3516 // If this is an or instruction, it is an inner node of the bswap.
3517 if (I->getOpcode() == Instruction::Or)
3518 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3519 CollectBSwapParts(I->getOperand(1), ByteValues);
3520
Zhou Shengb25806f2007-03-30 09:29:48 +00003521 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003522 // If this is a shift by a constant int, and it is "24", then its operand
3523 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003524 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003525 // Not shifting the entire input by N-1 bytes?
Zhou Shengb25806f2007-03-30 09:29:48 +00003526 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003527 8*(ByteValues.size()-1))
3528 return true;
3529
3530 unsigned DestNo;
3531 if (I->getOpcode() == Instruction::Shl) {
3532 // X << 24 defines the top byte with the lowest of the input bytes.
3533 DestNo = ByteValues.size()-1;
3534 } else {
3535 // X >>u 24 defines the low byte with the highest of the input bytes.
3536 DestNo = 0;
3537 }
3538
3539 // If the destination byte value is already defined, the values are or'd
3540 // together, which isn't a bswap (unless it's an or of the same bits).
3541 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3542 return true;
3543 ByteValues[DestNo] = I->getOperand(0);
3544 return false;
3545 }
3546
3547 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3548 // don't have this.
3549 Value *Shift = 0, *ShiftLHS = 0;
3550 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3551 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3552 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3553 return true;
3554 Instruction *SI = cast<Instruction>(Shift);
3555
3556 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Shengb25806f2007-03-30 09:29:48 +00003557 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3558 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003559 return true;
3560
3561 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3562 unsigned DestByte;
Zhou Shengb25806f2007-03-30 09:29:48 +00003563 if (AndAmt->getValue().getActiveBits() > 64)
3564 return true;
3565 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003566 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Shengb25806f2007-03-30 09:29:48 +00003567 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003568 break;
3569 // Unknown mask for bswap.
3570 if (DestByte == ByteValues.size()) return true;
3571
Reid Spencere0fc4df2006-10-20 07:07:24 +00003572 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003573 unsigned SrcByte;
3574 if (SI->getOpcode() == Instruction::Shl)
3575 SrcByte = DestByte - ShiftBytes;
3576 else
3577 SrcByte = DestByte + ShiftBytes;
3578
3579 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3580 if (SrcByte != ByteValues.size()-DestByte-1)
3581 return true;
3582
3583 // If the destination byte value is already defined, the values are or'd
3584 // together, which isn't a bswap (unless it's an or of the same bits).
3585 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3586 return true;
3587 ByteValues[DestByte] = SI->getOperand(0);
3588 return false;
3589}
3590
3591/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3592/// If so, insert the new bswap intrinsic and return it.
3593Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003594 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3595 if (!ITy || ITy->getBitWidth() % 16)
3596 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003597
3598 /// ByteValues - For each byte of the result, we keep track of which value
3599 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003600 SmallVector<Value*, 8> ByteValues;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003601 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003602
3603 // Try to find all the pieces corresponding to the bswap.
3604 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3605 CollectBSwapParts(I.getOperand(1), ByteValues))
3606 return 0;
3607
3608 // Check to see if all of the bytes come from the same value.
3609 Value *V = ByteValues[0];
3610 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3611
3612 // Check to make sure that all of the bytes come from the same value.
3613 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3614 if (ByteValues[i] != V)
3615 return 0;
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003616 const Type *Tys[] = { ITy, ITy };
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003617 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnerc3eeb422007-04-01 20:57:36 +00003618 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003619 return new CallInst(F, V);
3620}
3621
3622
Chris Lattner113f4f42002-06-25 16:13:24 +00003623Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003624 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003626
Chris Lattner3a8248f2007-03-24 23:56:43 +00003627 if (isa<UndefValue>(Op1)) // X | undef -> -1
3628 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003629
Chris Lattner5b2edb12006-02-12 08:02:11 +00003630 // or X, X = X
3631 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003632 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003633
Chris Lattner5b2edb12006-02-12 08:02:11 +00003634 // See if we can simplify any instructions used by the instruction whose sole
3635 // purpose is to compute bits we don't care about.
Chris Lattner3a8248f2007-03-24 23:56:43 +00003636 if (!isa<VectorType>(I.getType())) {
3637 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3638 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3639 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3640 KnownZero, KnownOne))
3641 return &I;
3642 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003643
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003644 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003645 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003646 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003647 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3648 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003649 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003650 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003651 Or->takeName(Op0);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003652 return BinaryOperator::createAnd(Or,
3653 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003654 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003655
Chris Lattnerd4252a72004-07-30 07:50:03 +00003656 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3657 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003658 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003659 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003660 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003661 return BinaryOperator::createXor(Or,
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003662 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003663 }
Chris Lattner183b3362004-04-09 19:05:30 +00003664
3665 // Try to fold constant and into select arguments.
3666 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003667 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003668 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003669 if (isa<PHINode>(Op0))
3670 if (Instruction *NV = FoldOpIntoPhi(I))
3671 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003672 }
3673
Chris Lattner330628a2006-01-06 17:59:59 +00003674 Value *A = 0, *B = 0;
3675 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003676
3677 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3678 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3679 return ReplaceInstUsesWith(I, Op1);
3680 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3681 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3682 return ReplaceInstUsesWith(I, Op0);
3683
Chris Lattnerb7845d62006-07-10 20:25:24 +00003684 // (A | B) | C and A | (B | C) -> bswap if possible.
3685 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003686 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003687 match(Op1, m_Or(m_Value(), m_Value())) ||
3688 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3689 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003690 if (Instruction *BSwap = MatchBSwap(I))
3691 return BSwap;
3692 }
3693
Chris Lattnerb62f5082005-05-09 04:58:36 +00003694 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3695 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003696 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003697 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3698 InsertNewInstBefore(NOr, I);
3699 NOr->takeName(Op0);
3700 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003701 }
3702
3703 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3704 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencerb722f2b2007-03-22 22:19:58 +00003705 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003706 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3707 InsertNewInstBefore(NOr, I);
3708 NOr->takeName(Op0);
3709 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003710 }
3711
Chris Lattner15212982005-09-18 03:42:07 +00003712 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003713 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003714 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3715
3716 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003717 return BinaryOperator::createAnd(A,
3718 ConstantInt::get(C1->getValue() | C2->getValue()));
Chris Lattner15212982005-09-18 03:42:07 +00003719
3720
Chris Lattner01f56c62005-09-18 06:02:59 +00003721 // If we have: ((V + N) & C1) | (V & C2)
3722 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3723 // replace with V+N.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003724 if (C1->getValue() == ~C2->getValue()) {
Chris Lattner330628a2006-01-06 17:59:59 +00003725 Value *V1 = 0, *V2 = 0;
Reid Spencerb722f2b2007-03-22 22:19:58 +00003726 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003727 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3728 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003729 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003730 return ReplaceInstUsesWith(I, A);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003731 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003732 return ReplaceInstUsesWith(I, A);
3733 }
3734 // Or commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003735 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003736 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3737 // Add commutes, try both ways.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003738 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003739 return ReplaceInstUsesWith(I, B);
Reid Spencerb722f2b2007-03-22 22:19:58 +00003740 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003741 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003742 }
3743 }
3744 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003745
3746 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003747 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3748 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3749 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003750 SI0->getOperand(1) == SI1->getOperand(1) &&
3751 (SI0->hasOneUse() || SI1->hasOneUse())) {
3752 Instruction *NewOp =
3753 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3754 SI1->getOperand(0),
3755 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003756 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3757 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003758 }
3759 }
Chris Lattner812aab72003-08-12 19:11:07 +00003760
Chris Lattnerd4252a72004-07-30 07:50:03 +00003761 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3762 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003763 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003764 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003765 } else {
3766 A = 0;
3767 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003768 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003769 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3770 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003771 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003772 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003773
Misha Brukman9c003d82004-07-30 12:50:08 +00003774 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003775 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3776 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3777 I.getName()+".demorgan"), I);
3778 return BinaryOperator::createNot(And);
3779 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003780 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003781
Reid Spencer266e42b2006-12-23 06:05:41 +00003782 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3783 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3784 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003785 return R;
3786
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003787 Value *LHSVal, *RHSVal;
3788 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003789 ICmpInst::Predicate LHSCC, RHSCC;
3790 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3791 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3792 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3793 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3794 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3795 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3796 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3797 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003798 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003799 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3800 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3801 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3802 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003803 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003804 std::swap(LHS, RHS);
3805 std::swap(LHSCst, RHSCst);
3806 std::swap(LHSCC, RHSCC);
3807 }
3808
Reid Spencer266e42b2006-12-23 06:05:41 +00003809 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003810 // comparing a value against two constants and or'ing the result
3811 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003812 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3813 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003814 // equal.
3815 assert(LHSCst != RHSCst && "Compares not folded above?");
3816
3817 switch (LHSCC) {
3818 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003819 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003820 switch (RHSCC) {
3821 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003822 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003823 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3824 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3825 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3826 LHSVal->getName()+".off");
3827 InsertNewInstBefore(Add, I);
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00003828 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003829 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003830 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003831 break; // (X == 13 | X == 15) -> no change
3832 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3833 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003834 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003835 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3836 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3837 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003838 return ReplaceInstUsesWith(I, RHS);
3839 }
3840 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003841 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003842 switch (RHSCC) {
3843 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003844 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3845 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3846 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003847 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003848 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3849 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3850 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003852 }
3853 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003854 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003855 switch (RHSCC) {
3856 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003857 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003858 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003859 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3860 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3861 false, I);
3862 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3863 break;
3864 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3865 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003866 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003867 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3868 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003869 }
3870 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003871 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003872 switch (RHSCC) {
3873 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003874 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3875 break;
3876 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3877 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3878 false, I);
3879 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3880 break;
3881 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3882 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3883 return ReplaceInstUsesWith(I, RHS);
3884 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3885 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003886 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003887 break;
3888 case ICmpInst::ICMP_UGT:
3889 switch (RHSCC) {
3890 default: assert(0 && "Unknown integer condition code!");
3891 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3892 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3893 return ReplaceInstUsesWith(I, LHS);
3894 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3895 break;
3896 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3897 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003898 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003899 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3900 break;
3901 }
3902 break;
3903 case ICmpInst::ICMP_SGT:
3904 switch (RHSCC) {
3905 default: assert(0 && "Unknown integer condition code!");
3906 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3907 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3908 return ReplaceInstUsesWith(I, LHS);
3909 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3910 break;
3911 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3912 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003913 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003914 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3915 break;
3916 }
3917 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003918 }
3919 }
3920 }
Chris Lattner3af10532006-05-05 06:39:07 +00003921
3922 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003923 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003924 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003925 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3926 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003927 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003928 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003929 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3930 I.getType(), TD) &&
3931 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3932 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003933 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3934 Op1C->getOperand(0),
3935 I.getName());
3936 InsertNewInstBefore(NewOp, I);
3937 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3938 }
Chris Lattner3af10532006-05-05 06:39:07 +00003939 }
Chris Lattner3af10532006-05-05 06:39:07 +00003940
Chris Lattner15212982005-09-18 03:42:07 +00003941
Chris Lattner113f4f42002-06-25 16:13:24 +00003942 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003943}
3944
Chris Lattnerc2076352004-02-16 01:20:27 +00003945// XorSelf - Implements: X ^ X --> 0
3946struct XorSelf {
3947 Value *RHS;
3948 XorSelf(Value *rhs) : RHS(rhs) {}
3949 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3950 Instruction *apply(BinaryOperator &Xor) const {
3951 return &Xor;
3952 }
3953};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003954
3955
Chris Lattner113f4f42002-06-25 16:13:24 +00003956Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003957 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003959
Chris Lattner81a7a232004-10-16 18:11:37 +00003960 if (isa<UndefValue>(Op1))
3961 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3962
Chris Lattnerc2076352004-02-16 01:20:27 +00003963 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3964 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3965 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003967 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003968
3969 // See if we can simplify any instructions used by the instruction whose sole
3970 // purpose is to compute bits we don't care about.
Reid Spencerb722f2b2007-03-22 22:19:58 +00003971 if (!isa<VectorType>(I.getType())) {
3972 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3973 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3974 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3975 KnownZero, KnownOne))
3976 return &I;
3977 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003978
Zhou Sheng75b871f2007-01-11 12:24:14 +00003979 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003980 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3981 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003982 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003983 return new ICmpInst(ICI->getInversePredicate(),
3984 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003985
Reid Spencer266e42b2006-12-23 06:05:41 +00003986 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003987 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003988 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3989 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003990 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3991 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003992 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003993 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003994 }
Chris Lattner023a4832004-06-18 06:07:51 +00003995
3996 // ~(~X & Y) --> (X | ~Y)
3997 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3998 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3999 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4000 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00004001 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00004002 Op0I->getOperand(1)->getName()+".not");
4003 InsertNewInstBefore(NotY, I);
4004 return BinaryOperator::createOr(Op0NotVal, NotY);
4005 }
4006 }
Chris Lattnerb24acc72007-04-02 05:36:22 +00004007
Chris Lattner97638592003-07-23 21:37:07 +00004008 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00004009 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00004010 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004011 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004012 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4013 return BinaryOperator::createSub(
4014 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004015 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00004016 Op0I->getOperand(0));
Chris Lattner50490d52007-04-02 05:42:22 +00004017 } else if (RHS->getValue().isSignBit()) {
Chris Lattnerb24acc72007-04-02 05:36:22 +00004018 // (X + C) ^ signbit -> (X + C + signbit)
4019 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4020 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattner9d5aace2007-04-02 05:48:58 +00004021
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004022 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004023 } else if (Op0I->getOpcode() == Instruction::Or) {
4024 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencerb722f2b2007-03-22 22:19:58 +00004025 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004026 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4027 // Anything in both C1 and C2 is known to be zero, remove it from
4028 // NewRHS.
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004029 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004030 NewRHS = ConstantExpr::getAnd(NewRHS,
4031 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004032 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00004033 I.setOperand(0, Op0I->getOperand(0));
4034 I.setOperand(1, NewRHS);
4035 return &I;
4036 }
Chris Lattner97638592003-07-23 21:37:07 +00004037 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00004038 }
Chris Lattner183b3362004-04-09 19:05:30 +00004039
4040 // Try to fold constant and into select arguments.
4041 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00004042 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004043 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004044 if (isa<PHINode>(Op0))
4045 if (Instruction *NV = FoldOpIntoPhi(I))
4046 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004047 }
4048
Chris Lattnerbb74e222003-03-10 23:06:50 +00004049 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004050 if (X == Op1)
4051 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00004052 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004053
Chris Lattnerbb74e222003-03-10 23:06:50 +00004054 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00004055 if (X == Op0)
Chris Lattner07418422007-03-18 22:51:34 +00004056 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00004057
Chris Lattner07418422007-03-18 22:51:34 +00004058
4059 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4060 if (Op1I) {
4061 Value *A, *B;
4062 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4063 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004064 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004065 I.swapOperands();
4066 std::swap(Op0, Op1);
Chris Lattner07418422007-03-18 22:51:34 +00004067 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004068 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004069 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004070 }
Chris Lattner07418422007-03-18 22:51:34 +00004071 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4072 if (Op0 == A) // A^(A^B) == B
4073 return ReplaceInstUsesWith(I, B);
4074 else if (Op0 == B) // A^(B^A) == B
4075 return ReplaceInstUsesWith(I, A);
4076 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner04277992007-04-01 05:36:37 +00004077 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattnerdcd07922006-04-01 08:03:55 +00004078 Op1I->swapOperands();
Chris Lattner04277992007-04-01 05:36:37 +00004079 std::swap(A, B);
4080 }
Chris Lattner07418422007-03-18 22:51:34 +00004081 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattnerdcd07922006-04-01 08:03:55 +00004082 I.swapOperands(); // Simplified below.
4083 std::swap(Op0, Op1);
4084 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004085 }
Chris Lattner07418422007-03-18 22:51:34 +00004086 }
4087
4088 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4089 if (Op0I) {
4090 Value *A, *B;
4091 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4092 if (A == Op1) // (B|A)^B == (A|B)^B
4093 std::swap(A, B);
4094 if (B == Op1) { // (A|B)^B == A & ~B
4095 Instruction *NotB =
4096 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4097 return BinaryOperator::createAnd(A, NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004098 }
Chris Lattner07418422007-03-18 22:51:34 +00004099 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4100 if (Op1 == A) // (A^B)^A == B
4101 return ReplaceInstUsesWith(I, B);
4102 else if (Op1 == B) // (B^A)^A == B
4103 return ReplaceInstUsesWith(I, A);
4104 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4105 if (A == Op1) // (A&B)^A -> (B&A)^A
4106 std::swap(A, B);
4107 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattner6cf49142006-04-01 22:05:01 +00004108 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner07418422007-03-18 22:51:34 +00004109 Instruction *N =
4110 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattnerdcd07922006-04-01 08:03:55 +00004111 return BinaryOperator::createAnd(N, Op1);
4112 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004113 }
Chris Lattner07418422007-03-18 22:51:34 +00004114 }
4115
4116 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4117 if (Op0I && Op1I && Op0I->isShift() &&
4118 Op0I->getOpcode() == Op1I->getOpcode() &&
4119 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4120 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4121 Instruction *NewOp =
4122 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4123 Op1I->getOperand(0),
4124 Op0I->getName()), I);
4125 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4126 Op1I->getOperand(1));
4127 }
4128
4129 if (Op0I && Op1I) {
4130 Value *A, *B, *C, *D;
4131 // (A & B)^(A | B) -> A ^ B
4132 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4133 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4134 if ((A == C && B == D) || (A == D && B == C))
4135 return BinaryOperator::createXor(A, B);
4136 }
4137 // (A | B)^(A & B) -> A ^ B
4138 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4139 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4140 if ((A == C && B == D) || (A == D && B == C))
4141 return BinaryOperator::createXor(A, B);
4142 }
4143
4144 // (A & B)^(C & D)
4145 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4146 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4147 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4148 // (X & Y)^(X & Y) -> (Y^Z) & X
4149 Value *X = 0, *Y = 0, *Z = 0;
4150 if (A == C)
4151 X = A, Y = B, Z = D;
4152 else if (A == D)
4153 X = A, Y = B, Z = C;
4154 else if (B == C)
4155 X = B, Y = A, Z = D;
4156 else if (B == D)
4157 X = B, Y = A, Z = C;
4158
4159 if (X) {
4160 Instruction *NewOp =
4161 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4162 return BinaryOperator::createAnd(NewOp, X);
4163 }
4164 }
4165 }
4166
Reid Spencer266e42b2006-12-23 06:05:41 +00004167 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4168 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4169 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004170 return R;
4171
Chris Lattner3af10532006-05-05 06:39:07 +00004172 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004173 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004174 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004175 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4176 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004177 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004178 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004179 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4180 I.getType(), TD) &&
4181 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4182 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004183 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4184 Op1C->getOperand(0),
4185 I.getName());
4186 InsertNewInstBefore(NewOp, I);
4187 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4188 }
Chris Lattner3af10532006-05-05 06:39:07 +00004189 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004190
Chris Lattner113f4f42002-06-25 16:13:24 +00004191 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004192}
4193
Chris Lattner6862fbd2004-09-29 17:40:11 +00004194/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4195/// overflowed for this type.
4196static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencerf4071162007-03-21 23:19:50 +00004197 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004198 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004199
Reid Spencerf4071162007-03-21 23:19:50 +00004200 if (IsSigned)
4201 if (In2->getValue().isNegative())
4202 return Result->getValue().sgt(In1->getValue());
4203 else
4204 return Result->getValue().slt(In1->getValue());
4205 else
4206 return Result->getValue().ult(In1->getValue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004207}
4208
Chris Lattner0798af32005-01-13 20:14:25 +00004209/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4210/// code necessary to compute the offset from the base pointer (without adding
4211/// in the base pointer). Return the result as a signed integer of intptr size.
4212static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4213 TargetData &TD = IC.getTargetData();
4214 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004215 const Type *IntPtrTy = TD.getIntPtrType();
4216 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004217
4218 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004219 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004220
Chris Lattner0798af32005-01-13 20:14:25 +00004221 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4222 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004223 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004224 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004225 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4226 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004227 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004228 Scale = ConstantExpr::getMul(OpC, Scale);
4229 if (Constant *RC = dyn_cast<Constant>(Result))
4230 Result = ConstantExpr::getAdd(RC, Scale);
4231 else {
4232 // Emit an add instruction.
4233 Result = IC.InsertNewInstBefore(
4234 BinaryOperator::createAdd(Result, Scale,
4235 GEP->getName()+".offs"), I);
4236 }
4237 }
4238 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004239 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004240 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004241 Op->getName()+".c"), I);
4242 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004243 // We'll let instcombine(mul) convert this to a shl if possible.
4244 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4245 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004246
4247 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004248 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004249 GEP->getName()+".offs"), I);
4250 }
4251 }
4252 return Result;
4253}
4254
Reid Spencer266e42b2006-12-23 06:05:41 +00004255/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004256/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004257Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4258 ICmpInst::Predicate Cond,
4259 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004260 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004261
4262 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4263 if (isa<PointerType>(CI->getOperand(0)->getType()))
4264 RHS = CI->getOperand(0);
4265
Chris Lattner0798af32005-01-13 20:14:25 +00004266 Value *PtrBase = GEPLHS->getOperand(0);
4267 if (PtrBase == RHS) {
4268 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004269 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4270 // each index is zero or not.
4271 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004272 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004273 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4274 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004275 bool EmitIt = true;
4276 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4277 if (isa<UndefValue>(C)) // undef index -> undef.
4278 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4279 if (C->isNullValue())
4280 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004281 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4282 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004283 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004284 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004285 ConstantInt::get(Type::Int1Ty,
4286 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004287 }
4288
4289 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004290 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004291 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004292 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4293 if (InVal == 0)
4294 InVal = Comp;
4295 else {
4296 InVal = InsertNewInstBefore(InVal, I);
4297 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004298 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004299 InVal = BinaryOperator::createOr(InVal, Comp);
4300 else // True if all are equal
4301 InVal = BinaryOperator::createAnd(InVal, Comp);
4302 }
4303 }
4304 }
4305
4306 if (InVal)
4307 return InVal;
4308 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004309 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004310 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4311 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004312 }
Chris Lattner0798af32005-01-13 20:14:25 +00004313
Reid Spencer266e42b2006-12-23 06:05:41 +00004314 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004315 // the result to fold to a constant!
4316 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4317 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4318 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004319 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4320 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004321 }
4322 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004323 // If the base pointers are different, but the indices are the same, just
4324 // compare the base pointer.
4325 if (PtrBase != GEPRHS->getOperand(0)) {
4326 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004327 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004328 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004329 if (IndicesTheSame)
4330 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4331 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4332 IndicesTheSame = false;
4333 break;
4334 }
4335
4336 // If all indices are the same, just compare the base pointers.
4337 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004338 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4339 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004340
4341 // Otherwise, the base pointers are different and the indices are
4342 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004343 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004344 }
Chris Lattner0798af32005-01-13 20:14:25 +00004345
Chris Lattner81e84172005-01-13 22:25:21 +00004346 // If one of the GEPs has all zero indices, recurse.
4347 bool AllZeros = true;
4348 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4349 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4350 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4351 AllZeros = false;
4352 break;
4353 }
4354 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004355 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4356 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004357
4358 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004359 AllZeros = true;
4360 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4361 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4362 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4363 AllZeros = false;
4364 break;
4365 }
4366 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004367 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004368
Chris Lattner4fa89822005-01-14 00:20:05 +00004369 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4370 // If the GEPs only differ by one index, compare it.
4371 unsigned NumDifferences = 0; // Keep track of # differences.
4372 unsigned DiffOperand = 0; // The operand that differs.
4373 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4374 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004375 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4376 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004377 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004378 NumDifferences = 2;
4379 break;
4380 } else {
4381 if (NumDifferences++) break;
4382 DiffOperand = i;
4383 }
4384 }
4385
4386 if (NumDifferences == 0) // SAME GEP?
4387 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004388 ConstantInt::get(Type::Int1Ty,
4389 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004390 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004391 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4392 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004393 // Make sure we do a signed comparison here.
4394 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004395 }
4396 }
4397
Reid Spencer266e42b2006-12-23 06:05:41 +00004398 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004399 // the result to fold to a constant!
4400 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4401 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4402 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4403 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4404 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004405 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004406 }
4407 }
4408 return 0;
4409}
4410
Reid Spencer266e42b2006-12-23 06:05:41 +00004411Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4412 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004414
Chris Lattner6ee923f2007-01-14 19:42:17 +00004415 // Fold trivial predicates.
4416 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4417 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4418 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4419 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4420
4421 // Simplify 'fcmp pred X, X'
4422 if (Op0 == Op1) {
4423 switch (I.getPredicate()) {
4424 default: assert(0 && "Unknown predicate!");
4425 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4426 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4427 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4428 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4429 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4430 case FCmpInst::FCMP_OLT: // True if ordered and less than
4431 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4432 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4433
4434 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4435 case FCmpInst::FCMP_ULT: // True if unordered or less than
4436 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4437 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4438 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4439 I.setPredicate(FCmpInst::FCMP_UNO);
4440 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4441 return &I;
4442
4443 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4444 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4445 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4446 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4447 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4448 I.setPredicate(FCmpInst::FCMP_ORD);
4449 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4450 return &I;
4451 }
4452 }
4453
Reid Spencer266e42b2006-12-23 06:05:41 +00004454 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004455 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004456
Reid Spencer266e42b2006-12-23 06:05:41 +00004457 // Handle fcmp with constant RHS
4458 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4459 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4460 switch (LHSI->getOpcode()) {
4461 case Instruction::PHI:
4462 if (Instruction *NV = FoldOpIntoPhi(I))
4463 return NV;
4464 break;
4465 case Instruction::Select:
4466 // If either operand of the select is a constant, we can fold the
4467 // comparison into the select arms, which will cause one to be
4468 // constant folded and the select turned into a bitwise or.
4469 Value *Op1 = 0, *Op2 = 0;
4470 if (LHSI->hasOneUse()) {
4471 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4472 // Fold the known value into the constant operand.
4473 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4474 // Insert a new FCmp of the other select operand.
4475 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4476 LHSI->getOperand(2), RHSC,
4477 I.getName()), I);
4478 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4479 // Fold the known value into the constant operand.
4480 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4481 // Insert a new FCmp of the other select operand.
4482 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4483 LHSI->getOperand(1), RHSC,
4484 I.getName()), I);
4485 }
4486 }
4487
4488 if (Op1)
4489 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4490 break;
4491 }
4492 }
4493
4494 return Changed ? &I : 0;
4495}
4496
4497Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4498 bool Changed = SimplifyCompare(I);
4499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4500 const Type *Ty = Op0->getType();
4501
4502 // icmp X, X
4503 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004504 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4505 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004506
4507 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004508 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004509
4510 // icmp of GlobalValues can never equal each other as long as they aren't
4511 // external weak linkage type.
4512 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4513 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4514 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004515 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4516 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004517
4518 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004519 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004520 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4521 isa<ConstantPointerNull>(Op0)) &&
4522 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004523 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004524 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4525 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004526
Reid Spencer266e42b2006-12-23 06:05:41 +00004527 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004528 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004529 switch (I.getPredicate()) {
4530 default: assert(0 && "Invalid icmp instruction!");
4531 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004532 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004533 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004534 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004535 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004536 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004537 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004538
Reid Spencer266e42b2006-12-23 06:05:41 +00004539 case ICmpInst::ICMP_UGT:
4540 case ICmpInst::ICMP_SGT:
4541 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004542 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004543 case ICmpInst::ICMP_ULT:
4544 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004545 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4546 InsertNewInstBefore(Not, I);
4547 return BinaryOperator::createAnd(Not, Op1);
4548 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 case ICmpInst::ICMP_UGE:
4550 case ICmpInst::ICMP_SGE:
4551 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004552 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004553 case ICmpInst::ICMP_ULE:
4554 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004555 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4556 InsertNewInstBefore(Not, I);
4557 return BinaryOperator::createOr(Not, Op1);
4558 }
4559 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004560 }
4561
Chris Lattner2dd01742004-06-09 04:24:29 +00004562 // See if we are doing a comparison between a constant and an instruction that
4563 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004564 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 switch (I.getPredicate()) {
4566 default: break;
4567 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4568 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004569 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004570 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4571 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4572 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4573 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4574 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004575
Reid Spencer266e42b2006-12-23 06:05:41 +00004576 case ICmpInst::ICMP_SLT:
4577 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004579 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4580 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4581 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4582 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4583 break;
4584
4585 case ICmpInst::ICMP_UGT:
4586 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004587 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004588 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4589 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4590 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4591 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4592 break;
4593
4594 case ICmpInst::ICMP_SGT:
4595 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004596 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004597 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4598 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4599 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4600 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4601 break;
4602
4603 case ICmpInst::ICMP_ULE:
4604 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004605 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004606 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4607 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4608 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4609 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4610 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004611
Reid Spencer266e42b2006-12-23 06:05:41 +00004612 case ICmpInst::ICMP_SLE:
4613 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004614 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004615 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4616 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4617 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4618 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4619 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004620
Reid Spencer266e42b2006-12-23 06:05:41 +00004621 case ICmpInst::ICMP_UGE:
4622 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004623 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004624 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4625 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4626 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4627 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4628 break;
4629
4630 case ICmpInst::ICMP_SGE:
4631 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004632 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004633 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4634 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4635 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4636 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4637 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004638 }
4639
Reid Spencer266e42b2006-12-23 06:05:41 +00004640 // If we still have a icmp le or icmp ge instruction, turn it into the
4641 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004642 // already been handled above, this requires little checking.
4643 //
Reid Spencer624766f2007-03-25 19:55:33 +00004644 switch (I.getPredicate()) {
4645 default: break;
4646 case ICmpInst::ICMP_ULE:
4647 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4648 case ICmpInst::ICMP_SLE:
4649 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4650 case ICmpInst::ICMP_UGE:
4651 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4652 case ICmpInst::ICMP_SGE:
4653 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4654 }
Chris Lattneree0f2802006-02-12 02:07:56 +00004655
4656 // See if we can fold the comparison based on bits known to be zero or one
4657 // in the input.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004658 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4659 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4660 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
Chris Lattneree0f2802006-02-12 02:07:56 +00004661 KnownZero, KnownOne, 0))
4662 return &I;
4663
4664 // Given the known and unknown bits, compute a range that the LHS could be
4665 // in.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004666 if ((KnownOne | KnownZero) != 0) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004667 // Compute the Min, Max and RHS values based on the known bits. For the
4668 // EQ and NE we use unsigned values.
Zhou Sheng150f3bb2007-04-01 17:13:37 +00004669 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4670 const APInt& RHSVal = CI->getValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00004671 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004672 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4673 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004674 } else {
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004675 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4676 Max);
Reid Spencer266e42b2006-12-23 06:05:41 +00004677 }
4678 switch (I.getPredicate()) { // LE/GE have been folded already.
4679 default: assert(0 && "Unknown icmp opcode!");
4680 case ICmpInst::ICMP_EQ:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004681 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004682 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004683 break;
4684 case ICmpInst::ICMP_NE:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004685 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004686 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004687 break;
4688 case ICmpInst::ICMP_ULT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004689 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004690 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004691 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004692 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004693 break;
4694 case ICmpInst::ICMP_UGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004695 if (Min.ugt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004696 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004697 if (Max.ult(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004698 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004699 break;
4700 case ICmpInst::ICMP_SLT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004701 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004702 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004703 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004704 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004705 break;
4706 case ICmpInst::ICMP_SGT:
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004707 if (Min.sgt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004708 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00004709 if (Max.slt(RHSVal))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004710 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004711 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004712 }
4713 }
4714
Reid Spencer266e42b2006-12-23 06:05:41 +00004715 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004716 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004717 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004718 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnera74deaf2007-04-03 17:43:25 +00004719 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4720 return Res;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004721 }
4722
Chris Lattnera74deaf2007-04-03 17:43:25 +00004723 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00004724 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4725 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4726 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004727 case Instruction::GetElementPtr:
4728 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004729 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00004730 bool isAllZeros = true;
4731 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4732 if (!isa<Constant>(LHSI->getOperand(i)) ||
4733 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4734 isAllZeros = false;
4735 break;
4736 }
4737 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004738 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00004739 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4740 }
4741 break;
4742
Chris Lattner77c32c32005-04-23 15:31:55 +00004743 case Instruction::PHI:
4744 if (Instruction *NV = FoldOpIntoPhi(I))
4745 return NV;
4746 break;
4747 case Instruction::Select:
4748 // If either operand of the select is a constant, we can fold the
4749 // comparison into the select arms, which will cause one to be
4750 // constant folded and the select turned into a bitwise or.
4751 Value *Op1 = 0, *Op2 = 0;
4752 if (LHSI->hasOneUse()) {
4753 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4754 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004755 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4756 // Insert a new ICmp of the other select operand.
4757 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4758 LHSI->getOperand(2), RHSC,
4759 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004760 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4761 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00004762 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4763 // Insert a new ICmp of the other select operand.
4764 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4765 LHSI->getOperand(1), RHSC,
4766 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00004767 }
4768 }
Jeff Cohen82639852005-04-23 21:38:35 +00004769
Chris Lattner77c32c32005-04-23 15:31:55 +00004770 if (Op1)
4771 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4772 break;
4773 }
4774 }
4775
Reid Spencer266e42b2006-12-23 06:05:41 +00004776 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00004777 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004778 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004779 return NI;
4780 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004781 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4782 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00004783 return NI;
4784
Reid Spencer266e42b2006-12-23 06:05:41 +00004785 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00004786 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4787 // now.
4788 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4789 if (isa<PointerType>(Op0->getType()) &&
4790 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004791 // We keep moving the cast from the left operand over to the right
4792 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00004793 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004794
Chris Lattner64d87b02007-01-06 01:45:59 +00004795 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4796 // so eliminate it as well.
4797 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4798 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004799
Chris Lattner16930792003-11-03 04:25:02 +00004800 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00004801 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00004802 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004803 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004804 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00004805 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00004806 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004807 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004808 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00004809 }
Chris Lattner64d87b02007-01-06 01:45:59 +00004810 }
4811
4812 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004813 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00004814 // This comes up when you have code like
4815 // int X = A < B;
4816 // if (X) ...
4817 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004818 // with a constant or another cast from the same type.
4819 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004820 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004821 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004822 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004823
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004824 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00004825 Value *A, *B, *C, *D;
4826 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4827 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4828 Value *OtherVal = A == Op1 ? B : A;
4829 return new ICmpInst(I.getPredicate(), OtherVal,
4830 Constant::getNullValue(A->getType()));
4831 }
4832
4833 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4834 // A^c1 == C^c2 --> A == C^(c1^c2)
4835 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4836 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
4837 if (Op1->hasOneUse()) {
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00004838 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner17c7c032007-01-05 03:04:57 +00004839 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
4840 return new ICmpInst(I.getPredicate(), A,
4841 InsertNewInstBefore(Xor, I));
4842 }
4843
4844 // A^B == A^D -> B == D
4845 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4846 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4847 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4848 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4849 }
4850 }
4851
4852 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4853 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004854 // A == (A^B) -> B == 0
4855 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00004856 return new ICmpInst(I.getPredicate(), OtherVal,
4857 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00004858 }
4859 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004860 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00004861 return new ICmpInst(I.getPredicate(), B,
4862 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00004863 }
4864 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004865 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 return new ICmpInst(I.getPredicate(), B,
4867 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004868 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004869
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004870 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4871 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4872 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4873 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4874 Value *X = 0, *Y = 0, *Z = 0;
4875
4876 if (A == C) {
4877 X = B; Y = D; Z = A;
4878 } else if (A == D) {
4879 X = B; Y = C; Z = A;
4880 } else if (B == C) {
4881 X = A; Y = D; Z = B;
4882 } else if (B == D) {
4883 X = A; Y = C; Z = B;
4884 }
4885
4886 if (X) { // Build (X^Y) & Z
4887 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4888 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4889 I.setOperand(0, Op1);
4890 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4891 return &I;
4892 }
4893 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004894 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004895 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004896}
4897
Chris Lattnera74deaf2007-04-03 17:43:25 +00004898/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
4899///
4900Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
4901 Instruction *LHSI,
4902 ConstantInt *RHS) {
4903 const APInt &RHSV = RHS->getValue();
4904
4905 switch (LHSI->getOpcode()) {
4906 case Instruction::Xor: // (icmp pred (and X, XorCST), CI)
4907 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4908 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
4909 // fold the xor.
4910 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
4911 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
4912 Value *CompareVal = LHSI->getOperand(0);
4913
4914 // If the sign bit of the XorCST is not set, there is no change to
4915 // the operation, just stop using the Xor.
4916 if (!XorCST->getValue().isNegative()) {
4917 ICI.setOperand(0, CompareVal);
4918 AddToWorkList(LHSI);
4919 return &ICI;
4920 }
4921
4922 // Was the old condition true if the operand is positive?
4923 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
4924
4925 // If so, the new one isn't.
4926 isTrueIfPositive ^= true;
4927
4928 if (isTrueIfPositive)
4929 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
4930 else
4931 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
4932 }
4933 }
4934 break;
4935 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
4936 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4937 LHSI->getOperand(0)->hasOneUse()) {
4938 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4939
4940 // If the LHS is an AND of a truncating cast, we can widen the
4941 // and/compare to be the input width without changing the value
4942 // produced, eliminating a cast.
4943 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
4944 // We can do this transformation if either the AND constant does not
4945 // have its sign bit set or if it is an equality comparison.
4946 // Extending a relational comparison when we're checking the sign
4947 // bit would not work.
4948 if (Cast->hasOneUse() &&
4949 (ICI.isEquality() || AndCST->getValue().isPositive() &&
4950 RHSV.isPositive())) {
4951 uint32_t BitWidth =
4952 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
4953 APInt NewCST = AndCST->getValue();
4954 NewCST.zext(BitWidth);
4955 APInt NewCI = RHSV;
4956 NewCI.zext(BitWidth);
4957 Instruction *NewAnd =
4958 BinaryOperator::createAnd(Cast->getOperand(0),
4959 ConstantInt::get(NewCST),LHSI->getName());
4960 InsertNewInstBefore(NewAnd, ICI);
4961 return new ICmpInst(ICI.getPredicate(), NewAnd,
4962 ConstantInt::get(NewCI));
4963 }
4964 }
4965
4966 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4967 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4968 // happens a LOT in code produced by the C front-end, for bitfield
4969 // access.
4970 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4971 if (Shift && !Shift->isShift())
4972 Shift = 0;
4973
4974 ConstantInt *ShAmt;
4975 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4976 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4977 const Type *AndTy = AndCST->getType(); // Type of the and.
4978
4979 // We can fold this as long as we can't shift unknown bits
4980 // into the mask. This can only happen with signed shift
4981 // rights, as they sign-extend.
4982 if (ShAmt) {
4983 bool CanFold = Shift->isLogicalShift();
4984 if (!CanFold) {
4985 // To test for the bad case of the signed shr, see if any
4986 // of the bits shifted in could be tested after the mask.
4987 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
4988 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
4989
4990 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
4991 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
4992 AndCST->getValue()) == 0)
4993 CanFold = true;
4994 }
4995
4996 if (CanFold) {
4997 Constant *NewCst;
4998 if (Shift->getOpcode() == Instruction::Shl)
4999 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5000 else
5001 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5002
5003 // Check to see if we are shifting out any of the bits being
5004 // compared.
5005 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5006 // If we shifted bits out, the fold is not going to work out.
5007 // As a special case, check to see if this means that the
5008 // result is always true or false now.
5009 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5010 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5011 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5012 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5013 } else {
5014 ICI.setOperand(1, NewCst);
5015 Constant *NewAndCST;
5016 if (Shift->getOpcode() == Instruction::Shl)
5017 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5018 else
5019 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5020 LHSI->setOperand(1, NewAndCST);
5021 LHSI->setOperand(0, Shift->getOperand(0));
5022 AddToWorkList(Shift); // Shift is dead.
5023 AddUsesToWorkList(ICI);
5024 return &ICI;
5025 }
5026 }
5027 }
5028
5029 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5030 // preferable because it allows the C<<Y expression to be hoisted out
5031 // of a loop if Y is invariant and X is not.
5032 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5033 ICI.isEquality() && !Shift->isArithmeticShift() &&
5034 isa<Instruction>(Shift->getOperand(0))) {
5035 // Compute C << Y.
5036 Value *NS;
5037 if (Shift->getOpcode() == Instruction::LShr) {
5038 NS = BinaryOperator::createShl(AndCST,
5039 Shift->getOperand(1), "tmp");
5040 } else {
5041 // Insert a logical shift.
5042 NS = BinaryOperator::createLShr(AndCST,
5043 Shift->getOperand(1), "tmp");
5044 }
5045 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5046
5047 // Compute X & (C << Y).
5048 Instruction *NewAnd =
5049 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5050 InsertNewInstBefore(NewAnd, ICI);
5051
5052 ICI.setOperand(0, NewAnd);
5053 return &ICI;
5054 }
5055 }
5056 break;
5057
5058 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5059 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5060 if (ICI.isEquality()) {
5061 uint32_t TypeBits = RHSV.getBitWidth();
5062
5063 // Check that the shift amount is in range. If not, don't perform
5064 // undefined shifts. When the shift is visited it will be
5065 // simplified.
5066 if (ShAmt->uge(TypeBits))
5067 break;
5068
5069 // If we are comparing against bits always shifted out, the
5070 // comparison cannot succeed.
5071 Constant *Comp =
5072 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5073 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5074 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5075 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5076 return ReplaceInstUsesWith(ICI, Cst);
5077 }
5078
5079 if (LHSI->hasOneUse()) {
5080 // Otherwise strength reduce the shift into an and.
5081 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5082 Constant *Mask =
5083 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5084
5085 Instruction *AndI =
5086 BinaryOperator::createAnd(LHSI->getOperand(0),
5087 Mask, LHSI->getName()+".mask");
5088 Value *And = InsertNewInstBefore(AndI, ICI);
5089 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattnere5bbb3c2007-04-03 23:29:39 +00005090 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattnera74deaf2007-04-03 17:43:25 +00005091 }
5092 }
5093 }
5094 break;
5095
5096 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5097 case Instruction::AShr:
5098 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5099 if (ICI.isEquality()) {
5100 // Check that the shift amount is in range. If not, don't perform
5101 // undefined shifts. When the shift is visited it will be
5102 // simplified.
5103 uint32_t TypeBits = RHSV.getBitWidth();
5104 if (ShAmt->uge(TypeBits))
5105 break;
5106 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5107
5108 // If we are comparing against bits always shifted out, the
5109 // comparison cannot succeed.
5110 APInt Comp = RHSV << ShAmtVal;
5111 if (LHSI->getOpcode() == Instruction::LShr)
5112 Comp = Comp.lshr(ShAmtVal);
5113 else
5114 Comp = Comp.ashr(ShAmtVal);
5115
5116 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5117 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5118 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5119 return ReplaceInstUsesWith(ICI, Cst);
5120 }
5121
5122 if (LHSI->hasOneUse() || RHSV == 0) {
5123 // Otherwise strength reduce the shift into an and.
5124 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5125 Constant *Mask = ConstantInt::get(Val);
5126
5127 Instruction *AndI =
5128 BinaryOperator::createAnd(LHSI->getOperand(0),
5129 Mask, LHSI->getName()+".mask");
5130 Value *And = InsertNewInstBefore(AndI, ICI);
5131 return new ICmpInst(ICI.getPredicate(), And,
5132 ConstantExpr::getShl(RHS, ShAmt));
5133 }
5134 }
5135 }
5136 break;
5137
5138 case Instruction::SDiv:
5139 case Instruction::UDiv:
5140 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5141 // Fold this div into the comparison, producing a range check.
5142 // Determine, based on the divide type, what the range is being
5143 // checked. If there is an overflow on the low or high side, remember
5144 // it, otherwise compute the range [low, hi) bounding the new value.
5145 // See: InsertRangeTest above for the kinds of replacements possible.
5146 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5147 // FIXME: If the operand types don't match the type of the divide
5148 // then don't attempt this transform. The code below doesn't have the
5149 // logic to deal with a signed divide and an unsigned compare (and
5150 // vice versa). This is because (x /s C1) <s C2 produces different
5151 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5152 // (x /u C1) <u C2. Simply casting the operands and result won't
5153 // work. :( The if statement below tests that condition and bails
5154 // if it finds it.
5155 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5156 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5157 break;
5158 if (DivRHS->isZero())
5159 break; // Don't hack on div by zero
5160
5161 // Initialize the variables that will indicate the nature of the
5162 // range check.
5163 bool LoOverflow = false, HiOverflow = false;
5164 ConstantInt *LoBound = 0, *HiBound = 0;
5165
5166 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5167 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5168 // C2 (CI). By solving for X we can turn this into a range check
5169 // instead of computing a divide.
5170 ConstantInt *Prod = Multiply(RHS, DivRHS);
5171
5172 // Determine if the product overflows by seeing if the product is
5173 // not equal to the divide. Make sure we do the same kind of divide
5174 // as in the LHS instruction that we're folding.
5175 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5176 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5177
5178 // Get the ICmp opcode
5179 ICmpInst::Predicate predicate = ICI.getPredicate();
5180
5181 if (!DivIsSigned) { // udiv
5182 LoBound = Prod;
5183 LoOverflow = ProdOV;
5184 HiOverflow = ProdOV ||
5185 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5186 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5187 if (RHSV == 0) { // (X / pos) op 0
5188 // Can't overflow.
5189 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5190 HiBound = DivRHS;
5191 } else if (RHSV.isPositive()) { // (X / pos) op pos
5192 LoBound = Prod;
5193 LoOverflow = ProdOV;
5194 HiOverflow = ProdOV ||
5195 AddWithOverflow(HiBound, Prod, DivRHS, true);
5196 } else { // (X / pos) op neg
5197 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5198 LoOverflow = AddWithOverflow(LoBound, Prod,
5199 cast<ConstantInt>(DivRHSH), true);
5200 HiBound = AddOne(Prod);
5201 HiOverflow = ProdOV;
5202 }
5203 } else { // Divisor is < 0.
5204 if (RHSV == 0) { // (X / neg) op 0
5205 LoBound = AddOne(DivRHS);
5206 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5207 if (HiBound == DivRHS)
5208 LoBound = 0; // - INTMIN = INTMIN
5209 } else if (RHSV.isPositive()) { // (X / neg) op pos
5210 HiOverflow = LoOverflow = ProdOV;
5211 if (!LoOverflow)
5212 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5213 true);
5214 HiBound = AddOne(Prod);
5215 } else { // (X / neg) op neg
5216 LoBound = Prod;
5217 LoOverflow = HiOverflow = ProdOV;
5218 HiBound = Subtract(Prod, DivRHS);
5219 }
5220
5221 // Dividing by a negate swaps the condition.
5222 predicate = ICmpInst::getSwappedPredicate(predicate);
5223 }
5224
5225 if (LoBound) {
5226 Value *X = LHSI->getOperand(0);
5227 switch (predicate) {
5228 default: assert(0 && "Unhandled icmp opcode!");
5229 case ICmpInst::ICMP_EQ:
5230 if (LoOverflow && HiOverflow)
5231 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5232 else if (HiOverflow)
5233 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5234 ICmpInst::ICMP_UGE, X, LoBound);
5235 else if (LoOverflow)
5236 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5237 ICmpInst::ICMP_ULT, X, HiBound);
5238 else
5239 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5240 true, ICI);
5241 case ICmpInst::ICMP_NE:
5242 if (LoOverflow && HiOverflow)
5243 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5244 else if (HiOverflow)
5245 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5246 ICmpInst::ICMP_ULT, X, LoBound);
5247 else if (LoOverflow)
5248 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5249 ICmpInst::ICMP_UGE, X, HiBound);
5250 else
5251 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5252 false, ICI);
5253 case ICmpInst::ICMP_ULT:
5254 case ICmpInst::ICMP_SLT:
5255 if (LoOverflow)
5256 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5257 return new ICmpInst(predicate, X, LoBound);
5258 case ICmpInst::ICMP_UGT:
5259 case ICmpInst::ICMP_SGT:
5260 if (HiOverflow)
5261 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5262 if (predicate == ICmpInst::ICMP_UGT)
5263 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5264 else
5265 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5266 }
5267 }
5268 }
5269 break;
5270 }
5271
5272 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5273 if (ICI.isEquality()) {
5274 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5275
5276 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5277 // the second operand is a constant, simplify a bit.
5278 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5279 switch (BO->getOpcode()) {
5280 case Instruction::SRem:
5281 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5282 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5283 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5284 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5285 Instruction *NewRem =
5286 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5287 BO->getName());
5288 InsertNewInstBefore(NewRem, ICI);
5289 return new ICmpInst(ICI.getPredicate(), NewRem,
5290 Constant::getNullValue(BO->getType()));
5291 }
5292 }
5293 break;
5294 case Instruction::Add:
5295 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5296 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5297 if (BO->hasOneUse())
5298 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5299 Subtract(RHS, BOp1C));
5300 } else if (RHSV == 0) {
5301 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5302 // efficiently invertible, or if the add has just this one use.
5303 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5304
5305 if (Value *NegVal = dyn_castNegVal(BOp1))
5306 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5307 else if (Value *NegVal = dyn_castNegVal(BOp0))
5308 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5309 else if (BO->hasOneUse()) {
5310 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5311 InsertNewInstBefore(Neg, ICI);
5312 Neg->takeName(BO);
5313 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5314 }
5315 }
5316 break;
5317 case Instruction::Xor:
5318 // For the xor case, we can xor two constants together, eliminating
5319 // the explicit xor.
5320 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5321 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5322 ConstantExpr::getXor(RHS, BOC));
5323
5324 // FALLTHROUGH
5325 case Instruction::Sub:
5326 // Replace (([sub|xor] A, B) != 0) with (A != B)
5327 if (RHSV == 0)
5328 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5329 BO->getOperand(1));
5330 break;
5331
5332 case Instruction::Or:
5333 // If bits are being or'd in that are not present in the constant we
5334 // are comparing against, then the comparison could never succeed!
5335 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5336 Constant *NotCI = ConstantExpr::getNot(RHS);
5337 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5338 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5339 isICMP_NE));
5340 }
5341 break;
5342
5343 case Instruction::And:
5344 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5345 // If bits are being compared against that are and'd out, then the
5346 // comparison can never succeed!
5347 if ((RHSV & ~BOC->getValue()) != 0)
5348 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5349 isICMP_NE));
5350
5351 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5352 if (RHS == BOC && RHSV.isPowerOf2())
5353 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5354 ICmpInst::ICMP_NE, LHSI,
5355 Constant::getNullValue(RHS->getType()));
5356
5357 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5358 if (isSignBit(BOC)) {
5359 Value *X = BO->getOperand(0);
5360 Constant *Zero = Constant::getNullValue(X->getType());
5361 ICmpInst::Predicate pred = isICMP_NE ?
5362 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5363 return new ICmpInst(pred, X, Zero);
5364 }
5365
5366 // ((X & ~7) == 0) --> X < 8
5367 if (RHSV == 0 && isHighOnes(BOC)) {
5368 Value *X = BO->getOperand(0);
5369 Constant *NegX = ConstantExpr::getNeg(BOC);
5370 ICmpInst::Predicate pred = isICMP_NE ?
5371 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5372 return new ICmpInst(pred, X, NegX);
5373 }
5374 }
5375 default: break;
5376 }
5377 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5378 // Handle icmp {eq|ne} <intrinsic>, intcst.
5379 if (II->getIntrinsicID() == Intrinsic::bswap) {
5380 AddToWorkList(II);
5381 ICI.setOperand(0, II->getOperand(1));
5382 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5383 return &ICI;
5384 }
5385 }
5386 } else { // Not a ICMP_EQ/ICMP_NE
5387 // If the LHS is a cast from an integral value of the same size, then
5388 // since we know the RHS is a constant, try to simlify.
5389 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5390 Value *CastOp = Cast->getOperand(0);
5391 const Type *SrcTy = CastOp->getType();
5392 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5393 if (SrcTy->isInteger() &&
5394 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5395 // If this is an unsigned comparison, try to make the comparison use
5396 // smaller constant values.
5397 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5398 // X u< 128 => X s> -1
5399 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5400 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5401 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5402 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5403 // X u> 127 => X s< 0
5404 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5405 Constant::getNullValue(SrcTy));
5406 }
5407 }
5408 }
5409 }
5410 return 0;
5411}
5412
5413/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5414/// We only handle extending casts so far.
5415///
Reid Spencer266e42b2006-12-23 06:05:41 +00005416Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5417 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005418 Value *LHSCIOp = LHSCI->getOperand(0);
5419 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005420 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005421 Value *RHSCIOp;
5422
Reid Spencer266e42b2006-12-23 06:05:41 +00005423 // We only handle extension cast instructions, so far. Enforce this.
5424 if (LHSCI->getOpcode() != Instruction::ZExt &&
5425 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005426 return 0;
5427
Reid Spencer266e42b2006-12-23 06:05:41 +00005428 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5429 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005430
Reid Spencer266e42b2006-12-23 06:05:41 +00005431 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005432 // Not an extension from the same type?
5433 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005434 if (RHSCIOp->getType() != LHSCIOp->getType())
5435 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005436
5437 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5438 // and the other is a zext), then we can't handle this.
5439 if (CI->getOpcode() != LHSCI->getOpcode())
5440 return 0;
5441
5442 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5443 // then we can't handle this.
5444 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5445 return 0;
5446
5447 // Okay, just insert a compare of the reduced operands now!
5448 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005449 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005450
Reid Spencer266e42b2006-12-23 06:05:41 +00005451 // If we aren't dealing with a constant on the RHS, exit early
5452 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5453 if (!CI)
5454 return 0;
5455
5456 // Compute the constant that would happen if we truncated to SrcTy then
5457 // reextended to DestTy.
5458 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5459 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5460
5461 // If the re-extended constant didn't change...
5462 if (Res2 == CI) {
5463 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5464 // For example, we might have:
5465 // %A = sext short %X to uint
5466 // %B = icmp ugt uint %A, 1330
5467 // It is incorrect to transform this into
5468 // %B = icmp ugt short %X, 1330
5469 // because %A may have negative value.
5470 //
5471 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5472 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005473 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005474 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5475 else
5476 return 0;
5477 }
5478
5479 // The re-extended constant changed so the constant cannot be represented
5480 // in the shorter type. Consequently, we cannot emit a simple comparison.
5481
5482 // First, handle some easy cases. We know the result cannot be equal at this
5483 // point so handle the ICI.isEquality() cases
5484 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005485 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005486 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005487 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005488
5489 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5490 // should have been folded away previously and not enter in here.
5491 Value *Result;
5492 if (isSignedCmp) {
5493 // We're performing a signed comparison.
Reid Spencerc3e3b8a2007-03-22 20:36:03 +00005494 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng75b871f2007-01-11 12:24:14 +00005495 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005496 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005497 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005498 } else {
5499 // We're performing an unsigned comparison.
5500 if (isSignedExt) {
5501 // We're performing an unsigned comp with a sign extended value.
5502 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005503 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005504 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5505 NegOne, ICI.getName()), ICI);
5506 } else {
5507 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005508 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005509 }
5510 }
5511
5512 // Finally, return the value computed.
5513 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5514 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5515 return ReplaceInstUsesWith(ICI, Result);
5516 } else {
5517 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5518 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5519 "ICmp should be folded!");
5520 if (Constant *CI = dyn_cast<Constant>(Result))
5521 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5522 else
5523 return BinaryOperator::createNot(Result);
5524 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005525}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005526
Reid Spencer2341c222007-02-02 02:16:23 +00005527Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5528 return commonShiftTransforms(I);
5529}
5530
5531Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5532 return commonShiftTransforms(I);
5533}
5534
5535Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5536 return commonShiftTransforms(I);
5537}
5538
5539Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5540 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005542
5543 // shl X, 0 == X and shr X, 0 == X
5544 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005545 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005546 Op0 == Constant::getNullValue(Op0->getType()))
5547 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005548
Reid Spencer266e42b2006-12-23 06:05:41 +00005549 if (isa<UndefValue>(Op0)) {
5550 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005551 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005552 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005553 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5554 }
5555 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005556 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5557 return ReplaceInstUsesWith(I, Op0);
5558 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005560 }
5561
Chris Lattnerd4dee402006-11-10 23:38:52 +00005562 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5563 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005564 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005565 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005566 return ReplaceInstUsesWith(I, CSI);
5567
Chris Lattner183b3362004-04-09 19:05:30 +00005568 // Try to fold constant and into select arguments.
5569 if (isa<Constant>(Op0))
5570 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005571 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005572 return R;
5573
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005574 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005575 if (I.isArithmeticShift()) {
Reid Spencer6274c722007-03-23 18:46:34 +00005576 if (MaskedValueIsZero(Op0,
5577 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005578 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005579 }
5580 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005581
Reid Spencere0fc4df2006-10-20 07:07:24 +00005582 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005583 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5584 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005585 return 0;
5586}
5587
Reid Spencere0fc4df2006-10-20 07:07:24 +00005588Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005589 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005590 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005591
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005592 // See if we can simplify any instructions used by the instruction whose sole
5593 // purpose is to compute bits we don't care about.
Reid Spencer6274c722007-03-23 18:46:34 +00005594 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5595 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5596 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005597 KnownZero, KnownOne))
5598 return &I;
5599
Chris Lattner14553932006-01-06 07:12:35 +00005600 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5601 // of a signed value.
5602 //
Zhou Shengb25806f2007-03-30 09:29:48 +00005603 if (Op1->uge(TypeBits)) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005604 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005605 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5606 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005607 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005608 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005609 }
Chris Lattner14553932006-01-06 07:12:35 +00005610 }
5611
5612 // ((X*C1) << C2) == (X * (C1 << C2))
5613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5614 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5615 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5616 return BinaryOperator::createMul(BO->getOperand(0),
5617 ConstantExpr::getShl(BOOp, Op1));
5618
5619 // Try to fold constant and into select arguments.
5620 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5621 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5622 return R;
5623 if (isa<PHINode>(Op0))
5624 if (Instruction *NV = FoldOpIntoPhi(I))
5625 return NV;
5626
5627 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005628 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5629 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5630 Value *V1, *V2;
5631 ConstantInt *CC;
5632 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005633 default: break;
5634 case Instruction::Add:
5635 case Instruction::And:
5636 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005637 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005638 // These operators commute.
5639 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005640 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5641 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005642 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005643 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005644 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005645 Op0BO->getName());
5646 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005647 Instruction *X =
5648 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5649 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005650 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005651 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005652 return BinaryOperator::createAnd(X, ConstantInt::get(
5653 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005654 }
Chris Lattner14553932006-01-06 07:12:35 +00005655
Chris Lattner797dee72005-09-18 06:30:59 +00005656 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005657 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005658 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencer2f34b982007-02-02 14:41:37 +00005659 match(Op0BOOp1,
5660 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattnerfe53cf22007-03-05 00:11:19 +00005661 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5662 V2 == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005663 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005664 Op0BO->getOperand(0), Op1,
5665 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005666 InsertNewInstBefore(YS, I); // (Y << C)
5667 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005668 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005669 V1->getName()+".mask");
5670 InsertNewInstBefore(XM, I); // X & (CC << C)
5671
5672 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5673 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005674 }
Chris Lattner14553932006-01-06 07:12:35 +00005675
Reid Spencer2f34b982007-02-02 14:41:37 +00005676 // FALL THROUGH.
5677 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005678 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005679 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5680 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005681 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005682 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005683 Op0BO->getOperand(1), Op1,
5684 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005685 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005686 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005687 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005688 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005689 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Shengfd28a332007-03-30 17:20:39 +00005690 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng5e60a4a2007-03-30 05:45:18 +00005691 return BinaryOperator::createAnd(X, ConstantInt::get(
5692 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner797dee72005-09-18 06:30:59 +00005693 }
Chris Lattner14553932006-01-06 07:12:35 +00005694
Chris Lattner1df0e982006-05-31 21:14:00 +00005695 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005696 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5697 match(Op0BO->getOperand(0),
5698 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005699 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005700 cast<BinaryOperator>(Op0BO->getOperand(0))
5701 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005702 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005703 Op0BO->getOperand(1), Op1,
5704 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005705 InsertNewInstBefore(YS, I); // (Y << C)
5706 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005707 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005708 V1->getName()+".mask");
5709 InsertNewInstBefore(XM, I); // X & (CC << C)
5710
Chris Lattner1df0e982006-05-31 21:14:00 +00005711 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005712 }
Chris Lattner14553932006-01-06 07:12:35 +00005713
Chris Lattner27cb9db2005-09-18 05:12:10 +00005714 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005715 }
Chris Lattner14553932006-01-06 07:12:35 +00005716 }
5717
5718
5719 // If the operand is an bitwise operator with a constant RHS, and the
5720 // shift is the only use, we can pull it out of the shift.
5721 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5722 bool isValid = true; // Valid only for And, Or, Xor
5723 bool highBitSet = false; // Transform if high bit of constant set?
5724
5725 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005726 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005727 case Instruction::Add:
5728 isValid = isLeftShift;
5729 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005730 case Instruction::Or:
5731 case Instruction::Xor:
5732 highBitSet = false;
5733 break;
5734 case Instruction::And:
5735 highBitSet = true;
5736 break;
Chris Lattner14553932006-01-06 07:12:35 +00005737 }
5738
5739 // If this is a signed shift right, and the high bit is modified
5740 // by the logical operation, do not perform the transformation.
5741 // The highBitSet boolean indicates the value of the high bit of
5742 // the constant which would cause it to be modified for this
5743 // operation.
5744 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005745 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005746 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner14553932006-01-06 07:12:35 +00005747 }
5748
5749 if (isValid) {
5750 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5751
5752 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005753 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005754 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005755 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005756
5757 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5758 NewRHS);
5759 }
5760 }
5761 }
5762 }
5763
Chris Lattnereb372a02006-01-06 07:52:12 +00005764 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005765 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5766 if (ShiftOp && !ShiftOp->isShift())
5767 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005768
Reid Spencere0fc4df2006-10-20 07:07:24 +00005769 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005770 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Shengb25806f2007-03-30 09:29:48 +00005771 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5772 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattner3e009e82007-02-05 00:57:54 +00005773 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5774 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5775 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005776
Zhou Sheng56cda952007-04-02 08:20:41 +00005777 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencer6274c722007-03-23 18:46:34 +00005778 if (AmtSum > TypeBits)
5779 AmtSum = TypeBits;
Chris Lattner3e009e82007-02-05 00:57:54 +00005780
5781 const IntegerType *Ty = cast<IntegerType>(I.getType());
5782
5783 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005784 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005785 return BinaryOperator::create(I.getOpcode(), X,
5786 ConstantInt::get(Ty, AmtSum));
5787 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5788 I.getOpcode() == Instruction::AShr) {
5789 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5790 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5791 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5792 I.getOpcode() == Instruction::LShr) {
5793 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5794 Instruction *Shift =
5795 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5796 InsertNewInstBefore(Shift, I);
5797
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005798 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005799 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005800 }
5801
Chris Lattner3e009e82007-02-05 00:57:54 +00005802 // Okay, if we get here, one shift must be left, and the other shift must be
5803 // right. See if the amounts are equal.
5804 if (ShiftAmt1 == ShiftAmt2) {
5805 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5806 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer52830322007-03-25 21:11:44 +00005807 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005808 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005809 }
5810 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5811 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00005812 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencer6274c722007-03-23 18:46:34 +00005813 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005814 }
5815 // We can simplify ((X << C) >>s C) into a trunc + sext.
5816 // NOTE: we could do this for any C, but that would make 'unusual' integer
5817 // types. For now, just stick to ones well-supported by the code
5818 // generators.
5819 const Type *SExtType = 0;
5820 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Sheng23f7a1c2007-03-28 15:02:20 +00005821 case 1 :
5822 case 8 :
5823 case 16 :
5824 case 32 :
5825 case 64 :
5826 case 128:
5827 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5828 break;
Chris Lattner3e009e82007-02-05 00:57:54 +00005829 default: break;
5830 }
5831 if (SExtType) {
5832 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5833 InsertNewInstBefore(NewTrunc, I);
5834 return new SExtInst(NewTrunc, Ty);
5835 }
5836 // Otherwise, we can't handle it yet.
5837 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng56cda952007-04-02 08:20:41 +00005838 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005839
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005840 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005841 if (I.getOpcode() == Instruction::Shl) {
5842 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5843 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005844 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005845 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005846 InsertNewInstBefore(Shift, I);
5847
Reid Spencer52830322007-03-25 21:11:44 +00005848 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5849 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005850 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005851
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005852 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005853 if (I.getOpcode() == Instruction::LShr) {
5854 assert(ShiftOp->getOpcode() == Instruction::Shl);
5855 Instruction *Shift =
5856 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5857 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005858
Reid Spencer769a5a82007-03-26 17:18:58 +00005859 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005860 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005861 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005862
5863 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5864 } else {
5865 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng56cda952007-04-02 08:20:41 +00005866 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005867
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005868 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005869 if (I.getOpcode() == Instruction::Shl) {
5870 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5871 ShiftOp->getOpcode() == Instruction::AShr);
5872 Instruction *Shift =
5873 BinaryOperator::create(ShiftOp->getOpcode(), X,
5874 ConstantInt::get(Ty, ShiftDiff));
5875 InsertNewInstBefore(Shift, I);
5876
Reid Spencer52830322007-03-25 21:11:44 +00005877 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005878 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005879 }
5880
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005881 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005882 if (I.getOpcode() == Instruction::LShr) {
5883 assert(ShiftOp->getOpcode() == Instruction::Shl);
5884 Instruction *Shift =
5885 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5886 InsertNewInstBefore(Shift, I);
5887
Reid Spencer441486c2007-03-26 23:45:51 +00005888 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencer6274c722007-03-23 18:46:34 +00005889 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner3e009e82007-02-05 00:57:54 +00005890 }
5891
5892 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005893 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005894 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005895 return 0;
5896}
5897
Chris Lattner48a44f72002-05-02 17:06:02 +00005898
Chris Lattner8f663e82005-10-29 04:36:15 +00005899/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5900/// expression. If so, decompose it, returning some value X, such that Val is
5901/// X*Scale+Offset.
5902///
5903static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5904 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005905 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005906 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005907 Offset = CI->getZExtValue();
5908 Scale = 1;
5909 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005910 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5911 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005912 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005913 if (I->getOpcode() == Instruction::Shl) {
5914 // This is a value scaled by '1 << the shift amt'.
5915 Scale = 1U << CUI->getZExtValue();
5916 Offset = 0;
5917 return I->getOperand(0);
5918 } else if (I->getOpcode() == Instruction::Mul) {
5919 // This value is scaled by 'CUI'.
5920 Scale = CUI->getZExtValue();
5921 Offset = 0;
5922 return I->getOperand(0);
5923 } else if (I->getOpcode() == Instruction::Add) {
5924 // We have X+C. Check to see if we really have (X*C2)+C1,
5925 // where C1 is divisible by C2.
5926 unsigned SubScale;
5927 Value *SubVal =
5928 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5929 Offset += CUI->getZExtValue();
5930 if (SubScale > 1 && (Offset % SubScale == 0)) {
5931 Scale = SubScale;
5932 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005933 }
5934 }
5935 }
5936 }
5937 }
5938
5939 // Otherwise, we can't look past this.
5940 Scale = 1;
5941 Offset = 0;
5942 return Val;
5943}
5944
5945
Chris Lattner216be912005-10-24 06:03:58 +00005946/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5947/// try to eliminate the cast by moving the type information into the alloc.
5948Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5949 AllocationInst &AI) {
5950 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005951 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005952
Chris Lattnerac87beb2005-10-24 06:22:12 +00005953 // Remove any uses of AI that are dead.
5954 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005955
Chris Lattnerac87beb2005-10-24 06:22:12 +00005956 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5957 Instruction *User = cast<Instruction>(*UI++);
5958 if (isInstructionTriviallyDead(User)) {
5959 while (UI != E && *UI == User)
5960 ++UI; // If this instruction uses AI more than once, don't break UI.
5961
Chris Lattnerac87beb2005-10-24 06:22:12 +00005962 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005963 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005964 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005965 }
5966 }
5967
Chris Lattner216be912005-10-24 06:03:58 +00005968 // Get the type really allocated and the type casted to.
5969 const Type *AllocElTy = AI.getAllocatedType();
5970 const Type *CastElTy = PTy->getElementType();
5971 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005972
Chris Lattner945e4372007-02-14 05:52:17 +00005973 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5974 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005975 if (CastElTyAlign < AllocElTyAlign) return 0;
5976
Chris Lattner46705b22005-10-24 06:35:18 +00005977 // If the allocation has multiple uses, only promote it if we are strictly
5978 // increasing the alignment of the resultant allocation. If we keep it the
5979 // same, we open the door to infinite loops of various kinds.
5980 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5981
Chris Lattner216be912005-10-24 06:03:58 +00005982 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5983 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005984 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005985
Chris Lattner8270c332005-10-29 03:19:53 +00005986 // See if we can satisfy the modulus by pulling a scale out of the array
5987 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005988 unsigned ArraySizeScale, ArrayOffset;
5989 Value *NumElements = // See if the array size is a decomposable linear expr.
5990 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5991
Chris Lattner8270c332005-10-29 03:19:53 +00005992 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5993 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005994 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5995 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005996
Chris Lattner8270c332005-10-29 03:19:53 +00005997 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5998 Value *Amt = 0;
5999 if (Scale == 1) {
6000 Amt = NumElements;
6001 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00006002 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00006003 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6004 if (isa<ConstantInt>(NumElements))
Zhou Sheng9bc8ab12007-04-02 13:45:30 +00006005 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencere0fc4df2006-10-20 07:07:24 +00006006 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00006007 else if (Scale != 1) {
6008 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6009 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00006010 }
Chris Lattnerbb171802005-10-27 05:53:56 +00006011 }
6012
Chris Lattner8f663e82005-10-29 04:36:15 +00006013 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00006014 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00006015 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6016 Amt = InsertNewInstBefore(Tmp, AI);
6017 }
6018
Chris Lattner216be912005-10-24 06:03:58 +00006019 AllocationInst *New;
6020 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00006021 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006022 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00006023 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00006024 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006025 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00006026
6027 // If the allocation has multiple uses, insert a cast and change all things
6028 // that used it to use the new cast. This will also hack on CI, but it will
6029 // die soon.
6030 if (!AI.hasOneUse()) {
6031 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006032 // New is the allocation instruction, pointer typed. AI is the original
6033 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6034 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00006035 InsertNewInstBefore(NewCast, AI);
6036 AI.replaceAllUsesWith(NewCast);
6037 }
Chris Lattner216be912005-10-24 06:03:58 +00006038 return ReplaceInstUsesWith(CI, New);
6039}
6040
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006041/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006042/// and return it as type Ty without inserting any new casts and without
6043/// changing the computed value. This is used by code that tries to decide
6044/// whether promoting or shrinking integer operations to wider or smaller types
6045/// will allow us to eliminate a truncate or extend.
6046///
6047/// This is a truncation operation if Ty is smaller than V->getType(), or an
6048/// extension operation if Ty is larger.
6049static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006050 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006051 // We can always evaluate constants in another type.
6052 if (isa<ConstantInt>(V))
6053 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006054
6055 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006056 if (!I) return false;
6057
6058 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006059
6060 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006061 case Instruction::Add:
6062 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006063 case Instruction::And:
6064 case Instruction::Or:
6065 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006066 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006067 // These operators can all arbitrarily be extended or truncated.
6068 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6069 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006070
Chris Lattner960acb02006-11-29 07:18:39 +00006071 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006072 if (!I->hasOneUse()) return false;
6073 // If we are truncating the result of this SHL, and if it's a shift of a
6074 // constant amount, we can always perform a SHL in a smaller type.
6075 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006076 uint32_t BitWidth = Ty->getBitWidth();
6077 if (BitWidth < OrigTy->getBitWidth() &&
6078 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006079 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6080 }
6081 break;
6082 case Instruction::LShr:
6083 if (!I->hasOneUse()) return false;
6084 // If this is a truncate of a logical shr, we can truncate it to a smaller
6085 // lshr iff we know that the bits we would otherwise be shifting in are
6086 // already zeros.
6087 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006088 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6089 uint32_t BitWidth = Ty->getBitWidth();
6090 if (BitWidth < OrigBitWidth &&
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006091 MaskedValueIsZero(I->getOperand(0),
Zhou Shengfd28a332007-03-30 17:20:39 +00006092 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6093 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006094 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6095 }
6096 }
Chris Lattner960acb02006-11-29 07:18:39 +00006097 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006098 case Instruction::Trunc:
6099 case Instruction::ZExt:
6100 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006101 // If this is a cast from the destination type, we can trivially eliminate
6102 // it, and this will remove a cast overall.
6103 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00006104 // If the first operand is itself a cast, and is eliminable, do not count
6105 // this as an eliminable cast. We would prefer to eliminate those two
6106 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00006107 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00006108 return true;
6109
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006110 ++NumCastsRemoved;
6111 return true;
6112 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006113 break;
6114 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006115 // TODO: Can handle more cases here.
6116 break;
6117 }
6118
6119 return false;
6120}
6121
6122/// EvaluateInDifferentType - Given an expression that
6123/// CanEvaluateInDifferentType returns true for, actually insert the code to
6124/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00006125Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006126 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006127 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00006128 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006129
6130 // Otherwise, it must be an instruction.
6131 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00006132 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006133 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006134 case Instruction::Add:
6135 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006136 case Instruction::And:
6137 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006138 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006139 case Instruction::AShr:
6140 case Instruction::LShr:
6141 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006142 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006143 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6144 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6145 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006146 break;
6147 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006148 case Instruction::Trunc:
6149 case Instruction::ZExt:
6150 case Instruction::SExt:
6151 case Instruction::BitCast:
6152 // If the source type of the cast is the type we're trying for then we can
6153 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006154 if (I->getOperand(0)->getType() == Ty)
6155 return I->getOperand(0);
6156
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006157 // Some other kind of cast, which shouldn't happen, so just ..
6158 // FALL THROUGH
6159 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006160 // TODO: Can handle more cases here.
6161 assert(0 && "Unreachable!");
6162 break;
6163 }
6164
6165 return InsertNewInstBefore(Res, *I);
6166}
6167
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006168/// @brief Implement the transforms common to all CastInst visitors.
6169Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006170 Value *Src = CI.getOperand(0);
6171
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006172 // Casting undef to anything results in undef so might as just replace it and
6173 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006174 if (isa<UndefValue>(Src)) // cast undef -> undef
6175 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6176
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006177 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6178 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006179 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006180 if (Instruction::CastOps opc =
6181 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6182 // The first cast (CSrc) is eliminable so we need to fix up or replace
6183 // the second cast (CI). CSrc will then have a good chance of being dead.
6184 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006185 }
6186 }
Chris Lattner03841652004-05-25 04:29:21 +00006187
Chris Lattnerd0d51602003-06-21 23:12:02 +00006188 // If casting the result of a getelementptr instruction with no offset, turn
6189 // this into a cast of the original pointer!
6190 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006191 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006192 bool AllZeroOperands = true;
6193 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6194 if (!isa<Constant>(GEP->getOperand(i)) ||
6195 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6196 AllZeroOperands = false;
6197 break;
6198 }
6199 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006200 // Changing the cast operand is usually not a good idea but it is safe
6201 // here because the pointer operand is being replaced with another
6202 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006203 CI.setOperand(0, GEP->getOperand(0));
6204 return &CI;
6205 }
6206 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006207
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006208 // If we are casting a malloc or alloca to a pointer to a type of the same
6209 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006210 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006211 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6212 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006213
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006214 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006215 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6216 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6217 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006218
6219 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006220 if (isa<PHINode>(Src))
6221 if (Instruction *NV = FoldOpIntoPhi(CI))
6222 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006223
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006224 return 0;
6225}
6226
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006227/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6228/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006229/// cases.
6230/// @brief Implement the transforms common to CastInst with integer operands
6231Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6232 if (Instruction *Result = commonCastTransforms(CI))
6233 return Result;
6234
6235 Value *Src = CI.getOperand(0);
6236 const Type *SrcTy = Src->getType();
6237 const Type *DestTy = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006238 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6239 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006240
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006241 // See if we can simplify any instructions used by the LHS whose sole
6242 // purpose is to compute bits we don't care about.
Reid Spencer4154e732007-03-22 20:56:53 +00006243 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6244 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006245 KnownZero, KnownOne))
6246 return &CI;
6247
6248 // If the source isn't an instruction or has more than one use then we
6249 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006250 Instruction *SrcI = dyn_cast<Instruction>(Src);
6251 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006252 return 0;
6253
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006254 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006255 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006256 if (!isa<BitCastInst>(CI) &&
6257 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6258 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006259 // If this cast is a truncate, evaluting in a different type always
6260 // eliminates the cast, so it is always a win. If this is a noop-cast
6261 // this just removes a noop cast which isn't pointful, but simplifies
6262 // the code. If this is a zero-extension, we need to do an AND to
6263 // maintain the clear top-part of the computation, so we require that
6264 // the input have eliminated at least one cast. If this is a sign
6265 // extension, we insert two new casts (to do the extension) so we
6266 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006267 bool DoXForm;
6268 switch (CI.getOpcode()) {
6269 default:
6270 // All the others use floating point so we shouldn't actually
6271 // get here because of the check above.
6272 assert(0 && "Unknown cast type");
6273 case Instruction::Trunc:
6274 DoXForm = true;
6275 break;
6276 case Instruction::ZExt:
6277 DoXForm = NumCastsRemoved >= 1;
6278 break;
6279 case Instruction::SExt:
6280 DoXForm = NumCastsRemoved >= 2;
6281 break;
6282 case Instruction::BitCast:
6283 DoXForm = false;
6284 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006285 }
6286
6287 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006288 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6289 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006290 assert(Res->getType() == DestTy);
6291 switch (CI.getOpcode()) {
6292 default: assert(0 && "Unknown cast type!");
6293 case Instruction::Trunc:
6294 case Instruction::BitCast:
6295 // Just replace this cast with the result.
6296 return ReplaceInstUsesWith(CI, Res);
6297 case Instruction::ZExt: {
6298 // We need to emit an AND to clear the high bits.
6299 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattner9d5aace2007-04-02 05:48:58 +00006300 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6301 SrcBitSize));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006302 return BinaryOperator::createAnd(Res, C);
6303 }
6304 case Instruction::SExt:
6305 // We need to emit a cast to truncate, then a cast to sext.
6306 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006307 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6308 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006309 }
6310 }
6311 }
6312
6313 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6314 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6315
6316 switch (SrcI->getOpcode()) {
6317 case Instruction::Add:
6318 case Instruction::Mul:
6319 case Instruction::And:
6320 case Instruction::Or:
6321 case Instruction::Xor:
Chris Lattnera74deaf2007-04-03 17:43:25 +00006322 // If we are discarding information, rewrite.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006323 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6324 // Don't insert two casts if they cannot be eliminated. We allow
6325 // two casts to be inserted if the sizes are the same. This could
6326 // only be converting signedness, which is a noop.
6327 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006328 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6329 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006330 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006331 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6332 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6333 return BinaryOperator::create(
6334 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006335 }
6336 }
6337
6338 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6339 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6340 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006341 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006342 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006343 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006344 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6345 }
6346 break;
6347 case Instruction::SDiv:
6348 case Instruction::UDiv:
6349 case Instruction::SRem:
6350 case Instruction::URem:
6351 // If we are just changing the sign, rewrite.
6352 if (DestBitSize == SrcBitSize) {
6353 // Don't insert two casts if they cannot be eliminated. We allow
6354 // two casts to be inserted if the sizes are the same. This could
6355 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006356 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6357 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006358 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6359 Op0, DestTy, SrcI);
6360 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6361 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006362 return BinaryOperator::create(
6363 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6364 }
6365 }
6366 break;
6367
6368 case Instruction::Shl:
6369 // Allow changing the sign of the source operand. Do not allow
6370 // changing the size of the shift, UNLESS the shift amount is a
6371 // constant. We must not change variable sized shifts to a smaller
6372 // size, because it is undefined to shift more bits out than exist
6373 // in the value.
6374 if (DestBitSize == SrcBitSize ||
6375 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006376 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6377 Instruction::BitCast : Instruction::Trunc);
6378 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006379 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006380 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 }
6382 break;
6383 case Instruction::AShr:
6384 // If this is a signed shr, and if all bits shifted in are about to be
6385 // truncated off, turn it into an unsigned shr to allow greater
6386 // simplifications.
6387 if (DestBitSize < SrcBitSize &&
6388 isa<ConstantInt>(Op1)) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006389 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006390 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6391 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006392 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006393 }
6394 }
6395 break;
6396
Reid Spencer266e42b2006-12-23 06:05:41 +00006397 case Instruction::ICmp:
6398 // If we are just checking for a icmp eq of a single bit and casting it
6399 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006400 // cast to integer to avoid the comparison.
6401 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng150f3bb2007-04-01 17:13:37 +00006402 const APInt& Op1CV = Op1C->getValue();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006403 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6404 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6405 // cast (X == 1) to int --> X iff X has only the low bit set.
6406 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6407 // cast (X != 0) to int --> X iff X has only the low bit set.
6408 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6409 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6410 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
Reid Spencer4154e732007-03-22 20:56:53 +00006411 if (Op1CV == 0 || Op1CV.isPowerOf2()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412 // If Op1C some other power of two, convert:
Reid Spencer4154e732007-03-22 20:56:53 +00006413 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6414 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6415 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006417
6418 // This only works for EQ and NE
6419 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6420 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6421 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006422
Zhou Sheng0900993e2007-03-23 03:13:21 +00006423 APInt KnownZeroMask(KnownZero ^ TypeMask);
6424 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006425 bool isNE = pred == ICmpInst::ICMP_NE;
Zhou Sheng0900993e2007-03-23 03:13:21 +00006426 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006427 // (X&4) == 2 --> false
6428 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006429 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006430 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006431 return ReplaceInstUsesWith(CI, Res);
6432 }
6433
Zhou Sheng56cda952007-04-02 08:20:41 +00006434 uint32_t ShiftAmt = KnownZeroMask.logBase2();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006435 Value *In = Op0;
6436 if (ShiftAmt) {
6437 // Perform a logical shr by shiftamt.
6438 // Insert the shift to put the result in the low bit.
6439 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006440 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006441 ConstantInt::get(In->getType(), ShiftAmt),
6442 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443 }
6444
Reid Spencer266e42b2006-12-23 06:05:41 +00006445 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006446 Constant *One = ConstantInt::get(In->getType(), 1);
6447 In = BinaryOperator::createXor(In, One, "tmp");
6448 InsertNewInstBefore(cast<Instruction>(In), CI);
6449 }
6450
6451 if (CI.getType() == In->getType())
6452 return ReplaceInstUsesWith(CI, In);
6453 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006454 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006455 }
6456 }
6457 }
6458 break;
6459 }
6460 return 0;
6461}
6462
6463Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006464 if (Instruction *Result = commonIntCastTransforms(CI))
6465 return Result;
6466
6467 Value *Src = CI.getOperand(0);
6468 const Type *Ty = CI.getType();
Zhou Sheng56cda952007-04-02 08:20:41 +00006469 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6470 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattnerd747f012006-11-29 07:04:07 +00006471
6472 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6473 switch (SrcI->getOpcode()) {
6474 default: break;
6475 case Instruction::LShr:
6476 // We can shrink lshr to something smaller if we know the bits shifted in
6477 // are already zeros.
6478 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Shengfd28a332007-03-30 17:20:39 +00006479 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattnerd747f012006-11-29 07:04:07 +00006480
6481 // Get a mask for the bits shifting in.
Zhou Sheng2777a312007-03-28 09:19:01 +00006482 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer13bc5d72006-12-12 09:18:51 +00006483 Value* SrcIOp0 = SrcI->getOperand(0);
6484 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006485 if (ShAmt >= DestBitWidth) // All zeros.
6486 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6487
6488 // Okay, we can shrink this. Truncate the input, then return a new
6489 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006490 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6491 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6492 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006493 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006494 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006495 } else { // This is a variable shr.
6496
6497 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6498 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6499 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006500 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006501 Value *One = ConstantInt::get(SrcI->getType(), 1);
6502
Reid Spencer2341c222007-02-02 02:16:23 +00006503 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006504 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006505 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006506 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6507 SrcI->getOperand(0),
6508 "tmp"), CI);
6509 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006510 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006511 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006512 }
6513 break;
6514 }
6515 }
6516
6517 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006518}
6519
6520Instruction *InstCombiner::visitZExt(CastInst &CI) {
6521 // If one of the common conversion will work ..
6522 if (Instruction *Result = commonIntCastTransforms(CI))
6523 return Result;
6524
6525 Value *Src = CI.getOperand(0);
6526
6527 // If this is a cast of a cast
6528 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006529 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6530 // types and if the sizes are just right we can convert this into a logical
6531 // 'and' which will be much cheaper than the pair of casts.
6532 if (isa<TruncInst>(CSrc)) {
6533 // Get the sizes of the types involved
6534 Value *A = CSrc->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00006535 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6536 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6537 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006538 // If we're actually extending zero bits and the trunc is a no-op
6539 if (MidSize < DstSize && SrcSize == DstSize) {
6540 // Replace both of the casts with an And of the type mask.
Zhou Sheng2777a312007-03-28 09:19:01 +00006541 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencer4154e732007-03-22 20:56:53 +00006542 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006543 Instruction *And =
6544 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6545 // Unfortunately, if the type changed, we need to cast it back.
6546 if (And->getType() != CI.getType()) {
6547 And->setName(CSrc->getName()+".mask");
6548 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006549 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006550 }
6551 return And;
6552 }
6553 }
6554 }
6555
6556 return 0;
6557}
6558
6559Instruction *InstCombiner::visitSExt(CastInst &CI) {
6560 return commonIntCastTransforms(CI);
6561}
6562
6563Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6564 return commonCastTransforms(CI);
6565}
6566
6567Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6568 return commonCastTransforms(CI);
6569}
6570
6571Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006572 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006573}
6574
6575Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006576 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006577}
6578
6579Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6580 return commonCastTransforms(CI);
6581}
6582
6583Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6584 return commonCastTransforms(CI);
6585}
6586
6587Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006588 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006589}
6590
6591Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6592 return commonCastTransforms(CI);
6593}
6594
6595Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6596
6597 // If the operands are integer typed then apply the integer transforms,
6598 // otherwise just apply the common ones.
6599 Value *Src = CI.getOperand(0);
6600 const Type *SrcTy = Src->getType();
6601 const Type *DestTy = CI.getType();
6602
Chris Lattner03c49532007-01-15 02:27:26 +00006603 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006604 if (Instruction *Result = commonIntCastTransforms(CI))
6605 return Result;
6606 } else {
6607 if (Instruction *Result = commonCastTransforms(CI))
6608 return Result;
6609 }
6610
6611
6612 // Get rid of casts from one type to the same type. These are useless and can
6613 // be replaced by the operand.
6614 if (DestTy == Src->getType())
6615 return ReplaceInstUsesWith(CI, Src);
6616
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006617 // If the source and destination are pointers, and this cast is equivalent to
6618 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6619 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006620 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6621 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6622 const Type *DstElTy = DstPTy->getElementType();
6623 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006624
Reid Spencerc635f472006-12-31 05:48:39 +00006625 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006626 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006627 while (SrcElTy != DstElTy &&
6628 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6629 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6630 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006631 ++NumZeros;
6632 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006633
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006634 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006635 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006636 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6637 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006638 }
6639 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006640 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006641
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006642 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6643 if (SVI->hasOneUse()) {
6644 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6645 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006646 if (isa<VectorType>(DestTy) &&
6647 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006648 SVI->getType()->getNumElements()) {
6649 CastInst *Tmp;
6650 // If either of the operands is a cast from CI.getType(), then
6651 // evaluating the shuffle in the casted destination's type will allow
6652 // us to eliminate at least one cast.
6653 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6654 Tmp->getOperand(0)->getType() == DestTy) ||
6655 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6656 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006657 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6658 SVI->getOperand(0), DestTy, &CI);
6659 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6660 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006661 // Return a new shuffle vector. Use the same element ID's, as we
6662 // know the vector types match #elts.
6663 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006664 }
6665 }
6666 }
6667 }
Chris Lattner260ab202002-04-18 17:39:14 +00006668 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006669}
6670
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006671/// GetSelectFoldableOperands - We want to turn code that looks like this:
6672/// %C = or %A, %B
6673/// %D = select %cond, %C, %A
6674/// into:
6675/// %C = select %cond, %B, 0
6676/// %D = or %A, %C
6677///
6678/// Assuming that the specified instruction is an operand to the select, return
6679/// a bitmask indicating which operands of this instruction are foldable if they
6680/// equal the other incoming value of the select.
6681///
6682static unsigned GetSelectFoldableOperands(Instruction *I) {
6683 switch (I->getOpcode()) {
6684 case Instruction::Add:
6685 case Instruction::Mul:
6686 case Instruction::And:
6687 case Instruction::Or:
6688 case Instruction::Xor:
6689 return 3; // Can fold through either operand.
6690 case Instruction::Sub: // Can only fold on the amount subtracted.
6691 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006692 case Instruction::LShr:
6693 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006694 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006695 default:
6696 return 0; // Cannot fold
6697 }
6698}
6699
6700/// GetSelectFoldableConstant - For the same transformation as the previous
6701/// function, return the identity constant that goes into the select.
6702static Constant *GetSelectFoldableConstant(Instruction *I) {
6703 switch (I->getOpcode()) {
6704 default: assert(0 && "This cannot happen!"); abort();
6705 case Instruction::Add:
6706 case Instruction::Sub:
6707 case Instruction::Or:
6708 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006709 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006710 case Instruction::LShr:
6711 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006712 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006713 case Instruction::And:
6714 return ConstantInt::getAllOnesValue(I->getType());
6715 case Instruction::Mul:
6716 return ConstantInt::get(I->getType(), 1);
6717 }
6718}
6719
Chris Lattner411336f2005-01-19 21:50:18 +00006720/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6721/// have the same opcode and only one use each. Try to simplify this.
6722Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6723 Instruction *FI) {
6724 if (TI->getNumOperands() == 1) {
6725 // If this is a non-volatile load or a cast from the same type,
6726 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006727 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006728 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6729 return 0;
6730 } else {
6731 return 0; // unknown unary op.
6732 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006733
Chris Lattner411336f2005-01-19 21:50:18 +00006734 // Fold this by inserting a select from the input values.
6735 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6736 FI->getOperand(0), SI.getName()+".v");
6737 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006738 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6739 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006740 }
6741
Reid Spencer2341c222007-02-02 02:16:23 +00006742 // Only handle binary operators here.
6743 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006744 return 0;
6745
6746 // Figure out if the operations have any operands in common.
6747 Value *MatchOp, *OtherOpT, *OtherOpF;
6748 bool MatchIsOpZero;
6749 if (TI->getOperand(0) == FI->getOperand(0)) {
6750 MatchOp = TI->getOperand(0);
6751 OtherOpT = TI->getOperand(1);
6752 OtherOpF = FI->getOperand(1);
6753 MatchIsOpZero = true;
6754 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6755 MatchOp = TI->getOperand(1);
6756 OtherOpT = TI->getOperand(0);
6757 OtherOpF = FI->getOperand(0);
6758 MatchIsOpZero = false;
6759 } else if (!TI->isCommutative()) {
6760 return 0;
6761 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6762 MatchOp = TI->getOperand(0);
6763 OtherOpT = TI->getOperand(1);
6764 OtherOpF = FI->getOperand(0);
6765 MatchIsOpZero = true;
6766 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6767 MatchOp = TI->getOperand(1);
6768 OtherOpT = TI->getOperand(0);
6769 OtherOpF = FI->getOperand(1);
6770 MatchIsOpZero = true;
6771 } else {
6772 return 0;
6773 }
6774
6775 // If we reach here, they do have operations in common.
6776 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6777 OtherOpF, SI.getName()+".v");
6778 InsertNewInstBefore(NewSI, SI);
6779
6780 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6781 if (MatchIsOpZero)
6782 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6783 else
6784 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006785 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006786 assert(0 && "Shouldn't get here");
6787 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006788}
6789
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006790Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006791 Value *CondVal = SI.getCondition();
6792 Value *TrueVal = SI.getTrueValue();
6793 Value *FalseVal = SI.getFalseValue();
6794
6795 // select true, X, Y -> X
6796 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006797 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006798 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006799
6800 // select C, X, X -> X
6801 if (TrueVal == FalseVal)
6802 return ReplaceInstUsesWith(SI, TrueVal);
6803
Chris Lattner81a7a232004-10-16 18:11:37 +00006804 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6805 return ReplaceInstUsesWith(SI, FalseVal);
6806 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6807 return ReplaceInstUsesWith(SI, TrueVal);
6808 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6809 if (isa<Constant>(TrueVal))
6810 return ReplaceInstUsesWith(SI, TrueVal);
6811 else
6812 return ReplaceInstUsesWith(SI, FalseVal);
6813 }
6814
Reid Spencer542964f2007-01-11 18:21:29 +00006815 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006816 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006817 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006818 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006819 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006820 } else {
6821 // Change: A = select B, false, C --> A = and !B, C
6822 Value *NotCond =
6823 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6824 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006825 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006826 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006827 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006828 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006829 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006830 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006831 } else {
6832 // Change: A = select B, C, true --> A = or !B, C
6833 Value *NotCond =
6834 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6835 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006836 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006837 }
6838 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006839 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006840
Chris Lattner183b3362004-04-09 19:05:30 +00006841 // Selecting between two integer constants?
6842 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6843 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6844 // select C, 1, 0 -> cast C to int
Reid Spencer959a21d2007-03-23 21:24:59 +00006845 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006846 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer959a21d2007-03-23 21:24:59 +00006847 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006848 // select C, 0, 1 -> cast !C to int
6849 Value *NotCond =
6850 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006851 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006852 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006853 }
Chris Lattner35167c32004-06-09 07:59:58 +00006854
Reid Spencer266e42b2006-12-23 06:05:41 +00006855 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006856
Reid Spencer266e42b2006-12-23 06:05:41 +00006857 // (x <s 0) ? -1 : 0 -> ashr x, 31
6858 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Reid Spencer959a21d2007-03-23 21:24:59 +00006859 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattner380c7e92006-09-20 04:44:59 +00006860 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6861 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006862 if (IC->isSignedPredicate())
Reid Spencer959a21d2007-03-23 21:24:59 +00006863 CanXForm = CmpCst->isZero() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006864 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006865 else {
Zhou Sheng56cda952007-04-02 08:20:41 +00006866 uint32_t Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencer959a21d2007-03-23 21:24:59 +00006867 CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006868 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006869 }
6870
6871 if (CanXForm) {
6872 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006873 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006874 Value *X = IC->getOperand(0);
Zhou Sheng56cda952007-04-02 08:20:41 +00006875 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006876 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6877 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6878 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006879 InsertNewInstBefore(SRA, SI);
6880
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006881 // Finally, convert to the type of the select RHS. We figure out
6882 // if this requires a SExt, Trunc or BitCast based on the sizes.
6883 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng56cda952007-04-02 08:20:41 +00006884 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
6885 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006886 if (SRASize < SISize)
6887 opc = Instruction::SExt;
6888 else if (SRASize > SISize)
6889 opc = Instruction::Trunc;
6890 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006891 }
6892 }
6893
6894
6895 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006896 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006897 // non-constant value, eliminate this whole mess. This corresponds to
6898 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer959a21d2007-03-23 21:24:59 +00006899 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006900 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006901 cast<Constant>(IC->getOperand(1))->isNullValue())
6902 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6903 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006904 isa<ConstantInt>(ICA->getOperand(1)) &&
6905 (ICA->getOperand(1) == TrueValC ||
6906 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006907 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6908 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006909 // know whether we have a icmp_ne or icmp_eq and whether the
6910 // true or false val is the zero.
Reid Spencer959a21d2007-03-23 21:24:59 +00006911 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencer266e42b2006-12-23 06:05:41 +00006912 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006913 Value *V = ICA;
6914 if (ShouldNotVal)
6915 V = InsertNewInstBefore(BinaryOperator::create(
6916 Instruction::Xor, V, ICA->getOperand(1)), SI);
6917 return ReplaceInstUsesWith(SI, V);
6918 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006919 }
Chris Lattner533bc492004-03-30 19:37:13 +00006920 }
Chris Lattner623fba12004-04-10 22:21:27 +00006921
6922 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006923 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6924 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006925 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006926 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006927 return ReplaceInstUsesWith(SI, FalseVal);
6928 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006929 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006930 return ReplaceInstUsesWith(SI, TrueVal);
6931 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6932
Reid Spencer266e42b2006-12-23 06:05:41 +00006933 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006934 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006935 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006936 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006937 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006938 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6939 return ReplaceInstUsesWith(SI, TrueVal);
6940 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6941 }
6942 }
6943
6944 // See if we are selecting two values based on a comparison of the two values.
6945 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6946 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6947 // Transform (X == Y) ? X : Y -> Y
6948 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6949 return ReplaceInstUsesWith(SI, FalseVal);
6950 // Transform (X != Y) ? X : Y -> X
6951 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6952 return ReplaceInstUsesWith(SI, TrueVal);
6953 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6954
6955 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6956 // Transform (X == Y) ? Y : X -> X
6957 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6958 return ReplaceInstUsesWith(SI, FalseVal);
6959 // Transform (X != Y) ? Y : X -> Y
6960 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006961 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006962 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6963 }
6964 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006965
Chris Lattnera04c9042005-01-13 22:52:24 +00006966 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6967 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6968 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006969 Instruction *AddOp = 0, *SubOp = 0;
6970
Chris Lattner411336f2005-01-19 21:50:18 +00006971 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6972 if (TI->getOpcode() == FI->getOpcode())
6973 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6974 return IV;
6975
6976 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6977 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006978 if (TI->getOpcode() == Instruction::Sub &&
6979 FI->getOpcode() == Instruction::Add) {
6980 AddOp = FI; SubOp = TI;
6981 } else if (FI->getOpcode() == Instruction::Sub &&
6982 TI->getOpcode() == Instruction::Add) {
6983 AddOp = TI; SubOp = FI;
6984 }
6985
6986 if (AddOp) {
6987 Value *OtherAddOp = 0;
6988 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6989 OtherAddOp = AddOp->getOperand(1);
6990 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6991 OtherAddOp = AddOp->getOperand(0);
6992 }
6993
6994 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006995 // So at this point we know we have (Y -> OtherAddOp):
6996 // select C, (add X, Y), (sub X, Z)
6997 Value *NegVal; // Compute -Z
6998 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6999 NegVal = ConstantExpr::getNeg(C);
7000 } else {
7001 NegVal = InsertNewInstBefore(
7002 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00007003 }
Chris Lattnerb580d262006-02-24 18:05:58 +00007004
7005 Value *NewTrueOp = OtherAddOp;
7006 Value *NewFalseOp = NegVal;
7007 if (AddOp != TI)
7008 std::swap(NewTrueOp, NewFalseOp);
7009 Instruction *NewSel =
7010 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7011
7012 NewSel = InsertNewInstBefore(NewSel, SI);
7013 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00007014 }
7015 }
7016 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007017
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007018 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00007019 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007020 // See the comment above GetSelectFoldableOperands for a description of the
7021 // transformation we are doing here.
7022 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7023 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7024 !isa<Constant>(FalseVal))
7025 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7026 unsigned OpToFold = 0;
7027 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7028 OpToFold = 1;
7029 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7030 OpToFold = 2;
7031 }
7032
7033 if (OpToFold) {
7034 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007035 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007036 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007037 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007038 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7040 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007041 else {
7042 assert(0 && "Unknown instruction!!");
7043 }
7044 }
7045 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00007046
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007047 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7048 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7049 !isa<Constant>(TrueVal))
7050 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7051 unsigned OpToFold = 0;
7052 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7053 OpToFold = 1;
7054 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7055 OpToFold = 2;
7056 }
7057
7058 if (OpToFold) {
7059 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007060 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00007061 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007062 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00007063 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7065 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00007066 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007067 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00007068 }
7069 }
7070 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00007071
7072 if (BinaryOperator::isNot(CondVal)) {
7073 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7074 SI.setOperand(1, FalseVal);
7075 SI.setOperand(2, TrueVal);
7076 return &SI;
7077 }
7078
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007079 return 0;
7080}
7081
Chris Lattner82f2ef22006-03-06 20:18:44 +00007082/// GetKnownAlignment - If the specified pointer has an alignment that we can
7083/// determine, return it, otherwise return 0.
7084static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7086 unsigned Align = GV->getAlignment();
7087 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00007088 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007089 return Align;
7090 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7091 unsigned Align = AI->getAlignment();
7092 if (Align == 0 && TD) {
7093 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00007094 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00007095 else if (isa<MallocInst>(AI)) {
7096 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00007097 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00007098 Align =
7099 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007100 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00007101 Align =
7102 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00007103 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007104 }
7105 }
7106 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007107 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00007108 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007109 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00007110 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007111 if (isa<PointerType>(CI->getOperand(0)->getType()))
7112 return GetKnownAlignment(CI->getOperand(0), TD);
7113 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00007114 } else if (isa<GetElementPtrInst>(V) ||
7115 (isa<ConstantExpr>(V) &&
7116 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7117 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00007118 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7119 if (BaseAlignment == 0) return 0;
7120
7121 // If all indexes are zero, it is just the alignment of the base pointer.
7122 bool AllZeroOperands = true;
7123 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7124 if (!isa<Constant>(GEPI->getOperand(i)) ||
7125 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7126 AllZeroOperands = false;
7127 break;
7128 }
7129 if (AllZeroOperands)
7130 return BaseAlignment;
7131
7132 // Otherwise, if the base alignment is >= the alignment we expect for the
7133 // base pointer type, then we know that the resultant pointer is aligned at
7134 // least as much as its type requires.
7135 if (!TD) return 0;
7136
7137 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007138 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007139 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007140 <= BaseAlignment) {
7141 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007142 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007143 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007144 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007145 return 0;
7146 }
7147 return 0;
7148}
7149
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007150
Chris Lattnerc66b2232006-01-13 20:11:04 +00007151/// visitCallInst - CallInst simplification. This mostly only handles folding
7152/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7153/// the heavy lifting.
7154///
Chris Lattner970c33a2003-06-19 17:00:31 +00007155Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007156 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7157 if (!II) return visitCallSite(&CI);
7158
Chris Lattner51ea1272004-02-28 05:22:00 +00007159 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7160 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007161 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007162 bool Changed = false;
7163
7164 // memmove/cpy/set of zero bytes is a noop.
7165 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7166 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7167
Chris Lattner00648e12004-10-12 04:52:52 +00007168 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007169 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007170 // Replace the instruction with just byte operations. We would
7171 // transform other cases to loads/stores, but we don't know if
7172 // alignment is sufficient.
7173 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007174 }
7175
Chris Lattner00648e12004-10-12 04:52:52 +00007176 // If we have a memmove and the source operation is a constant global,
7177 // then the source and dest pointers can't alias, so we can change this
7178 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007179 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007180 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7181 if (GVSrc->isConstant()) {
7182 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007183 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007184 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007185 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007186 Name = "llvm.memcpy.i32";
7187 else
7188 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007189 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007190 CI.getCalledFunction()->getFunctionType());
7191 CI.setOperand(0, MemCpy);
7192 Changed = true;
7193 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007194 }
Chris Lattner00648e12004-10-12 04:52:52 +00007195
Chris Lattner82f2ef22006-03-06 20:18:44 +00007196 // If we can determine a pointer alignment that is bigger than currently
7197 // set, update the alignment.
7198 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7199 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7200 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7201 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007202 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007203 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007204 Changed = true;
7205 }
7206 } else if (isa<MemSetInst>(MI)) {
7207 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007208 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007209 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007210 Changed = true;
7211 }
7212 }
7213
Chris Lattnerc66b2232006-01-13 20:11:04 +00007214 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007215 } else {
7216 switch (II->getIntrinsicID()) {
7217 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007218 case Intrinsic::ppc_altivec_lvx:
7219 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007220 case Intrinsic::x86_sse_loadu_ps:
7221 case Intrinsic::x86_sse2_loadu_pd:
7222 case Intrinsic::x86_sse2_loadu_dq:
7223 // Turn PPC lvx -> load if the pointer is known aligned.
7224 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007225 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007226 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007227 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007228 return new LoadInst(Ptr);
7229 }
7230 break;
7231 case Intrinsic::ppc_altivec_stvx:
7232 case Intrinsic::ppc_altivec_stvxl:
7233 // Turn stvx -> store if the pointer is known aligned.
7234 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007235 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007236 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7237 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007238 return new StoreInst(II->getOperand(1), Ptr);
7239 }
7240 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007241 case Intrinsic::x86_sse_storeu_ps:
7242 case Intrinsic::x86_sse2_storeu_pd:
7243 case Intrinsic::x86_sse2_storeu_dq:
7244 case Intrinsic::x86_sse2_storel_dq:
7245 // Turn X86 storeu -> store if the pointer is known aligned.
7246 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7247 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007248 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7249 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007250 return new StoreInst(II->getOperand(2), Ptr);
7251 }
7252 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007253
7254 case Intrinsic::x86_sse_cvttss2si: {
7255 // These intrinsics only demands the 0th element of its input vector. If
7256 // we can simplify the input based on that, do so now.
7257 uint64_t UndefElts;
7258 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7259 UndefElts)) {
7260 II->setOperand(1, V);
7261 return II;
7262 }
7263 break;
7264 }
7265
Chris Lattnere79d2492006-04-06 19:19:17 +00007266 case Intrinsic::ppc_altivec_vperm:
7267 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007268 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007269 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7270
7271 // Check that all of the elements are integer constants or undefs.
7272 bool AllEltsOk = true;
7273 for (unsigned i = 0; i != 16; ++i) {
7274 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7275 !isa<UndefValue>(Mask->getOperand(i))) {
7276 AllEltsOk = false;
7277 break;
7278 }
7279 }
7280
7281 if (AllEltsOk) {
7282 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007283 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7284 II->getOperand(1), Mask->getType(), CI);
7285 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7286 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007287 Value *Result = UndefValue::get(Op0->getType());
7288
7289 // Only extract each element once.
7290 Value *ExtractedElts[32];
7291 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7292
7293 for (unsigned i = 0; i != 16; ++i) {
7294 if (isa<UndefValue>(Mask->getOperand(i)))
7295 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007296 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007297 Idx &= 31; // Match the hardware behavior.
7298
7299 if (ExtractedElts[Idx] == 0) {
7300 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007301 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007302 InsertNewInstBefore(Elt, CI);
7303 ExtractedElts[Idx] = Elt;
7304 }
7305
7306 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007307 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007308 InsertNewInstBefore(cast<Instruction>(Result), CI);
7309 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007310 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007311 }
7312 }
7313 break;
7314
Chris Lattner503221f2006-01-13 21:28:09 +00007315 case Intrinsic::stackrestore: {
7316 // If the save is right next to the restore, remove the restore. This can
7317 // happen when variable allocas are DCE'd.
7318 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7319 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7320 BasicBlock::iterator BI = SS;
7321 if (&*++BI == II)
7322 return EraseInstFromFunction(CI);
7323 }
7324 }
7325
7326 // If the stack restore is in a return/unwind block and if there are no
7327 // allocas or calls between the restore and the return, nuke the restore.
7328 TerminatorInst *TI = II->getParent()->getTerminator();
7329 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7330 BasicBlock::iterator BI = II;
7331 bool CannotRemove = false;
7332 for (++BI; &*BI != TI; ++BI) {
7333 if (isa<AllocaInst>(BI) ||
7334 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7335 CannotRemove = true;
7336 break;
7337 }
7338 }
7339 if (!CannotRemove)
7340 return EraseInstFromFunction(CI);
7341 }
7342 break;
7343 }
7344 }
Chris Lattner00648e12004-10-12 04:52:52 +00007345 }
7346
Chris Lattnerc66b2232006-01-13 20:11:04 +00007347 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007348}
7349
7350// InvokeInst simplification
7351//
7352Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007353 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007354}
7355
Chris Lattneraec3d942003-10-07 22:32:43 +00007356// visitCallSite - Improvements for call and invoke instructions.
7357//
7358Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007359 bool Changed = false;
7360
7361 // If the callee is a constexpr cast of a function, attempt to move the cast
7362 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007363 if (transformConstExprCastCall(CS)) return 0;
7364
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007365 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007366
Chris Lattner61d9d812005-05-13 07:09:09 +00007367 if (Function *CalleeF = dyn_cast<Function>(Callee))
7368 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7369 Instruction *OldCall = CS.getInstruction();
7370 // If the call and callee calling conventions don't match, this call must
7371 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007372 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007373 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007374 if (!OldCall->use_empty())
7375 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7376 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7377 return EraseInstFromFunction(*OldCall);
7378 return 0;
7379 }
7380
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007381 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7382 // This instruction is not reachable, just remove it. We insert a store to
7383 // undef so that we know that this code is not reachable, despite the fact
7384 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007385 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007386 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007387 CS.getInstruction());
7388
7389 if (!CS.getInstruction()->use_empty())
7390 CS.getInstruction()->
7391 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7392
7393 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7394 // Don't break the CFG, insert a dummy cond branch.
7395 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007396 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007397 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007398 return EraseInstFromFunction(*CS.getInstruction());
7399 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007400
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007401 const PointerType *PTy = cast<PointerType>(Callee->getType());
7402 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7403 if (FTy->isVarArg()) {
7404 // See if we can optimize any arguments passed through the varargs area of
7405 // the call.
7406 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7407 E = CS.arg_end(); I != E; ++I)
7408 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7409 // If this cast does not effect the value passed through the varargs
7410 // area, we can eliminate the use of the cast.
7411 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007412 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007413 *I = Op;
7414 Changed = true;
7415 }
7416 }
7417 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007418
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007419 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007420}
7421
Chris Lattner970c33a2003-06-19 17:00:31 +00007422// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7423// attempt to move the cast to the arguments of the call/invoke.
7424//
7425bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7426 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7427 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007428 if (CE->getOpcode() != Instruction::BitCast ||
7429 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007430 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007431 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007432 Instruction *Caller = CS.getInstruction();
7433
7434 // Okay, this is a cast from a function to a different type. Unless doing so
7435 // would cause a type conversion of one of our arguments, change this call to
7436 // be a direct call with arguments casted to the appropriate types.
7437 //
7438 const FunctionType *FT = Callee->getFunctionType();
7439 const Type *OldRetTy = Caller->getType();
7440
Chris Lattner1f7942f2004-01-14 06:06:08 +00007441 // Check to see if we are changing the return type...
7442 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007443 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007444 // Conversion is ok if changing from pointer to int of same size.
7445 !(isa<PointerType>(FT->getReturnType()) &&
7446 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007447 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007448
7449 // If the callsite is an invoke instruction, and the return value is used by
7450 // a PHI node in a successor, we cannot change the return type of the call
7451 // because there is no place to put the cast instruction (without breaking
7452 // the critical edge). Bail out in this case.
7453 if (!Caller->use_empty())
7454 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7455 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7456 UI != E; ++UI)
7457 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7458 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007459 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007460 return false;
7461 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007462
7463 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7464 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007465
Chris Lattner970c33a2003-06-19 17:00:31 +00007466 CallSite::arg_iterator AI = CS.arg_begin();
7467 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7468 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007469 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007470 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007471 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007472 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007473 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007474 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007475 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7476 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng222d5eb2007-03-25 05:01:29 +00007477 && c->getValue().isStrictlyPositive());
Reid Spencer5301e7c2007-01-30 20:08:39 +00007478 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007479 }
7480
7481 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007482 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007483 return false; // Do not delete arguments unless we have a function body...
7484
7485 // Okay, we decided that this is a safe thing to do: go ahead and start
7486 // inserting cast instructions as necessary...
7487 std::vector<Value*> Args;
7488 Args.reserve(NumActualArgs);
7489
7490 AI = CS.arg_begin();
7491 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7492 const Type *ParamTy = FT->getParamType(i);
7493 if ((*AI)->getType() == ParamTy) {
7494 Args.push_back(*AI);
7495 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007496 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007497 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007498 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007499 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007500 }
7501 }
7502
7503 // If the function takes more arguments than the call was taking, add them
7504 // now...
7505 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7506 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7507
7508 // If we are removing arguments to the function, emit an obnoxious warning...
7509 if (FT->getNumParams() < NumActualArgs)
7510 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007511 cerr << "WARNING: While resolving call to function '"
7512 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007513 } else {
7514 // Add all of the arguments in their promoted form to the arg list...
7515 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7516 const Type *PTy = getPromotedType((*AI)->getType());
7517 if (PTy != (*AI)->getType()) {
7518 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007519 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7520 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007521 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007522 InsertNewInstBefore(Cast, *Caller);
7523 Args.push_back(Cast);
7524 } else {
7525 Args.push_back(*AI);
7526 }
7527 }
7528 }
7529
7530 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007531 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007532
7533 Instruction *NC;
7534 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007535 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007536 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007537 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007538 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007539 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007540 if (cast<CallInst>(Caller)->isTailCall())
7541 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007542 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007543 }
7544
Chris Lattner6e0123b2007-02-11 01:23:03 +00007545 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007546 Value *NV = NC;
7547 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7548 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007549 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007550 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7551 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007552 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007553
7554 // If this is an invoke instruction, we should insert it after the first
7555 // non-phi, instruction in the normal successor block.
7556 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7557 BasicBlock::iterator I = II->getNormalDest()->begin();
7558 while (isa<PHINode>(I)) ++I;
7559 InsertNewInstBefore(NC, *I);
7560 } else {
7561 // Otherwise, it's a call, just insert cast right after the call instr
7562 InsertNewInstBefore(NC, *Caller);
7563 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007564 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007565 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007566 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007567 }
7568 }
7569
7570 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7571 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007572 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007573 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007574 return true;
7575}
7576
Chris Lattnercadac0c2006-11-01 04:51:18 +00007577/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7578/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7579/// and a single binop.
7580Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7581 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007582 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7583 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007584 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007585 Value *LHSVal = FirstInst->getOperand(0);
7586 Value *RHSVal = FirstInst->getOperand(1);
7587
7588 const Type *LHSType = LHSVal->getType();
7589 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007590
7591 // Scan to see if all operands are the same opcode, all have one use, and all
7592 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007593 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007594 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007595 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007596 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007597 // types or GEP's with different index types.
7598 I->getOperand(0)->getType() != LHSType ||
7599 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007600 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007601
7602 // If they are CmpInst instructions, check their predicates
7603 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7604 if (cast<CmpInst>(I)->getPredicate() !=
7605 cast<CmpInst>(FirstInst)->getPredicate())
7606 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007607
7608 // Keep track of which operand needs a phi node.
7609 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7610 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007611 }
7612
Chris Lattner4f218d52006-11-08 19:42:28 +00007613 // Otherwise, this is safe to transform, determine if it is profitable.
7614
7615 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7616 // Indexes are often folded into load/store instructions, so we don't want to
7617 // hide them behind a phi.
7618 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7619 return 0;
7620
Chris Lattnercadac0c2006-11-01 04:51:18 +00007621 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007622 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007623 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007624 if (LHSVal == 0) {
7625 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7626 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7627 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007628 InsertNewInstBefore(NewLHS, PN);
7629 LHSVal = NewLHS;
7630 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007631
7632 if (RHSVal == 0) {
7633 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7634 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7635 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007636 InsertNewInstBefore(NewRHS, PN);
7637 RHSVal = NewRHS;
7638 }
7639
Chris Lattnercd62f112006-11-08 19:29:23 +00007640 // Add all operands to the new PHIs.
7641 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7642 if (NewLHS) {
7643 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7644 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7645 }
7646 if (NewRHS) {
7647 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7648 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7649 }
7650 }
7651
Chris Lattnercadac0c2006-11-01 04:51:18 +00007652 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007653 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007654 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7655 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7656 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007657 else {
7658 assert(isa<GetElementPtrInst>(FirstInst));
7659 return new GetElementPtrInst(LHSVal, RHSVal);
7660 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007661}
7662
Chris Lattner14f82c72006-11-01 07:13:54 +00007663/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7664/// of the block that defines it. This means that it must be obvious the value
7665/// of the load is not changed from the point of the load to the end of the
7666/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007667///
7668/// Finally, it is safe, but not profitable, to sink a load targetting a
7669/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7670/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007671static bool isSafeToSinkLoad(LoadInst *L) {
7672 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7673
7674 for (++BBI; BBI != E; ++BBI)
7675 if (BBI->mayWriteToMemory())
7676 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007677
7678 // Check for non-address taken alloca. If not address-taken already, it isn't
7679 // profitable to do this xform.
7680 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7681 bool isAddressTaken = false;
7682 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7683 UI != E; ++UI) {
7684 if (isa<LoadInst>(UI)) continue;
7685 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7686 // If storing TO the alloca, then the address isn't taken.
7687 if (SI->getOperand(1) == AI) continue;
7688 }
7689 isAddressTaken = true;
7690 break;
7691 }
7692
7693 if (!isAddressTaken)
7694 return false;
7695 }
7696
Chris Lattner14f82c72006-11-01 07:13:54 +00007697 return true;
7698}
7699
Chris Lattner970c33a2003-06-19 17:00:31 +00007700
Chris Lattner7515cab2004-11-14 19:13:23 +00007701// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7702// operator and they all are only used by the PHI, PHI together their
7703// inputs, and do the operation once, to the result of the PHI.
7704Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7705 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7706
7707 // Scan the instruction, looking for input operations that can be folded away.
7708 // If all input operands to the phi are the same instruction (e.g. a cast from
7709 // the same type or "+42") we can pull the operation through the PHI, reducing
7710 // code size and simplifying code.
7711 Constant *ConstantOp = 0;
7712 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007713 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007714 if (isa<CastInst>(FirstInst)) {
7715 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007716 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007717 // Can fold binop, compare or shift here if the RHS is a constant,
7718 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007719 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007720 if (ConstantOp == 0)
7721 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007722 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7723 isVolatile = LI->isVolatile();
7724 // We can't sink the load if the loaded value could be modified between the
7725 // load and the PHI.
7726 if (LI->getParent() != PN.getIncomingBlock(0) ||
7727 !isSafeToSinkLoad(LI))
7728 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007729 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007730 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007731 return FoldPHIArgBinOpIntoPHI(PN);
7732 // Can't handle general GEPs yet.
7733 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007734 } else {
7735 return 0; // Cannot fold this operation.
7736 }
7737
7738 // Check to see if all arguments are the same operation.
7739 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7740 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7741 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007742 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007743 return 0;
7744 if (CastSrcTy) {
7745 if (I->getOperand(0)->getType() != CastSrcTy)
7746 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007747 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007748 // We can't sink the load if the loaded value could be modified between
7749 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007750 if (LI->isVolatile() != isVolatile ||
7751 LI->getParent() != PN.getIncomingBlock(i) ||
7752 !isSafeToSinkLoad(LI))
7753 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007754 } else if (I->getOperand(1) != ConstantOp) {
7755 return 0;
7756 }
7757 }
7758
7759 // Okay, they are all the same operation. Create a new PHI node of the
7760 // correct type, and PHI together all of the LHS's of the instructions.
7761 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7762 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007763 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007764
7765 Value *InVal = FirstInst->getOperand(0);
7766 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007767
7768 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007769 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7770 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7771 if (NewInVal != InVal)
7772 InVal = 0;
7773 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7774 }
7775
7776 Value *PhiVal;
7777 if (InVal) {
7778 // The new PHI unions all of the same values together. This is really
7779 // common, so we handle it intelligently here for compile-time speed.
7780 PhiVal = InVal;
7781 delete NewPN;
7782 } else {
7783 InsertNewInstBefore(NewPN, PN);
7784 PhiVal = NewPN;
7785 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007786
Chris Lattner7515cab2004-11-14 19:13:23 +00007787 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007788 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7789 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007790 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007791 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007792 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007793 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007794 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7795 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7796 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007797 else
Reid Spencer2341c222007-02-02 02:16:23 +00007798 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007799 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007800}
Chris Lattner48a44f72002-05-02 17:06:02 +00007801
Chris Lattner71536432005-01-17 05:10:15 +00007802/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7803/// that is dead.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007804static bool DeadPHICycle(PHINode *PN,
7805 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattner71536432005-01-17 05:10:15 +00007806 if (PN->use_empty()) return true;
7807 if (!PN->hasOneUse()) return false;
7808
7809 // Remember this node, and if we find the cycle, return.
Chris Lattnerd2602d52007-03-26 20:40:50 +00007810 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattner71536432005-01-17 05:10:15 +00007811 return true;
7812
7813 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7814 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007815
Chris Lattner71536432005-01-17 05:10:15 +00007816 return false;
7817}
7818
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007819// PHINode simplification
7820//
Chris Lattner113f4f42002-06-25 16:13:24 +00007821Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007822 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007823 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007824
Owen Andersonae8aa642006-07-10 22:03:18 +00007825 if (Value *V = PN.hasConstantValue())
7826 return ReplaceInstUsesWith(PN, V);
7827
Owen Andersonae8aa642006-07-10 22:03:18 +00007828 // If all PHI operands are the same operation, pull them through the PHI,
7829 // reducing code size.
7830 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7831 PN.getIncomingValue(0)->hasOneUse())
7832 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7833 return Result;
7834
7835 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7836 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7837 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007838 if (PN.hasOneUse()) {
7839 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7840 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattnerd2602d52007-03-26 20:40:50 +00007841 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Andersonae8aa642006-07-10 22:03:18 +00007842 PotentiallyDeadPHIs.insert(&PN);
7843 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7844 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7845 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007846
7847 // If this phi has a single use, and if that use just computes a value for
7848 // the next iteration of a loop, delete the phi. This occurs with unused
7849 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7850 // common case here is good because the only other things that catch this
7851 // are induction variable analysis (sometimes) and ADCE, which is only run
7852 // late.
7853 if (PHIUser->hasOneUse() &&
7854 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7855 PHIUser->use_back() == &PN) {
7856 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7857 }
7858 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007859
Chris Lattner91daeb52003-12-19 05:58:40 +00007860 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007861}
7862
Reid Spencer13bc5d72006-12-12 09:18:51 +00007863static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7864 Instruction *InsertPoint,
7865 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007866 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7867 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007868 // We must cast correctly to the pointer type. Ensure that we
7869 // sign extend the integer value if it is smaller as this is
7870 // used for address computation.
7871 Instruction::CastOps opcode =
7872 (VTySize < PtrSize ? Instruction::SExt :
7873 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7874 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007875}
7876
Chris Lattner48a44f72002-05-02 17:06:02 +00007877
Chris Lattner113f4f42002-06-25 16:13:24 +00007878Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007879 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007880 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007881 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007882 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007883 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007884
Chris Lattner81a7a232004-10-16 18:11:37 +00007885 if (isa<UndefValue>(GEP.getOperand(0)))
7886 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7887
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007888 bool HasZeroPointerIndex = false;
7889 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7890 HasZeroPointerIndex = C->isNullValue();
7891
7892 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007893 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007894
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007895 // Keep track of whether all indices are zero constants integers.
7896 bool AllZeroIndices = true;
7897
Chris Lattner69193f92004-04-05 01:30:19 +00007898 // Eliminate unneeded casts for indices.
7899 bool MadeChange = false;
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007900
Chris Lattner2b2412d2004-04-07 18:38:20 +00007901 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007902 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7903 // Track whether this GEP has all zero indices, if so, it doesn't move the
7904 // input pointer, it just changes its type.
7905 if (AllZeroIndices) {
7906 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7907 AllZeroIndices = CI->isNullValue();
7908 else
7909 AllZeroIndices = false;
7910 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007911 if (isa<SequentialType>(*GTI)) {
7912 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007913 if (CI->getOpcode() == Instruction::ZExt ||
7914 CI->getOpcode() == Instruction::SExt) {
7915 const Type *SrcTy = CI->getOperand(0)->getType();
7916 // We can eliminate a cast from i32 to i64 iff the target
7917 // is a 32-bit pointer target.
7918 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7919 MadeChange = true;
7920 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007921 }
7922 }
7923 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007924 // If we are using a wider index than needed for this platform, shrink it
7925 // to what we need. If the incoming value needs a cast instruction,
7926 // insert it. This explicit cast can make subsequent optimizations more
7927 // obvious.
7928 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007929 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007930 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007931 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007932 MadeChange = true;
7933 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007934 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7935 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007936 GEP.setOperand(i, Op);
7937 MadeChange = true;
7938 }
Chris Lattner69193f92004-04-05 01:30:19 +00007939 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007940 }
Chris Lattner69193f92004-04-05 01:30:19 +00007941 if (MadeChange) return &GEP;
7942
Chris Lattner9bf53ff2007-03-25 20:43:09 +00007943 // If this GEP instruction doesn't move the pointer, and if the input operand
7944 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7945 // real input to the dest type.
7946 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7947 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7948 GEP.getType());
7949
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007950 // Combine Indices - If the source pointer to this getelementptr instruction
7951 // is a getelementptr instruction, combine the indices of the two
7952 // getelementptr instructions into a single instruction.
7953 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007954 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007955 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007956 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007957
7958 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007959 // Note that if our source is a gep chain itself that we wait for that
7960 // chain to be resolved before we perform this transformation. This
7961 // avoids us creating a TON of code in some cases.
7962 //
7963 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7964 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7965 return 0; // Wait until our source is folded to completion.
7966
Chris Lattneraf6094f2007-02-15 22:48:32 +00007967 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007968
7969 // Find out whether the last index in the source GEP is a sequential idx.
7970 bool EndsWithSequential = false;
7971 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7972 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007973 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007974
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007975 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007976 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007977 // Replace: gep (gep %P, long B), long A, ...
7978 // With: T = long A+B; gep %P, T, ...
7979 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007980 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007981 if (SO1 == Constant::getNullValue(SO1->getType())) {
7982 Sum = GO1;
7983 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7984 Sum = SO1;
7985 } else {
7986 // If they aren't the same type, convert both to an integer of the
7987 // target's pointer size.
7988 if (SO1->getType() != GO1->getType()) {
7989 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007990 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007991 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007992 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007993 } else {
7994 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007995 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007996 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007997 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007998
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007999 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00008000 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00008001 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008002 } else {
8003 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00008004 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8005 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00008006 }
8007 }
8008 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008009 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8010 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8011 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00008012 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8013 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00008014 }
Chris Lattner69193f92004-04-05 01:30:19 +00008015 }
Chris Lattner5f667a62004-05-07 22:09:22 +00008016
8017 // Recycle the GEP we already have if possible.
8018 if (SrcGEPOperands.size() == 2) {
8019 GEP.setOperand(0, SrcGEPOperands[0]);
8020 GEP.setOperand(1, Sum);
8021 return &GEP;
8022 } else {
8023 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8024 SrcGEPOperands.end()-1);
8025 Indices.push_back(Sum);
8026 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8027 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008028 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00008029 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008030 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008031 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00008032 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8033 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008034 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8035 }
8036
8037 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00008038 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8039 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008040
Chris Lattner5f667a62004-05-07 22:09:22 +00008041 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008042 // GEP of global variable. If all of the indices for this GEP are
8043 // constants, we can promote this to a constexpr instead of an instruction.
8044
8045 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008046 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008047 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8048 for (; I != E && isa<Constant>(*I); ++I)
8049 Indices.push_back(cast<Constant>(*I));
8050
8051 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008052 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8053 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00008054
8055 // Replace all uses of the GEP with the new constexpr...
8056 return ReplaceInstUsesWith(GEP, CE);
8057 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008058 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00008059 if (!isa<PointerType>(X->getType())) {
8060 // Not interesting. Source pointer must be a cast from pointer.
8061 } else if (HasZeroPointerIndex) {
8062 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8063 // into : GEP [10 x ubyte]* X, long 0, ...
8064 //
8065 // This occurs when the program declares an array extern like "int X[];"
8066 //
8067 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8068 const PointerType *XTy = cast<PointerType>(X->getType());
8069 if (const ArrayType *XATy =
8070 dyn_cast<ArrayType>(XTy->getElementType()))
8071 if (const ArrayType *CATy =
8072 dyn_cast<ArrayType>(CPTy->getElementType()))
8073 if (CATy->getElementType() == XATy->getElementType()) {
8074 // At this point, we know that the cast source type is a pointer
8075 // to an array of the same type as the destination pointer
8076 // array. Because the array type is never stepped over (there
8077 // is a leading zero) we can fold the cast into this GEP.
8078 GEP.setOperand(0, X);
8079 return &GEP;
8080 }
8081 } else if (GEP.getNumOperands() == 2) {
8082 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00008083 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8084 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00008085 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8086 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8087 if (isa<ArrayType>(SrcElTy) &&
8088 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8089 TD->getTypeSize(ResElTy)) {
8090 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00008091 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00008092 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008093 // V and GEP are both pointer types --> BitCast
8094 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008095 }
Chris Lattner2a893292005-09-13 18:36:04 +00008096
8097 // Transform things like:
8098 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8099 // (where tmp = 8*tmp2) into:
8100 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8101
8102 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00008103 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00008104 uint64_t ArrayEltSize =
8105 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8106
8107 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8108 // allow either a mul, shift, or constant here.
8109 Value *NewIdx = 0;
8110 ConstantInt *Scale = 0;
8111 if (ArrayEltSize == 1) {
8112 NewIdx = GEP.getOperand(1);
8113 Scale = ConstantInt::get(NewIdx->getType(), 1);
8114 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00008115 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00008116 Scale = CI;
8117 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8118 if (Inst->getOpcode() == Instruction::Shl &&
8119 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Shengb25806f2007-03-30 09:29:48 +00008120 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8121 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8122 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner2a893292005-09-13 18:36:04 +00008123 NewIdx = Inst->getOperand(0);
8124 } else if (Inst->getOpcode() == Instruction::Mul &&
8125 isa<ConstantInt>(Inst->getOperand(1))) {
8126 Scale = cast<ConstantInt>(Inst->getOperand(1));
8127 NewIdx = Inst->getOperand(0);
8128 }
8129 }
8130
8131 // If the index will be to exactly the right offset with the scale taken
8132 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008133 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00008134 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00008135 Scale = ConstantInt::get(Scale->getType(),
8136 Scale->getZExtValue() / ArrayEltSize);
8137 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008138 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8139 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00008140 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8141 NewIdx = InsertNewInstBefore(Sc, GEP);
8142 }
8143
8144 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008145 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00008146 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00008147 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008148 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8149 // The NewGEP must be pointer typed, so must the old one -> BitCast
8150 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00008151 }
8152 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00008153 }
Chris Lattnerca081252001-12-14 16:52:21 +00008154 }
8155
Chris Lattnerca081252001-12-14 16:52:21 +00008156 return 0;
8157}
8158
Chris Lattner1085bdf2002-11-04 16:18:53 +00008159Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8160 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8161 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008162 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8163 const Type *NewTy =
8164 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008165 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008166
8167 // Create and insert the replacement instruction...
8168 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008169 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008170 else {
8171 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008172 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008173 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008174
8175 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008176
Chris Lattner1085bdf2002-11-04 16:18:53 +00008177 // Scan to the end of the allocation instructions, to skip over a block of
8178 // allocas if possible...
8179 //
8180 BasicBlock::iterator It = New;
8181 while (isa<AllocationInst>(*It)) ++It;
8182
8183 // Now that I is pointing to the first non-allocation-inst in the block,
8184 // insert our getelementptr instruction...
8185 //
Reid Spencerc635f472006-12-31 05:48:39 +00008186 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008187 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8188 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008189
8190 // Now make everything use the getelementptr instead of the original
8191 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008192 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008193 } else if (isa<UndefValue>(AI.getArraySize())) {
8194 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008195 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008196
8197 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8198 // Note that we only do this for alloca's, because malloc should allocate and
8199 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008200 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008201 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008202 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8203
Chris Lattner1085bdf2002-11-04 16:18:53 +00008204 return 0;
8205}
8206
Chris Lattner8427bff2003-12-07 01:24:23 +00008207Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8208 Value *Op = FI.getOperand(0);
8209
8210 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8211 if (CastInst *CI = dyn_cast<CastInst>(Op))
8212 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8213 FI.setOperand(0, CI->getOperand(0));
8214 return &FI;
8215 }
8216
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008217 // free undef -> unreachable.
8218 if (isa<UndefValue>(Op)) {
8219 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008220 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008221 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008222 return EraseInstFromFunction(FI);
8223 }
8224
Chris Lattnerf3a36602004-02-28 04:57:37 +00008225 // If we have 'free null' delete the instruction. This can happen in stl code
8226 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008227 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008228 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008229
Chris Lattner8427bff2003-12-07 01:24:23 +00008230 return 0;
8231}
8232
8233
Chris Lattner72684fe2005-01-31 05:51:45 +00008234/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008235static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8236 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008237 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008238
8239 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008240 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008241 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008242
Reid Spencer31a4ef42007-01-22 05:51:25 +00008243 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008244 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008245 // If the source is an array, the code below will not succeed. Check to
8246 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8247 // constants.
8248 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8249 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8250 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008251 Value *Idxs[2];
8252 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8253 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008254 SrcTy = cast<PointerType>(CastOp->getType());
8255 SrcPTy = SrcTy->getElementType();
8256 }
8257
Reid Spencer31a4ef42007-01-22 05:51:25 +00008258 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008259 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008260 // Do not allow turning this into a load of an integer, which is then
8261 // casted to a pointer, this pessimizes pointer analysis a lot.
8262 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008263 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8264 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008265
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008266 // Okay, we are casting from one integer or pointer type to another of
8267 // the same size. Instead of casting the pointer before the load, cast
8268 // the result of the loaded value.
8269 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8270 CI->getName(),
8271 LI.isVolatile()),LI);
8272 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008273 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008274 }
Chris Lattner35e24772004-07-13 01:49:43 +00008275 }
8276 }
8277 return 0;
8278}
8279
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008280/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008281/// from this value cannot trap. If it is not obviously safe to load from the
8282/// specified pointer, we do a quick local scan of the basic block containing
8283/// ScanFrom, to determine if the address is already accessed.
8284static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8285 // If it is an alloca or global variable, it is always safe to load from.
8286 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8287
8288 // Otherwise, be a little bit agressive by scanning the local block where we
8289 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008290 // from/to. If so, the previous load or store would have already trapped,
8291 // so there is no harm doing an extra load (also, CSE will later eliminate
8292 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008293 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8294
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008295 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008296 --BBI;
8297
8298 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8299 if (LI->getOperand(0) == V) return true;
8300 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8301 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008302
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008303 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008304 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008305}
8306
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008307Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8308 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008309
Chris Lattnera9d84e32005-05-01 04:24:53 +00008310 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008311 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008312 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8313 return Res;
8314
8315 // None of the following transforms are legal for volatile loads.
8316 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008317
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008318 if (&LI.getParent()->front() != &LI) {
8319 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008320 // If the instruction immediately before this is a store to the same
8321 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008322 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8323 if (SI->getOperand(1) == LI.getOperand(0))
8324 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008325 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8326 if (LIB->getOperand(0) == LI.getOperand(0))
8327 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008328 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008329
8330 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8331 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8332 isa<UndefValue>(GEPI->getOperand(0))) {
8333 // Insert a new store to null instruction before the load to indicate
8334 // that this code is not reachable. We do this instead of inserting
8335 // an unreachable instruction directly because we cannot modify the
8336 // CFG.
8337 new StoreInst(UndefValue::get(LI.getType()),
8338 Constant::getNullValue(Op->getType()), &LI);
8339 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8340 }
8341
Chris Lattner81a7a232004-10-16 18:11:37 +00008342 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008343 // load null/undef -> undef
8344 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008345 // Insert a new store to null instruction before the load to indicate that
8346 // this code is not reachable. We do this instead of inserting an
8347 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008348 new StoreInst(UndefValue::get(LI.getType()),
8349 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008350 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008351 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008352
Chris Lattner81a7a232004-10-16 18:11:37 +00008353 // Instcombine load (constant global) into the value loaded.
8354 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008355 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008356 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008357
Chris Lattner81a7a232004-10-16 18:11:37 +00008358 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8360 if (CE->getOpcode() == Instruction::GetElementPtr) {
8361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008362 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008363 if (Constant *V =
8364 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008365 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008366 if (CE->getOperand(0)->isNullValue()) {
8367 // Insert a new store to null instruction before the load to indicate
8368 // that this code is not reachable. We do this instead of inserting
8369 // an unreachable instruction directly because we cannot modify the
8370 // CFG.
8371 new StoreInst(UndefValue::get(LI.getType()),
8372 Constant::getNullValue(Op->getType()), &LI);
8373 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8374 }
8375
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008376 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008377 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8378 return Res;
8379 }
8380 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008381
Chris Lattnera9d84e32005-05-01 04:24:53 +00008382 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008383 // Change select and PHI nodes to select values instead of addresses: this
8384 // helps alias analysis out a lot, allows many others simplifications, and
8385 // exposes redundancy in the code.
8386 //
8387 // Note that we cannot do the transformation unless we know that the
8388 // introduced loads cannot trap! Something like this is valid as long as
8389 // the condition is always false: load (select bool %C, int* null, int* %G),
8390 // but it would not be valid if we transformed it to load from null
8391 // unconditionally.
8392 //
8393 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8394 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008395 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8396 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008397 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008398 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008399 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008400 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008401 return new SelectInst(SI->getCondition(), V1, V2);
8402 }
8403
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008404 // load (select (cond, null, P)) -> load P
8405 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8406 if (C->isNullValue()) {
8407 LI.setOperand(0, SI->getOperand(2));
8408 return &LI;
8409 }
8410
8411 // load (select (cond, P, null)) -> load P
8412 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8413 if (C->isNullValue()) {
8414 LI.setOperand(0, SI->getOperand(1));
8415 return &LI;
8416 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008417 }
8418 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008419 return 0;
8420}
8421
Reid Spencere928a152007-01-19 21:20:31 +00008422/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008423/// when possible.
8424static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8425 User *CI = cast<User>(SI.getOperand(1));
8426 Value *CastOp = CI->getOperand(0);
8427
8428 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8429 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8430 const Type *SrcPTy = SrcTy->getElementType();
8431
Reid Spencer31a4ef42007-01-22 05:51:25 +00008432 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008433 // If the source is an array, the code below will not succeed. Check to
8434 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8435 // constants.
8436 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8437 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8438 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008439 Value* Idxs[2];
8440 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8441 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008442 SrcTy = cast<PointerType>(CastOp->getType());
8443 SrcPTy = SrcTy->getElementType();
8444 }
8445
Reid Spencer9a4bed02007-01-20 23:35:48 +00008446 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8447 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8448 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008449
8450 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008451 // the same size. Instead of casting the pointer before
8452 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008453 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008454 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008455 Instruction::CastOps opcode = Instruction::BitCast;
8456 const Type* CastSrcTy = SIOp0->getType();
8457 const Type* CastDstTy = SrcPTy;
8458 if (isa<PointerType>(CastDstTy)) {
8459 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008460 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008461 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008462 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008463 opcode = Instruction::PtrToInt;
8464 }
8465 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008466 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008467 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008468 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008469 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8470 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008471 return new StoreInst(NewCast, CastOp);
8472 }
8473 }
8474 }
8475 return 0;
8476}
8477
Chris Lattner31f486c2005-01-31 05:36:43 +00008478Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8479 Value *Val = SI.getOperand(0);
8480 Value *Ptr = SI.getOperand(1);
8481
8482 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008483 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008484 ++NumCombined;
8485 return 0;
8486 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008487
8488 // If the RHS is an alloca with a single use, zapify the store, making the
8489 // alloca dead.
8490 if (Ptr->hasOneUse()) {
8491 if (isa<AllocaInst>(Ptr)) {
8492 EraseInstFromFunction(SI);
8493 ++NumCombined;
8494 return 0;
8495 }
8496
8497 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8498 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8499 GEP->getOperand(0)->hasOneUse()) {
8500 EraseInstFromFunction(SI);
8501 ++NumCombined;
8502 return 0;
8503 }
8504 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008505
Chris Lattner5997cf92006-02-08 03:25:32 +00008506 // Do really simple DSE, to catch cases where there are several consequtive
8507 // stores to the same location, separated by a few arithmetic operations. This
8508 // situation often occurs with bitfield accesses.
8509 BasicBlock::iterator BBI = &SI;
8510 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8511 --ScanInsts) {
8512 --BBI;
8513
8514 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8515 // Prev store isn't volatile, and stores to the same location?
8516 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8517 ++NumDeadStore;
8518 ++BBI;
8519 EraseInstFromFunction(*PrevSI);
8520 continue;
8521 }
8522 break;
8523 }
8524
Chris Lattnerdab43b22006-05-26 19:19:20 +00008525 // If this is a load, we have to stop. However, if the loaded value is from
8526 // the pointer we're loading and is producing the pointer we're storing,
8527 // then *this* store is dead (X = load P; store X -> P).
8528 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8529 if (LI == Val && LI->getOperand(0) == Ptr) {
8530 EraseInstFromFunction(SI);
8531 ++NumCombined;
8532 return 0;
8533 }
8534 // Otherwise, this is a load from some other location. Stores before it
8535 // may not be dead.
8536 break;
8537 }
8538
Chris Lattner5997cf92006-02-08 03:25:32 +00008539 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008540 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008541 break;
8542 }
8543
8544
8545 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008546
8547 // store X, null -> turns into 'unreachable' in SimplifyCFG
8548 if (isa<ConstantPointerNull>(Ptr)) {
8549 if (!isa<UndefValue>(Val)) {
8550 SI.setOperand(0, UndefValue::get(Val->getType()));
8551 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008552 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008553 ++NumCombined;
8554 }
8555 return 0; // Do not modify these!
8556 }
8557
8558 // store undef, Ptr -> noop
8559 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008560 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008561 ++NumCombined;
8562 return 0;
8563 }
8564
Chris Lattner72684fe2005-01-31 05:51:45 +00008565 // If the pointer destination is a cast, see if we can fold the cast into the
8566 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008567 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008568 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8569 return Res;
8570 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008571 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008572 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8573 return Res;
8574
Chris Lattner219175c2005-09-12 23:23:25 +00008575
8576 // If this store is the last instruction in the basic block, and if the block
8577 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008578 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008579 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8580 if (BI->isUnconditional()) {
8581 // Check to see if the successor block has exactly two incoming edges. If
8582 // so, see if the other predecessor contains a store to the same location.
8583 // if so, insert a PHI node (if needed) and move the stores down.
8584 BasicBlock *Dest = BI->getSuccessor(0);
8585
8586 pred_iterator PI = pred_begin(Dest);
8587 BasicBlock *Other = 0;
8588 if (*PI != BI->getParent())
8589 Other = *PI;
8590 ++PI;
8591 if (PI != pred_end(Dest)) {
8592 if (*PI != BI->getParent())
8593 if (Other)
8594 Other = 0;
8595 else
8596 Other = *PI;
8597 if (++PI != pred_end(Dest))
8598 Other = 0;
8599 }
8600 if (Other) { // If only one other pred...
8601 BBI = Other->getTerminator();
8602 // Make sure this other block ends in an unconditional branch and that
8603 // there is an instruction before the branch.
8604 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8605 BBI != Other->begin()) {
8606 --BBI;
8607 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8608
8609 // If this instruction is a store to the same location.
8610 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8611 // Okay, we know we can perform this transformation. Insert a PHI
8612 // node now if we need it.
8613 Value *MergedVal = OtherStore->getOperand(0);
8614 if (MergedVal != SI.getOperand(0)) {
8615 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8616 PN->reserveOperandSpace(2);
8617 PN->addIncoming(SI.getOperand(0), SI.getParent());
8618 PN->addIncoming(OtherStore->getOperand(0), Other);
8619 MergedVal = InsertNewInstBefore(PN, Dest->front());
8620 }
8621
8622 // Advance to a place where it is safe to insert the new store and
8623 // insert it.
8624 BBI = Dest->begin();
8625 while (isa<PHINode>(BBI)) ++BBI;
8626 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8627 OtherStore->isVolatile()), *BBI);
8628
8629 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008630 EraseInstFromFunction(SI);
8631 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008632 ++NumCombined;
8633 return 0;
8634 }
8635 }
8636 }
8637 }
8638
Chris Lattner31f486c2005-01-31 05:36:43 +00008639 return 0;
8640}
8641
8642
Chris Lattner9eef8a72003-06-04 04:46:00 +00008643Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8644 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008645 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008646 BasicBlock *TrueDest;
8647 BasicBlock *FalseDest;
8648 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8649 !isa<Constant>(X)) {
8650 // Swap Destinations and condition...
8651 BI.setCondition(X);
8652 BI.setSuccessor(0, FalseDest);
8653 BI.setSuccessor(1, TrueDest);
8654 return &BI;
8655 }
8656
Reid Spencer266e42b2006-12-23 06:05:41 +00008657 // Cannonicalize fcmp_one -> fcmp_oeq
8658 FCmpInst::Predicate FPred; Value *Y;
8659 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8660 TrueDest, FalseDest)))
8661 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8662 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8663 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008664 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008665 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8666 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008667 // Swap Destinations and condition...
8668 BI.setCondition(NewSCC);
8669 BI.setSuccessor(0, FalseDest);
8670 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008671 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008672 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008673 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008674 return &BI;
8675 }
8676
8677 // Cannonicalize icmp_ne -> icmp_eq
8678 ICmpInst::Predicate IPred;
8679 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8680 TrueDest, FalseDest)))
8681 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8682 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8683 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8684 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008685 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008686 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8687 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008688 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008689 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008690 BI.setSuccessor(0, FalseDest);
8691 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008692 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008693 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008694 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008695 return &BI;
8696 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008697
Chris Lattner9eef8a72003-06-04 04:46:00 +00008698 return 0;
8699}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008700
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008701Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8702 Value *Cond = SI.getCondition();
8703 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8704 if (I->getOpcode() == Instruction::Add)
8705 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8706 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8707 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008708 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008709 AddRHS));
8710 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008711 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008712 return &SI;
8713 }
8714 }
8715 return 0;
8716}
8717
Chris Lattner6bc98652006-03-05 00:22:33 +00008718/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8719/// is to leave as a vector operation.
8720static bool CheapToScalarize(Value *V, bool isConstant) {
8721 if (isa<ConstantAggregateZero>(V))
8722 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008723 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008724 if (isConstant) return true;
8725 // If all elts are the same, we can extract.
8726 Constant *Op0 = C->getOperand(0);
8727 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8728 if (C->getOperand(i) != Op0)
8729 return false;
8730 return true;
8731 }
8732 Instruction *I = dyn_cast<Instruction>(V);
8733 if (!I) return false;
8734
8735 // Insert element gets simplified to the inserted element or is deleted if
8736 // this is constant idx extract element and its a constant idx insertelt.
8737 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8738 isa<ConstantInt>(I->getOperand(2)))
8739 return true;
8740 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8741 return true;
8742 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8743 if (BO->hasOneUse() &&
8744 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8745 CheapToScalarize(BO->getOperand(1), isConstant)))
8746 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008747 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8748 if (CI->hasOneUse() &&
8749 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8750 CheapToScalarize(CI->getOperand(1), isConstant)))
8751 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008752
8753 return false;
8754}
8755
Chris Lattner945e4372007-02-14 05:52:17 +00008756/// Read and decode a shufflevector mask.
8757///
8758/// It turns undef elements into values that are larger than the number of
8759/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008760static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8761 unsigned NElts = SVI->getType()->getNumElements();
8762 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8763 return std::vector<unsigned>(NElts, 0);
8764 if (isa<UndefValue>(SVI->getOperand(2)))
8765 return std::vector<unsigned>(NElts, 2*NElts);
8766
8767 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008768 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008769 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8770 if (isa<UndefValue>(CP->getOperand(i)))
8771 Result.push_back(NElts*2); // undef -> 8
8772 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008773 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008774 return Result;
8775}
8776
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008777/// FindScalarElement - Given a vector and an element number, see if the scalar
8778/// value is already around as a register, for example if it were inserted then
8779/// extracted from the vector.
8780static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008781 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8782 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008783 unsigned Width = PTy->getNumElements();
8784 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008785 return UndefValue::get(PTy->getElementType());
8786
8787 if (isa<UndefValue>(V))
8788 return UndefValue::get(PTy->getElementType());
8789 else if (isa<ConstantAggregateZero>(V))
8790 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008791 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008792 return CP->getOperand(EltNo);
8793 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8794 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008795 if (!isa<ConstantInt>(III->getOperand(2)))
8796 return 0;
8797 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008798
8799 // If this is an insert to the element we are looking for, return the
8800 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008801 if (EltNo == IIElt)
8802 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008803
8804 // Otherwise, the insertelement doesn't modify the value, recurse on its
8805 // vector input.
8806 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008807 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008808 unsigned InEl = getShuffleMask(SVI)[EltNo];
8809 if (InEl < Width)
8810 return FindScalarElement(SVI->getOperand(0), InEl);
8811 else if (InEl < Width*2)
8812 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8813 else
8814 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008815 }
8816
8817 // Otherwise, we don't know.
8818 return 0;
8819}
8820
Robert Bocchinoa8352962006-01-13 22:48:06 +00008821Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008822
Chris Lattner92346c32006-03-31 18:25:14 +00008823 // If packed val is undef, replace extract with scalar undef.
8824 if (isa<UndefValue>(EI.getOperand(0)))
8825 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8826
8827 // If packed val is constant 0, replace extract with scalar 0.
8828 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8829 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8830
Reid Spencerd84d35b2007-02-15 02:26:10 +00008831 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008832 // If packed val is constant with uniform operands, replace EI
8833 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008834 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008835 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008836 if (C->getOperand(i) != op0) {
8837 op0 = 0;
8838 break;
8839 }
8840 if (op0)
8841 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008842 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008843
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008844 // If extracting a specified index from the vector, see if we can recursively
8845 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008846 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008847 // This instruction only demands the single element from the input vector.
8848 // If the input vector has a single use, simplify it based on this use
8849 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008850 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008851 if (EI.getOperand(0)->hasOneUse()) {
8852 uint64_t UndefElts;
8853 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008854 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008855 UndefElts)) {
8856 EI.setOperand(0, V);
8857 return &EI;
8858 }
8859 }
8860
Reid Spencere0fc4df2006-10-20 07:07:24 +00008861 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008862 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008863 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008864
Chris Lattner83f65782006-05-25 22:53:38 +00008865 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008866 if (I->hasOneUse()) {
8867 // Push extractelement into predecessor operation if legal and
8868 // profitable to do so
8869 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008870 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8871 if (CheapToScalarize(BO, isConstantElt)) {
8872 ExtractElementInst *newEI0 =
8873 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8874 EI.getName()+".lhs");
8875 ExtractElementInst *newEI1 =
8876 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8877 EI.getName()+".rhs");
8878 InsertNewInstBefore(newEI0, EI);
8879 InsertNewInstBefore(newEI1, EI);
8880 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8881 }
Reid Spencerde46e482006-11-02 20:25:50 +00008882 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008883 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008884 PointerType::get(EI.getType()), EI);
8885 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008886 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008887 InsertNewInstBefore(GEP, EI);
8888 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008889 }
8890 }
8891 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8892 // Extracting the inserted element?
8893 if (IE->getOperand(2) == EI.getOperand(1))
8894 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8895 // If the inserted and extracted elements are constants, they must not
8896 // be the same value, extract from the pre-inserted value instead.
8897 if (isa<Constant>(IE->getOperand(2)) &&
8898 isa<Constant>(EI.getOperand(1))) {
8899 AddUsesToWorkList(EI);
8900 EI.setOperand(0, IE->getOperand(0));
8901 return &EI;
8902 }
8903 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8904 // If this is extracting an element from a shufflevector, figure out where
8905 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008906 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8907 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008908 Value *Src;
8909 if (SrcIdx < SVI->getType()->getNumElements())
8910 Src = SVI->getOperand(0);
8911 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8912 SrcIdx -= SVI->getType()->getNumElements();
8913 Src = SVI->getOperand(1);
8914 } else {
8915 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008916 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008917 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008918 }
8919 }
Chris Lattner83f65782006-05-25 22:53:38 +00008920 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008921 return 0;
8922}
8923
Chris Lattner90951862006-04-16 00:51:47 +00008924/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8925/// elements from either LHS or RHS, return the shuffle mask and true.
8926/// Otherwise, return false.
8927static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8928 std::vector<Constant*> &Mask) {
8929 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8930 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008931 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008932
8933 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008934 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008935 return true;
8936 } else if (V == LHS) {
8937 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008938 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008939 return true;
8940 } else if (V == RHS) {
8941 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008942 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008943 return true;
8944 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8945 // If this is an insert of an extract from some other vector, include it.
8946 Value *VecOp = IEI->getOperand(0);
8947 Value *ScalarOp = IEI->getOperand(1);
8948 Value *IdxOp = IEI->getOperand(2);
8949
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008950 if (!isa<ConstantInt>(IdxOp))
8951 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008952 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008953
8954 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8955 // Okay, we can handle this if the vector we are insertinting into is
8956 // transitively ok.
8957 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8958 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008959 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008960 return true;
8961 }
8962 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8963 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008964 EI->getOperand(0)->getType() == V->getType()) {
8965 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008966 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008967
8968 // This must be extracting from either LHS or RHS.
8969 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8970 // Okay, we can handle this if the vector we are insertinting into is
8971 // transitively ok.
8972 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8973 // If so, update the mask to reflect the inserted value.
8974 if (EI->getOperand(0) == LHS) {
8975 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008976 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008977 } else {
8978 assert(EI->getOperand(0) == RHS);
8979 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008980 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008981
8982 }
8983 return true;
8984 }
8985 }
8986 }
8987 }
8988 }
8989 // TODO: Handle shufflevector here!
8990
8991 return false;
8992}
8993
8994/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8995/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8996/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008997static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008998 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008999 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00009000 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00009001 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00009002 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00009003
9004 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009005 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009006 return V;
9007 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00009008 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00009009 return V;
9010 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9011 // If this is an insert of an extract from some other vector, include it.
9012 Value *VecOp = IEI->getOperand(0);
9013 Value *ScalarOp = IEI->getOperand(1);
9014 Value *IdxOp = IEI->getOperand(2);
9015
9016 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9017 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9018 EI->getOperand(0)->getType() == V->getType()) {
9019 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00009020 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9021 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009022
9023 // Either the extracted from or inserted into vector must be RHSVec,
9024 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00009025 if (EI->getOperand(0) == RHS || RHS == 0) {
9026 RHS = EI->getOperand(0);
9027 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009028 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00009029 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009030 return V;
9031 }
9032
Chris Lattner90951862006-04-16 00:51:47 +00009033 if (VecOp == RHS) {
9034 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00009035 // Everything but the extracted element is replaced with the RHS.
9036 for (unsigned i = 0; i != NumElts; ++i) {
9037 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00009038 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00009039 }
9040 return V;
9041 }
Chris Lattner90951862006-04-16 00:51:47 +00009042
9043 // If this insertelement is a chain that comes from exactly these two
9044 // vectors, return the vector and the effective shuffle.
9045 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9046 return EI->getOperand(0);
9047
Chris Lattner39fac442006-04-15 01:39:45 +00009048 }
9049 }
9050 }
Chris Lattner90951862006-04-16 00:51:47 +00009051 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00009052
9053 // Otherwise, can't do anything fancy. Return an identity vector.
9054 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00009055 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00009056 return V;
9057}
9058
9059Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9060 Value *VecOp = IE.getOperand(0);
9061 Value *ScalarOp = IE.getOperand(1);
9062 Value *IdxOp = IE.getOperand(2);
9063
9064 // If the inserted element was extracted from some other vector, and if the
9065 // indexes are constant, try to turn this into a shufflevector operation.
9066 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9067 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9068 EI->getOperand(0)->getType() == IE.getType()) {
9069 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00009070 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9071 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00009072
9073 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9074 return ReplaceInstUsesWith(IE, VecOp);
9075
9076 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9077 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9078
9079 // If we are extracting a value from a vector, then inserting it right
9080 // back into the same place, just use the input vector.
9081 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9082 return ReplaceInstUsesWith(IE, VecOp);
9083
9084 // We could theoretically do this for ANY input. However, doing so could
9085 // turn chains of insertelement instructions into a chain of shufflevector
9086 // instructions, and right now we do not merge shufflevectors. As such,
9087 // only do this in a situation where it is clear that there is benefit.
9088 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9089 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9090 // the values of VecOp, except then one read from EIOp0.
9091 // Build a new shuffle mask.
9092 std::vector<Constant*> Mask;
9093 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00009094 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00009095 else {
9096 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00009097 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00009098 NumVectorElts));
9099 }
Reid Spencerc635f472006-12-31 05:48:39 +00009100 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00009101 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00009102 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009103 }
9104
9105 // If this insertelement isn't used by some other insertelement, turn it
9106 // (and any insertelements it points to), into one big shuffle.
9107 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9108 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00009109 Value *RHS = 0;
9110 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9111 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9112 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00009113 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00009114 }
9115 }
9116 }
9117
9118 return 0;
9119}
9120
9121
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009122Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9123 Value *LHS = SVI.getOperand(0);
9124 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00009125 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009126
9127 bool MadeChange = false;
9128
Chris Lattner2deeaea2006-10-05 06:55:50 +00009129 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00009130 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009131 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9132
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009133 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00009134 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009135 if (isa<UndefValue>(SVI.getOperand(1))) {
9136 // Scan to see if there are any references to the RHS. If so, replace them
9137 // with undef element refs and set MadeChange to true.
9138 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9139 if (Mask[i] >= e && Mask[i] != 2*e) {
9140 Mask[i] = 2*e;
9141 MadeChange = true;
9142 }
9143 }
9144
9145 if (MadeChange) {
9146 // Remap any references to RHS to use LHS.
9147 std::vector<Constant*> Elts;
9148 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9149 if (Mask[i] == 2*e)
9150 Elts.push_back(UndefValue::get(Type::Int32Ty));
9151 else
9152 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9153 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009154 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009155 }
9156 }
Chris Lattner39fac442006-04-15 01:39:45 +00009157
Chris Lattner12249be2006-05-25 23:48:38 +00009158 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9159 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9160 if (LHS == RHS || isa<UndefValue>(LHS)) {
9161 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009162 // shuffle(undef,undef,mask) -> undef.
9163 return ReplaceInstUsesWith(SVI, LHS);
9164 }
9165
Chris Lattner12249be2006-05-25 23:48:38 +00009166 // Remap any references to RHS to use LHS.
9167 std::vector<Constant*> Elts;
9168 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009169 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009170 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009171 else {
9172 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9173 (Mask[i] < e && isa<UndefValue>(LHS)))
9174 Mask[i] = 2*e; // Turn into undef.
9175 else
9176 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009177 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009178 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009179 }
Chris Lattner12249be2006-05-25 23:48:38 +00009180 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009181 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009182 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009183 LHS = SVI.getOperand(0);
9184 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009185 MadeChange = true;
9186 }
9187
Chris Lattner0e477162006-05-26 00:29:06 +00009188 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009189 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009190
Chris Lattner12249be2006-05-25 23:48:38 +00009191 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9192 if (Mask[i] >= e*2) continue; // Ignore undef values.
9193 // Is this an identity shuffle of the LHS value?
9194 isLHSID &= (Mask[i] == i);
9195
9196 // Is this an identity shuffle of the RHS value?
9197 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009198 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009199
Chris Lattner12249be2006-05-25 23:48:38 +00009200 // Eliminate identity shuffles.
9201 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9202 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009203
Chris Lattner0e477162006-05-26 00:29:06 +00009204 // If the LHS is a shufflevector itself, see if we can combine it with this
9205 // one without producing an unusual shuffle. Here we are really conservative:
9206 // we are absolutely afraid of producing a shuffle mask not in the input
9207 // program, because the code gen may not be smart enough to turn a merged
9208 // shuffle into two specific shuffles: it may produce worse code. As such,
9209 // we only merge two shuffles if the result is one of the two input shuffle
9210 // masks. In this case, merging the shuffles just removes one instruction,
9211 // which we know is safe. This is good for things like turning:
9212 // (splat(splat)) -> splat.
9213 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9214 if (isa<UndefValue>(RHS)) {
9215 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9216
9217 std::vector<unsigned> NewMask;
9218 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9219 if (Mask[i] >= 2*e)
9220 NewMask.push_back(2*e);
9221 else
9222 NewMask.push_back(LHSMask[Mask[i]]);
9223
9224 // If the result mask is equal to the src shuffle or this shuffle mask, do
9225 // the replacement.
9226 if (NewMask == LHSMask || NewMask == Mask) {
9227 std::vector<Constant*> Elts;
9228 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9229 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009230 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009231 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009232 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009233 }
9234 }
9235 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9236 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009237 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009238 }
9239 }
9240 }
Chris Lattner4284f642007-01-30 22:32:46 +00009241
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009242 return MadeChange ? &SVI : 0;
9243}
9244
9245
Robert Bocchinoa8352962006-01-13 22:48:06 +00009246
Chris Lattner39c98bb2004-12-08 23:43:58 +00009247
9248/// TryToSinkInstruction - Try to move the specified instruction from its
9249/// current block into the beginning of DestBlock, which can only happen if it's
9250/// safe to move the instruction past all of the instructions between it and the
9251/// end of its block.
9252static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9253 assert(I->hasOneUse() && "Invariants didn't hold!");
9254
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009255 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9256 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009257
Chris Lattner39c98bb2004-12-08 23:43:58 +00009258 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00009259 if (isa<AllocaInst>(I) && I->getParent() ==
9260 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00009261 return false;
9262
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009263 // We can only sink load instructions if there is nothing between the load and
9264 // the end of block that could change the value.
9265 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009266 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9267 Scan != E; ++Scan)
9268 if (Scan->mayWriteToMemory())
9269 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009270 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009271
9272 BasicBlock::iterator InsertPos = DestBlock->begin();
9273 while (isa<PHINode>(InsertPos)) ++InsertPos;
9274
Chris Lattner9f269e42005-08-08 19:11:57 +00009275 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009276 ++NumSunkInst;
9277 return true;
9278}
9279
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009280
9281/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9282/// all reachable code to the worklist.
9283///
9284/// This has a couple of tricks to make the code faster and more powerful. In
9285/// particular, we constant fold and DCE instructions as we go, to avoid adding
9286/// them to the worklist (this significantly speeds up instcombine on code where
9287/// many instructions are dead or constant). Additionally, if we find a branch
9288/// whose condition is a known constant, we only visit the reachable successors.
9289///
9290static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009291 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009292 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009293 const TargetData *TD) {
Chris Lattner12b89cc2007-03-23 19:17:18 +00009294 std::vector<BasicBlock*> Worklist;
9295 Worklist.push_back(BB);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009296
Chris Lattner12b89cc2007-03-23 19:17:18 +00009297 while (!Worklist.empty()) {
9298 BB = Worklist.back();
9299 Worklist.pop_back();
9300
9301 // We have now visited this block! If we've already been here, ignore it.
9302 if (!Visited.insert(BB)) continue;
9303
9304 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9305 Instruction *Inst = BBI++;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009306
Chris Lattner12b89cc2007-03-23 19:17:18 +00009307 // DCE instruction if trivially dead.
9308 if (isInstructionTriviallyDead(Inst)) {
9309 ++NumDeadInst;
9310 DOUT << "IC: DCE: " << *Inst;
9311 Inst->eraseFromParent();
9312 continue;
9313 }
9314
9315 // ConstantProp instruction if trivially constant.
9316 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9317 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9318 Inst->replaceAllUsesWith(C);
9319 ++NumConstProp;
9320 Inst->eraseFromParent();
9321 continue;
9322 }
9323
9324 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009325 }
Chris Lattner12b89cc2007-03-23 19:17:18 +00009326
9327 // Recursively visit successors. If this is a branch or switch on a
9328 // constant, only visit the reachable successor.
9329 TerminatorInst *TI = BB->getTerminator();
9330 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9331 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9332 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9333 Worklist.push_back(BI->getSuccessor(!CondVal));
9334 continue;
9335 }
9336 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9337 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9338 // See if this is an explicit destination.
9339 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9340 if (SI->getCaseValue(i) == Cond) {
9341 Worklist.push_back(SI->getSuccessor(i));
9342 continue;
9343 }
9344
9345 // Otherwise it is the default destination.
9346 Worklist.push_back(SI->getSuccessor(0));
9347 continue;
9348 }
9349 }
9350
9351 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9352 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009353 }
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009354}
9355
Chris Lattner960a5432007-03-03 02:04:50 +00009356bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009357 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009358 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009359
9360 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9361 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009362
Chris Lattner4ed40f72005-07-07 20:40:38 +00009363 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009364 // Do a depth-first traversal of the function, populate the worklist with
9365 // the reachable instructions. Ignore blocks that are not reachable. Keep
9366 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009367 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009368 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009369
Chris Lattner4ed40f72005-07-07 20:40:38 +00009370 // Do a quick scan over the function. If we find any blocks that are
9371 // unreachable, remove any instructions inside of them. This prevents
9372 // the instcombine code from having to deal with some bad special cases.
9373 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9374 if (!Visited.count(BB)) {
9375 Instruction *Term = BB->getTerminator();
9376 while (Term != BB->begin()) { // Remove instrs bottom-up
9377 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009378
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009379 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009380 ++NumDeadInst;
9381
9382 if (!I->use_empty())
9383 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9384 I->eraseFromParent();
9385 }
9386 }
9387 }
Chris Lattnerca081252001-12-14 16:52:21 +00009388
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009389 while (!Worklist.empty()) {
9390 Instruction *I = RemoveOneFromWorkList();
9391 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009392
Chris Lattner1443bc52006-05-11 17:11:52 +00009393 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009394 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009395 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009396 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009397 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009398 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009399
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009400 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009401
9402 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009403 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009404 continue;
9405 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009406
Chris Lattner1443bc52006-05-11 17:11:52 +00009407 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009408 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009409 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009410
Chris Lattner1443bc52006-05-11 17:11:52 +00009411 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009412 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009413 ReplaceInstUsesWith(*I, C);
9414
Chris Lattner99f48c62002-09-02 04:59:56 +00009415 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009416 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009417 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009418 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009419 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009420
Chris Lattner39c98bb2004-12-08 23:43:58 +00009421 // See if we can trivially sink this instruction to a successor basic block.
9422 if (I->hasOneUse()) {
9423 BasicBlock *BB = I->getParent();
9424 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9425 if (UserParent != BB) {
9426 bool UserIsSuccessor = false;
9427 // See if the user is one of our successors.
9428 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9429 if (*SI == UserParent) {
9430 UserIsSuccessor = true;
9431 break;
9432 }
9433
9434 // If the user is one of our immediate successors, and if that successor
9435 // only has us as a predecessors (we'd have to split the critical edge
9436 // otherwise), we can keep going.
9437 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9438 next(pred_begin(UserParent)) == pred_end(UserParent))
9439 // Okay, the CFG is simple enough, try to sink this instruction.
9440 Changed |= TryToSinkInstruction(I, UserParent);
9441 }
9442 }
9443
Chris Lattnerca081252001-12-14 16:52:21 +00009444 // Now that we have an instruction, try combining it to simplify it...
Reid Spencer755d0e72007-03-26 17:44:01 +00009445#ifndef NDEBUG
9446 std::string OrigI;
9447#endif
9448 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009449 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009450 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009451 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009452 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009453 DOUT << "IC: Old = " << *I
9454 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009455
Chris Lattner396dbfe2004-06-09 05:08:07 +00009456 // Everything uses the new instruction now.
9457 I->replaceAllUsesWith(Result);
9458
9459 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009460 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009461 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009462
Chris Lattner6e0123b2007-02-11 01:23:03 +00009463 // Move the name to the new instruction first.
9464 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009465
9466 // Insert the new instruction into the basic block...
9467 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009468 BasicBlock::iterator InsertPos = I;
9469
9470 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9471 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9472 ++InsertPos;
9473
9474 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009475
Chris Lattner63d75af2004-05-01 23:27:23 +00009476 // Make sure that we reprocess all operands now that we reduced their
9477 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009478 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009479
Chris Lattner396dbfe2004-06-09 05:08:07 +00009480 // Instructions can end up on the worklist more than once. Make sure
9481 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009482 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009483
9484 // Erase the old instruction.
9485 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009486 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00009487#ifndef NDEBUG
Reid Spencer755d0e72007-03-26 17:44:01 +00009488 DOUT << "IC: Mod = " << OrigI
9489 << " New = " << *I;
Evan Chenga4ed8a52007-03-27 16:44:48 +00009490#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00009491
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009492 // If the instruction was modified, it's possible that it is now dead.
9493 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009494 if (isInstructionTriviallyDead(I)) {
9495 // Make sure we process all operands now that we are reducing their
9496 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009497 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009498
Chris Lattner63d75af2004-05-01 23:27:23 +00009499 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009500 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009501 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009502 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009503 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009504 AddToWorkList(I);
9505 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009506 }
Chris Lattner053c0932002-05-14 15:24:07 +00009507 }
Chris Lattner260ab202002-04-18 17:39:14 +00009508 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009509 }
9510 }
9511
Chris Lattner960a5432007-03-03 02:04:50 +00009512 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009513 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009514}
9515
Chris Lattner960a5432007-03-03 02:04:50 +00009516
9517bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009518 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9519
Chris Lattner960a5432007-03-03 02:04:50 +00009520 bool EverMadeChange = false;
9521
9522 // Iterate while there is work to do.
9523 unsigned Iteration = 0;
9524 while (DoOneIteration(F, Iteration++))
9525 EverMadeChange = true;
9526 return EverMadeChange;
9527}
9528
Brian Gaeke38b79e82004-07-27 17:43:21 +00009529FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009530 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009531}
Brian Gaeke960707c2003-11-11 22:41:34 +00009532