blob: e8dbb73a88f471882dae3f9f8ea6ecdcf03ccdc6 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000050#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000052#include "llvm/Support/Compiler.h"
Chris Lattnerb15e2b12007-03-02 21:28:56 +000053#include "llvm/ADT/DenseMap.h"
Chris Lattnerf96f4a82007-01-31 04:40:53 +000054#include "llvm/ADT/SmallVector.h"
Chris Lattner7907e5f2007-02-15 19:41:52 +000055#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000058#include <algorithm>
Reid Spencer3f4e6e82007-02-04 00:40:42 +000059#include <set>
Chris Lattner8427bff2003-12-07 01:24:23 +000060using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000061using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000062
Chris Lattner79a42ac2006-12-19 21:40:18 +000063STATISTIC(NumCombined , "Number of insts combined");
64STATISTIC(NumConstProp, "Number of constant folds");
65STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000068
Chris Lattner79a42ac2006-12-19 21:40:18 +000069namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000070 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000073 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerb15e2b12007-03-02 21:28:56 +000074 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000076 TargetData *TD;
Chris Lattner8258b442007-03-04 04:27:24 +000077 bool MustPreserveLCSSA;
Chris Lattnerb15e2b12007-03-02 21:28:56 +000078 public:
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
84 }
85
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
90
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
93
94 WorklistMap.erase(It);
95 }
96
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
99 Worklist.pop_back();
100 WorklistMap.erase(I);
101 return I;
102 }
Chris Lattner260ab202002-04-18 17:39:14 +0000103
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000104
Chris Lattner51ea1272004-02-28 05:22:00 +0000105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
107 /// now.
108 ///
Chris Lattner2590e512006-02-07 06:56:34 +0000109 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +0000111 UI != UE; ++UI)
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000112 AddToWorkList(cast<Instruction>(*UI));
Chris Lattner260ab202002-04-18 17:39:14 +0000113 }
114
Chris Lattner51ea1272004-02-28 05:22:00 +0000115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
117 ///
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000121 AddToWorkList(Op);
Chris Lattner51ea1272004-02-28 05:22:00 +0000122 }
Chris Lattner2deeaea2006-10-05 06:55:50 +0000123
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
127 ///
128 /// Return the specified operand before it is turned into an undef.
129 ///
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
132
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000135 AddToWorkList(Op);
Chris Lattner2deeaea2006-10-05 06:55:50 +0000136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
138 }
139
140 return R;
141 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000142
Chris Lattner260ab202002-04-18 17:39:14 +0000143 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 virtual bool runOnFunction(Function &F);
Chris Lattner960a5432007-03-03 02:04:50 +0000145
146 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattner260ab202002-04-18 17:39:14 +0000147
Chris Lattnerf12cc842002-04-28 21:27:06 +0000148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000149 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000150 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000151 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000152 }
153
Chris Lattner69193f92004-04-05 01:30:19 +0000154 TargetData &getTargetData() const { return *TD; }
155
Chris Lattner260ab202002-04-18 17:39:14 +0000156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
158 // Return Value:
159 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000160 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000161 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
Reid Spencer2341c222007-02-02 02:16:23 +0000179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000186
Reid Spencer266e42b2006-12-23 06:05:41 +0000187 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
193 Instruction *visitTrunc(CastInst &CI);
194 Instruction *visitZExt(CastInst &CI);
195 Instruction *visitSExt(CastInst &CI);
196 Instruction *visitFPTrunc(CastInst &CI);
197 Instruction *visitFPExt(CastInst &CI);
198 Instruction *visitFPToUI(CastInst &CI);
199 Instruction *visitFPToSI(CastInst &CI);
200 Instruction *visitUIToFP(CastInst &CI);
201 Instruction *visitSIToFP(CastInst &CI);
202 Instruction *visitPtrToInt(CastInst &CI);
203 Instruction *visitIntToPtr(CastInst &CI);
204 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000205 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000207 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000208 Instruction *visitCallInst(CallInst &CI);
209 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000210 Instruction *visitPHINode(PHINode &PN);
211 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000212 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000213 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000214 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000215 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000216 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000217 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000218 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000219 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000220 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000221
222 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000223 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000224
Chris Lattner970c33a2003-06-19 17:00:31 +0000225 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000226 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000227 bool transformConstExprCastCall(CallSite CS);
228
Chris Lattner69193f92004-04-05 01:30:19 +0000229 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000230 // InsertNewInstBefore - insert an instruction New before instruction Old
231 // in the program. Add the new instruction to the worklist.
232 //
Chris Lattner623826c2004-09-28 21:48:02 +0000233 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000234 assert(New && New->getParent() == 0 &&
235 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 BasicBlock *BB = Old.getParent();
237 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000238 AddToWorkList(New);
Chris Lattnere79e8542004-02-23 06:38:22 +0000239 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000240 }
241
Chris Lattner7e794272004-09-24 15:21:34 +0000242 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243 /// This also adds the cast to the worklist. Finally, this returns the
244 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000245 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000247 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000248
Chris Lattnere79d2492006-04-06 19:19:17 +0000249 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000250 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000251
Reid Spencer13bc5d72006-12-12 09:18:51 +0000252 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000253 AddToWorkList(C);
Chris Lattner7e794272004-09-24 15:21:34 +0000254 return C;
255 }
256
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000265 if (&I != V) {
266 I.replaceAllUsesWith(V);
267 return &I;
268 } else {
269 // If we are replacing the instruction with itself, this must be in a
270 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000271 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000272 return &I;
273 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000274 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000275
Chris Lattner2590e512006-02-07 06:56:34 +0000276 // UpdateValueUsesWith - This method is to be used when an value is
277 // found to be replacable with another preexisting expression or was
278 // updated. Here we add all uses of I to the worklist, replace all uses of
279 // I with the new value (unless the instruction was just updated), then
280 // return true, so that the inst combiner will know that I was modified.
281 //
282 bool UpdateValueUsesWith(Value *Old, Value *New) {
283 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
284 if (Old != New)
285 Old->replaceAllUsesWith(New);
286 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000287 AddToWorkList(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000288 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000289 AddToWorkList(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000290 return true;
291 }
292
Chris Lattner51ea1272004-02-28 05:22:00 +0000293 // EraseInstFromFunction - When dealing with an instruction that has side
294 // effects or produces a void value, we can't rely on DCE to delete the
295 // instruction. Instead, visit methods should return the value returned by
296 // this function.
297 Instruction *EraseInstFromFunction(Instruction &I) {
298 assert(I.use_empty() && "Cannot erase instruction that is used!");
299 AddUsesToWorkList(I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000300 RemoveFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000301 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000302 return 0; // Don't do anything with FI
303 }
304
Chris Lattner3ac7c262003-08-13 20:16:26 +0000305 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000306 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307 /// InsertBefore instruction. This is specialized a bit to avoid inserting
308 /// casts that are known to not do anything...
309 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000310 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000312 Instruction *InsertBefore);
313
Reid Spencer266e42b2006-12-23 06:05:41 +0000314 /// SimplifyCommutative - This performs a few simplifications for
315 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000317
Reid Spencer266e42b2006-12-23 06:05:41 +0000318 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319 /// most-complex to least-complex order.
320 bool SimplifyCompare(CmpInst &I);
321
Chris Lattner0157e7f2006-02-11 09:31:47 +0000322 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
323 uint64_t &KnownZero, uint64_t &KnownOne,
324 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000325
Chris Lattner2deeaea2006-10-05 06:55:50 +0000326 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
327 uint64_t &UndefElts, unsigned Depth = 0);
328
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000329 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
330 // PHI node as operand #0, see if we can fold the instruction into the PHI
331 // (which is only possible if all operands to the PHI are constants).
332 Instruction *FoldOpIntoPhi(Instruction &I);
333
Chris Lattner7515cab2004-11-14 19:13:23 +0000334 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
335 // operator and they all are only used by the PHI, PHI together their
336 // inputs, and do the operation once, to the result of the PHI.
337 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000338 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
339
340
Zhou Sheng75b871f2007-01-11 12:24:14 +0000341 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
342 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000343
Zhou Sheng75b871f2007-01-11 12:24:14 +0000344 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000345 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000346 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000347 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000348 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000349 Instruction *MatchBSwap(BinaryOperator &I);
350
Reid Spencer74a528b2006-12-13 18:21:21 +0000351 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000352 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000353
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000354 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000355}
356
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000357// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000358// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000359static unsigned getComplexity(Value *V) {
360 if (isa<Instruction>(V)) {
361 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000362 return 3;
363 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000364 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000365 if (isa<Argument>(V)) return 3;
366 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000367}
Chris Lattner260ab202002-04-18 17:39:14 +0000368
Chris Lattner7fb29e12003-03-11 00:12:48 +0000369// isOnlyUse - Return true if this instruction will be deleted if we stop using
370// it.
371static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000372 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000373}
374
Chris Lattnere79e8542004-02-23 06:38:22 +0000375// getPromotedType - Return the specified type promoted as it would be to pass
376// though a va_arg area...
377static const Type *getPromotedType(const Type *Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000378 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
379 if (ITy->getBitWidth() < 32)
380 return Type::Int32Ty;
381 } else if (Ty == Type::FloatTy)
382 return Type::DoubleTy;
383 return Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000384}
385
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000386/// getBitCastOperand - If the specified operand is a CastInst or a constant
387/// expression bitcast, return the operand value, otherwise return null.
388static Value *getBitCastOperand(Value *V) {
389 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000390 return I->getOperand(0);
391 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000393 return CE->getOperand(0);
394 return 0;
395}
396
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000397/// This function is a wrapper around CastInst::isEliminableCastPair. It
398/// simply extracts arguments and returns what that function returns.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000399static Instruction::CastOps
400isEliminableCastPair(
401 const CastInst *CI, ///< The first cast instruction
402 unsigned opcode, ///< The opcode of the second cast instruction
403 const Type *DstTy, ///< The target type for the second cast instruction
404 TargetData *TD ///< The target data for pointer size
405) {
406
407 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
408 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000410 // Get the opcodes of the two Cast instructions
411 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
412 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000413
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000414 return Instruction::CastOps(
415 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
416 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000417}
418
419/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
420/// in any code being generated. It does not require codegen if V is simple
421/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000422static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
423 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000424 if (V->getType() == Ty || isa<Constant>(V)) return false;
425
Chris Lattner99155be2006-05-25 23:24:33 +0000426 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000427 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000428 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000429 return false;
430 return true;
431}
432
433/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
434/// InsertBefore instruction. This is specialized a bit to avoid inserting
435/// casts that are known to not do anything...
436///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000437Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
438 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000439 Instruction *InsertBefore) {
440 if (V->getType() == DestTy) return V;
441 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000442 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443
Reid Spencer13bc5d72006-12-12 09:18:51 +0000444 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000445}
446
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000447// SimplifyCommutative - This performs a few simplifications for commutative
448// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000449//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000450// 1. Order operands such that they are listed from right (least complex) to
451// left (most complex). This puts constants before unary operators before
452// binary operators.
453//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000454// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
455// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000457bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 bool Changed = false;
459 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
460 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000462 if (!I.isAssociative()) return Changed;
463 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
465 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
466 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000467 Constant *Folded = ConstantExpr::get(I.getOpcode(),
468 cast<Constant>(I.getOperand(1)),
469 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000470 I.setOperand(0, Op->getOperand(0));
471 I.setOperand(1, Folded);
472 return true;
473 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
474 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
475 isOnlyUse(Op) && isOnlyUse(Op1)) {
476 Constant *C1 = cast<Constant>(Op->getOperand(1));
477 Constant *C2 = cast<Constant>(Op1->getOperand(1));
478
479 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000480 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000481 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
482 Op1->getOperand(0),
483 Op1->getName(), &I);
Chris Lattnerb15e2b12007-03-02 21:28:56 +0000484 AddToWorkList(New);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000485 I.setOperand(0, New);
486 I.setOperand(1, Folded);
487 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000488 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000489 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000490 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000491}
Chris Lattnerca081252001-12-14 16:52:21 +0000492
Reid Spencer266e42b2006-12-23 06:05:41 +0000493/// SimplifyCompare - For a CmpInst this function just orders the operands
494/// so that theyare listed from right (least complex) to left (most complex).
495/// This puts constants before unary operators before binary operators.
496bool InstCombiner::SimplifyCompare(CmpInst &I) {
497 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
498 return false;
499 I.swapOperands();
500 // Compare instructions are not associative so there's nothing else we can do.
501 return true;
502}
503
Chris Lattnerbb74e222003-03-10 23:06:50 +0000504// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
505// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000506//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000507static inline Value *dyn_castNegVal(Value *V) {
508 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000509 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000510
Chris Lattner9ad0d552004-12-14 20:08:06 +0000511 // Constants can be considered to be negated values if they can be folded.
512 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
513 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000515}
516
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517static inline Value *dyn_castNotVal(Value *V) {
518 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000519 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000520
521 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000522 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000523 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524 return 0;
525}
526
Chris Lattner7fb29e12003-03-11 00:12:48 +0000527// dyn_castFoldableMul - If this value is a multiply that can be folded into
528// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000529// non-constant operand of the multiply, and set CST to point to the multiplier.
530// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000532static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner03c49532007-01-15 02:27:26 +0000533 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000534 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000535 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000536 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000537 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000538 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000539 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540 // The multiplier is really 1 << CST.
541 Constant *One = ConstantInt::get(V->getType(), 1);
542 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
543 return I->getOperand(0);
544 }
545 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000547}
Chris Lattner31ae8632002-08-14 17:51:49 +0000548
Chris Lattner0798af32005-01-13 20:14:25 +0000549/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
550/// expression, return it.
551static User *dyn_castGetElementPtr(Value *V) {
552 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
553 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
554 if (CE->getOpcode() == Instruction::GetElementPtr)
555 return cast<User>(V);
556 return false;
557}
558
Chris Lattner623826c2004-09-28 21:48:02 +0000559// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000560static ConstantInt *AddOne(ConstantInt *C) {
561 return cast<ConstantInt>(ConstantExpr::getAdd(C,
562 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000563}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000564static ConstantInt *SubOne(ConstantInt *C) {
565 return cast<ConstantInt>(ConstantExpr::getSub(C,
566 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000567}
568
Chris Lattner4534dd592006-02-09 07:38:58 +0000569/// ComputeMaskedBits - Determine which of the bits specified in Mask are
570/// known to be either zero or one and return them in the KnownZero/KnownOne
571/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
572/// processing.
573static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
574 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000575 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
576 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000577 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000578 // optimized based on the contradictory assumption that it is non-zero.
579 // Because instcombine aggressively folds operations with undef args anyway,
580 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000581 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000582 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000583 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000584 KnownZero = ~KnownOne & Mask;
585 return;
586 }
587
588 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000589 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000590 return; // Limit search depth.
591
592 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000593 Instruction *I = dyn_cast<Instruction>(V);
594 if (!I) return;
595
Reid Spencera94d3942007-01-19 21:13:56 +0000596 Mask &= cast<IntegerType>(V->getType())->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000597
Chris Lattner0157e7f2006-02-11 09:31:47 +0000598 switch (I->getOpcode()) {
599 case Instruction::And:
600 // If either the LHS or the RHS are Zero, the result is zero.
601 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
602 Mask &= ~KnownZero;
603 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
604 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
605 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
606
607 // Output known-1 bits are only known if set in both the LHS & RHS.
608 KnownOne &= KnownOne2;
609 // Output known-0 are known to be clear if zero in either the LHS | RHS.
610 KnownZero |= KnownZero2;
611 return;
612 case Instruction::Or:
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 Mask &= ~KnownOne;
615 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
616 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
617 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618
619 // Output known-0 bits are only known if clear in both the LHS & RHS.
620 KnownZero &= KnownZero2;
621 // Output known-1 are known to be set if set in either the LHS | RHS.
622 KnownOne |= KnownOne2;
623 return;
624 case Instruction::Xor: {
625 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
626 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629
630 // Output known-0 bits are known if clear or set in both the LHS & RHS.
631 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
632 // Output known-1 are known to be set if set in only one of the LHS, RHS.
633 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
634 KnownZero = KnownZeroOut;
635 return;
636 }
637 case Instruction::Select:
638 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
639 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
640 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
641 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642
643 // Only known if known in both the LHS and RHS.
644 KnownOne &= KnownOne2;
645 KnownZero &= KnownZero2;
646 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 case Instruction::FPTrunc:
648 case Instruction::FPExt:
649 case Instruction::FPToUI:
650 case Instruction::FPToSI:
651 case Instruction::SIToFP:
652 case Instruction::PtrToInt:
653 case Instruction::UIToFP:
654 case Instruction::IntToPtr:
655 return; // Can't work with floating point or pointers
656 case Instruction::Trunc:
657 // All these have integer operands
658 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
659 return;
660 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000661 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +0000662 if (SrcTy->isInteger()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000663 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000664 return;
665 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000666 break;
667 }
668 case Instruction::ZExt: {
669 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000670 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
671 uint64_t NotIn = ~SrcTy->getBitMask();
672 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000673
Reid Spencera94d3942007-01-19 21:13:56 +0000674 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
676 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
677 // The top bits are known to be zero.
678 KnownZero |= NewBits;
679 return;
680 }
681 case Instruction::SExt: {
682 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +0000683 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
684 uint64_t NotIn = ~SrcTy->getBitMask();
685 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000686
Reid Spencera94d3942007-01-19 21:13:56 +0000687 Mask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000688 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
689 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000690
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000691 // If the sign bit of the input is known set or clear, then we know the
692 // top bits of the result.
693 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
694 if (KnownZero & InSignBit) { // Input sign bit known zero
695 KnownZero |= NewBits;
696 KnownOne &= ~NewBits;
697 } else if (KnownOne & InSignBit) { // Input sign bit known set
698 KnownOne |= NewBits;
699 KnownZero &= ~NewBits;
700 } else { // Input sign bit unknown
701 KnownZero &= ~NewBits;
702 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000703 }
704 return;
705 }
706 case Instruction::Shl:
707 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000708 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709 uint64_t ShiftAmt = SA->getZExtValue();
710 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000711 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
712 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000713 KnownZero <<= ShiftAmt;
714 KnownOne <<= ShiftAmt;
715 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000716 return;
717 }
718 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000719 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000721 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000723 uint64_t ShiftAmt = SA->getZExtValue();
724 uint64_t HighBits = (1ULL << ShiftAmt)-1;
725 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000726
Reid Spencerfdff9382006-11-08 06:47:33 +0000727 // Unsigned shift right.
728 Mask <<= ShiftAmt;
729 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
730 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
731 KnownZero >>= ShiftAmt;
732 KnownOne >>= ShiftAmt;
733 KnownZero |= HighBits; // high bits known zero.
734 return;
735 }
736 break;
737 case Instruction::AShr:
738 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
739 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
740 // Compute the new bits that are at the top now.
741 uint64_t ShiftAmt = SA->getZExtValue();
742 uint64_t HighBits = (1ULL << ShiftAmt)-1;
743 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
744
745 // Signed shift right.
746 Mask <<= ShiftAmt;
747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
749 KnownZero >>= ShiftAmt;
750 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751
Reid Spencerfdff9382006-11-08 06:47:33 +0000752 // Handle the sign bits.
753 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
754 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755
Reid Spencerfdff9382006-11-08 06:47:33 +0000756 if (KnownZero & SignBit) { // New bits are known zero.
757 KnownZero |= HighBits;
758 } else if (KnownOne & SignBit) { // New bits are known one.
759 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000760 }
761 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000762 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000763 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000764 }
Chris Lattner92a68652006-02-07 08:05:22 +0000765}
766
767/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
768/// this predicate to simplify operations downstream. Mask is known to be zero
769/// for bits that V cannot have.
770static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000771 uint64_t KnownZero, KnownOne;
772 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
773 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
774 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000775}
776
Chris Lattner0157e7f2006-02-11 09:31:47 +0000777/// ShrinkDemandedConstant - Check to see if the specified operand of the
778/// specified instruction is a constant integer. If so, check to see if there
779/// are any bits set in the constant that are not demanded. If so, shrink the
780/// constant and return true.
781static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
782 uint64_t Demanded) {
783 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
784 if (!OpC) return false;
785
786 // If there are no bits set that aren't demanded, nothing to do.
787 if ((~Demanded & OpC->getZExtValue()) == 0)
788 return false;
789
790 // This is producing any bits that are not needed, shrink the RHS.
791 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000792 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000793 return true;
794}
795
Chris Lattneree0f2802006-02-12 02:07:56 +0000796// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
797// set of known zero and one bits, compute the maximum and minimum values that
798// could have the specified known zero and known one bits, returning them in
799// min/max.
800static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
801 uint64_t KnownZero,
802 uint64_t KnownOne,
803 int64_t &Min, int64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000804 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000805 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
806
807 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
808
809 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
810 // bit if it is unknown.
811 Min = KnownOne;
812 Max = KnownOne|UnknownBits;
813
814 if (SignBit & UnknownBits) { // Sign bit is unknown
815 Min |= SignBit;
816 Max &= ~SignBit;
817 }
818
819 // Sign extend the min/max values.
820 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
821 Min = (Min << ShAmt) >> ShAmt;
822 Max = (Max << ShAmt) >> ShAmt;
823}
824
825// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
826// a set of known zero and one bits, compute the maximum and minimum values that
827// could have the specified known zero and known one bits, returning them in
828// min/max.
829static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
830 uint64_t KnownZero,
831 uint64_t KnownOne,
832 uint64_t &Min,
833 uint64_t &Max) {
Reid Spencera94d3942007-01-19 21:13:56 +0000834 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
Chris Lattneree0f2802006-02-12 02:07:56 +0000835 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
836
837 // The minimum value is when the unknown bits are all zeros.
838 Min = KnownOne;
839 // The maximum value is when the unknown bits are all ones.
840 Max = KnownOne|UnknownBits;
841}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000842
843
844/// SimplifyDemandedBits - Look at V. At this point, we know that only the
845/// DemandedMask bits of the result of V are ever used downstream. If we can
846/// use this information to simplify V, do so and return true. Otherwise,
847/// analyze the expression and return a mask of KnownOne and KnownZero bits for
848/// the expression (used to simplify the caller). The KnownZero/One bits may
849/// only be accurate for those bits in the DemandedMask.
850bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
851 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000852 unsigned Depth) {
Chris Lattnerab2f9132007-03-04 23:16:36 +0000853 const IntegerType *VTy = cast<IntegerType>(V->getType());
Zhou Sheng75b871f2007-01-11 12:24:14 +0000854 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000855 // We know all of the bits for a constant!
856 KnownOne = CI->getZExtValue() & DemandedMask;
857 KnownZero = ~KnownOne & DemandedMask;
858 return false;
859 }
860
861 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000863 if (Depth != 0) { // Not at the root.
864 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
865 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000866 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 }
Chris Lattner2590e512006-02-07 06:56:34 +0000868 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000869 // just set the DemandedMask to all bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +0000870 DemandedMask = VTy->getBitMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000871 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattnerab2f9132007-03-04 23:16:36 +0000872 if (V != UndefValue::get(VTy))
873 return UpdateValueUsesWith(V, UndefValue::get(VTy));
Chris Lattner92a68652006-02-07 08:05:22 +0000874 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000875 } else if (Depth == 6) { // Limit search depth.
876 return false;
877 }
878
879 Instruction *I = dyn_cast<Instruction>(V);
880 if (!I) return false; // Only analyze instructions.
881
Chris Lattnerab2f9132007-03-04 23:16:36 +0000882 DemandedMask &= VTy->getBitMask();
Chris Lattnerfb296922006-05-04 17:33:35 +0000883
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000884 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000885 switch (I->getOpcode()) {
886 default: break;
887 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000888 // If either the LHS or the RHS are Zero, the result is zero.
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
891 return true;
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893
894 // If something is known zero on the RHS, the bits aren't demanded on the
895 // LHS.
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
897 KnownZero2, KnownOne2, Depth+1))
898 return true;
899 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000901 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 // These bits cannot contribute to the result of the 'and'.
903 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
904 return UpdateValueUsesWith(I, I->getOperand(0));
905 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
906 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +0000910 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000911
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000913 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914 return UpdateValueUsesWith(I, I);
915
916 // Output known-1 bits are only known if set in both the LHS & RHS.
917 KnownOne &= KnownOne2;
918 // Output known-0 are known to be clear if zero in either the LHS | RHS.
919 KnownZero |= KnownZero2;
920 break;
921 case Instruction::Or:
922 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
923 KnownZero, KnownOne, Depth+1))
924 return true;
925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
927 KnownZero2, KnownOne2, Depth+1))
928 return true;
929 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930
931 // If all of the demanded bits are known zero on one side, return the other.
932 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000933 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000935 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000936 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000937
938 // If all of the potentially set bits on one side are known to be set on
939 // the other side, just use the 'other' side.
940 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
941 (DemandedMask & (~KnownZero)))
942 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000943 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
944 (DemandedMask & (~KnownZero2)))
945 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000946
947 // If the RHS is a constant, see if we can simplify it.
948 if (ShrinkDemandedConstant(I, 1, DemandedMask))
949 return UpdateValueUsesWith(I, I);
950
951 // Output known-0 bits are only known if clear in both the LHS & RHS.
952 KnownZero &= KnownZero2;
953 // Output known-1 are known to be set if set in either the LHS | RHS.
954 KnownOne |= KnownOne2;
955 break;
956 case Instruction::Xor: {
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 KnownZero, KnownOne, Depth+1))
959 return true;
960 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
961 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
962 KnownZero2, KnownOne2, Depth+1))
963 return true;
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965
966 // If all of the demanded bits are known zero on one side, return the other.
967 // These bits cannot contribute to the result of the 'xor'.
968 if ((DemandedMask & KnownZero) == DemandedMask)
969 return UpdateValueUsesWith(I, I->getOperand(0));
970 if ((DemandedMask & KnownZero2) == DemandedMask)
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // Output known-0 bits are known if clear or set in both the LHS & RHS.
974 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
975 // Output known-1 are known to be set if set in only one of the LHS, RHS.
976 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
977
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000978 // If all of the demanded bits are known to be zero on one side or the
979 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000980 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000981 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
982 Instruction *Or =
983 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
984 I->getName());
985 InsertNewInstBefore(Or, *I);
986 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000987 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000988
Chris Lattner5b2edb12006-02-12 08:02:11 +0000989 // If all of the demanded bits on one side are known, and all of the set
990 // bits on that side are also known to be set on the other side, turn this
991 // into an AND, as we know the bits will be cleared.
992 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
993 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
994 if ((KnownOne & KnownOne2) == KnownOne) {
Chris Lattnerab2f9132007-03-04 23:16:36 +0000995 Constant *AndC = ConstantInt::get(VTy, ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000996 Instruction *And =
997 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
998 InsertNewInstBefore(And, *I);
999 return UpdateValueUsesWith(I, And);
1000 }
1001 }
1002
Chris Lattner0157e7f2006-02-11 09:31:47 +00001003 // If the RHS is a constant, see if we can simplify it.
1004 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1005 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006 return UpdateValueUsesWith(I, I);
1007
1008 KnownZero = KnownZeroOut;
1009 KnownOne = KnownOneOut;
1010 break;
1011 }
1012 case Instruction::Select:
1013 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1014 KnownZero, KnownOne, Depth+1))
1015 return true;
1016 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1017 KnownZero2, KnownOne2, Depth+1))
1018 return true;
1019 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1020 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1021
1022 // If the operands are constants, see if we can simplify them.
1023 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024 return UpdateValueUsesWith(I, I);
1025 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1026 return UpdateValueUsesWith(I, I);
1027
1028 // Only known if known in both the LHS and RHS.
1029 KnownOne &= KnownOne2;
1030 KnownZero &= KnownZero2;
1031 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001032 case Instruction::Trunc:
1033 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1034 KnownZero, KnownOne, Depth+1))
1035 return true;
1036 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1037 break;
1038 case Instruction::BitCast:
Chris Lattner03c49532007-01-15 02:27:26 +00001039 if (!I->getOperand(0)->getType()->isInteger())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001040 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001041
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001042 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1046 break;
1047 case Instruction::ZExt: {
1048 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001049 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1050 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001051 uint64_t NewBits = VTy->getBitMask() & NotIn;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001052
Reid Spencera94d3942007-01-19 21:13:56 +00001053 DemandedMask &= SrcTy->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001054 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1055 KnownZero, KnownOne, Depth+1))
1056 return true;
1057 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1058 // The top bits are known to be zero.
1059 KnownZero |= NewBits;
1060 break;
1061 }
1062 case Instruction::SExt: {
1063 // Compute the bits in the result that are not present in the input.
Reid Spencera94d3942007-01-19 21:13:56 +00001064 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1065 uint64_t NotIn = ~SrcTy->getBitMask();
Chris Lattnerab2f9132007-03-04 23:16:36 +00001066 uint64_t NewBits = VTy->getBitMask() & NotIn;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001067
1068 // Get the sign bit for the source type
1069 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001070 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001071
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001072 // If any of the sign extended bits are demanded, we know that the sign
1073 // bit is demanded.
1074 if (NewBits & DemandedMask)
1075 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001076
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001077 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001081
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001082 // If the sign bit of the input is known set or clear, then we know the
1083 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001084
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001085 // If the input sign bit is known zero, or if the NewBits are not demanded
1086 // convert this into a zero extension.
1087 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1088 // Convert to ZExt cast
Chris Lattnerab2f9132007-03-04 23:16:36 +00001089 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001090 return UpdateValueUsesWith(I, NewCast);
1091 } else if (KnownOne & InSignBit) { // Input sign bit known set
1092 KnownOne |= NewBits;
1093 KnownZero &= ~NewBits;
1094 } else { // Input sign bit unknown
1095 KnownZero &= ~NewBits;
1096 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001097 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001098 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001099 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001100 case Instruction::Add:
1101 // If there is a constant on the RHS, there are a variety of xformations
1102 // we can do.
1103 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1104 // If null, this should be simplified elsewhere. Some of the xforms here
1105 // won't work if the RHS is zero.
1106 if (RHS->isNullValue())
1107 break;
1108
1109 // Figure out what the input bits are. If the top bits of the and result
1110 // are not demanded, then the add doesn't demand them from its input
1111 // either.
1112
1113 // Shift the demanded mask up so that it's at the top of the uint64_t.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001114 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001115 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1116
1117 // If the top bit of the output is demanded, demand everything from the
1118 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001119 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001120
1121 // Find information about known zero/one bits in the input.
1122 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1123 KnownZero2, KnownOne2, Depth+1))
1124 return true;
1125
1126 // If the RHS of the add has bits set that can't affect the input, reduce
1127 // the constant.
1128 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1129 return UpdateValueUsesWith(I, I);
1130
1131 // Avoid excess work.
1132 if (KnownZero2 == 0 && KnownOne2 == 0)
1133 break;
1134
1135 // Turn it into OR if input bits are zero.
1136 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1137 Instruction *Or =
1138 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1139 I->getName());
1140 InsertNewInstBefore(Or, *I);
1141 return UpdateValueUsesWith(I, Or);
1142 }
1143
1144 // We can say something about the output known-zero and known-one bits,
1145 // depending on potential carries from the input constant and the
1146 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1147 // bits set and the RHS constant is 0x01001, then we know we have a known
1148 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1149
1150 // To compute this, we first compute the potential carry bits. These are
1151 // the bits which may be modified. I'm not aware of a better way to do
1152 // this scan.
1153 uint64_t RHSVal = RHS->getZExtValue();
1154
1155 bool CarryIn = false;
1156 uint64_t CarryBits = 0;
1157 uint64_t CurBit = 1;
1158 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1159 // Record the current carry in.
1160 if (CarryIn) CarryBits |= CurBit;
1161
1162 bool CarryOut;
1163
1164 // This bit has a carry out unless it is "zero + zero" or
1165 // "zero + anything" with no carry in.
1166 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1167 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1168 } else if (!CarryIn &&
1169 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1170 CarryOut = false; // 0 + anything has no carry out if no carry in.
1171 } else {
1172 // Otherwise, we have to assume we have a carry out.
1173 CarryOut = true;
1174 }
1175
1176 // This stage's carry out becomes the next stage's carry-in.
1177 CarryIn = CarryOut;
1178 }
1179
1180 // Now that we know which bits have carries, compute the known-1/0 sets.
1181
1182 // Bits are known one if they are known zero in one operand and one in the
1183 // other, and there is no input carry.
1184 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1185
1186 // Bits are known zero if they are known zero in both operands and there
1187 // is no input carry.
1188 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1189 }
1190 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001191 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001192 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1193 uint64_t ShiftAmt = SA->getZExtValue();
1194 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001195 KnownZero, KnownOne, Depth+1))
1196 return true;
1197 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001198 KnownZero <<= ShiftAmt;
1199 KnownOne <<= ShiftAmt;
1200 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001201 }
Chris Lattner2590e512006-02-07 06:56:34 +00001202 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001203 case Instruction::LShr:
1204 // For a logical shift right
1205 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1206 unsigned ShiftAmt = SA->getZExtValue();
1207
1208 // Compute the new bits that are at the top now.
1209 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001210 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1211 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001212 // Unsigned shift right.
1213 if (SimplifyDemandedBits(I->getOperand(0),
1214 (DemandedMask << ShiftAmt) & TypeMask,
1215 KnownZero, KnownOne, Depth+1))
1216 return true;
1217 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1218 KnownZero &= TypeMask;
1219 KnownOne &= TypeMask;
1220 KnownZero >>= ShiftAmt;
1221 KnownOne >>= ShiftAmt;
1222 KnownZero |= HighBits; // high bits known zero.
1223 }
1224 break;
1225 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001226 // If this is an arithmetic shift right and only the low-bit is set, we can
1227 // always convert this into a logical shr, even if the shift amount is
1228 // variable. The low bit of the shift cannot be an input sign bit unless
1229 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001230 if (DemandedMask == 1) {
1231 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001232 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001233 I->getOperand(0), I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001234 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001235 return UpdateValueUsesWith(I, NewVal);
1236 }
1237
Reid Spencere0fc4df2006-10-20 07:07:24 +00001238 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1239 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001240
1241 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001242 uint64_t HighBits = (1ULL << ShiftAmt)-1;
Chris Lattnerab2f9132007-03-04 23:16:36 +00001243 HighBits <<= VTy->getBitWidth() - ShiftAmt;
1244 uint64_t TypeMask = VTy->getBitMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001245 // Signed shift right.
1246 if (SimplifyDemandedBits(I->getOperand(0),
1247 (DemandedMask << ShiftAmt) & TypeMask,
1248 KnownZero, KnownOne, Depth+1))
1249 return true;
1250 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1251 KnownZero &= TypeMask;
1252 KnownOne &= TypeMask;
1253 KnownZero >>= ShiftAmt;
1254 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001255
Reid Spencerfdff9382006-11-08 06:47:33 +00001256 // Handle the sign bits.
Chris Lattnerab2f9132007-03-04 23:16:36 +00001257 uint64_t SignBit = 1ULL << (VTy->getBitWidth()-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00001258 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001259
Reid Spencerfdff9382006-11-08 06:47:33 +00001260 // If the input sign bit is known to be zero, or if none of the top bits
1261 // are demanded, turn this into an unsigned shift right.
1262 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1263 // Perform the logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00001264 Value *NewVal = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00001265 I->getOperand(0), SA, I->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00001266 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1267 return UpdateValueUsesWith(I, NewVal);
1268 } else if (KnownOne & SignBit) { // New bits are known one.
1269 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001270 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001271 }
Chris Lattner2590e512006-02-07 06:56:34 +00001272 break;
1273 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001274
1275 // If the client is only demanding bits that we know, return the known
1276 // constant.
1277 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Chris Lattnerab2f9132007-03-04 23:16:36 +00001278 return UpdateValueUsesWith(I, ConstantInt::get(VTy, KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001279 return false;
1280}
1281
Chris Lattner2deeaea2006-10-05 06:55:50 +00001282
1283/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1284/// 64 or fewer elements. DemandedElts contains the set of elements that are
1285/// actually used by the caller. This method analyzes which elements of the
1286/// operand are undef and returns that information in UndefElts.
1287///
1288/// If the information about demanded elements can be used to simplify the
1289/// operation, the operation is simplified, then the resultant value is
1290/// returned. This returns null if no change was made.
1291Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1292 uint64_t &UndefElts,
1293 unsigned Depth) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001294 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001295 assert(VWidth <= 64 && "Vector too wide to analyze!");
1296 uint64_t EltMask = ~0ULL >> (64-VWidth);
1297 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1298 "Invalid DemandedElts!");
1299
1300 if (isa<UndefValue>(V)) {
1301 // If the entire vector is undefined, just return this info.
1302 UndefElts = EltMask;
1303 return 0;
1304 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1305 UndefElts = EltMask;
1306 return UndefValue::get(V->getType());
1307 }
1308
1309 UndefElts = 0;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001310 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1311 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001312 Constant *Undef = UndefValue::get(EltTy);
1313
1314 std::vector<Constant*> Elts;
1315 for (unsigned i = 0; i != VWidth; ++i)
1316 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1317 Elts.push_back(Undef);
1318 UndefElts |= (1ULL << i);
1319 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1320 Elts.push_back(Undef);
1321 UndefElts |= (1ULL << i);
1322 } else { // Otherwise, defined.
1323 Elts.push_back(CP->getOperand(i));
1324 }
1325
1326 // If we changed the constant, return it.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001327 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001328 return NewCP != CP ? NewCP : 0;
1329 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001330 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner2deeaea2006-10-05 06:55:50 +00001331 // set to undef.
Reid Spencerd84d35b2007-02-15 02:26:10 +00001332 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001333 Constant *Zero = Constant::getNullValue(EltTy);
1334 Constant *Undef = UndefValue::get(EltTy);
1335 std::vector<Constant*> Elts;
1336 for (unsigned i = 0; i != VWidth; ++i)
1337 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1338 UndefElts = DemandedElts ^ EltMask;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001339 return ConstantVector::get(Elts);
Chris Lattner2deeaea2006-10-05 06:55:50 +00001340 }
1341
1342 if (!V->hasOneUse()) { // Other users may use these bits.
1343 if (Depth != 0) { // Not at the root.
1344 // TODO: Just compute the UndefElts information recursively.
1345 return false;
1346 }
1347 return false;
1348 } else if (Depth == 10) { // Limit search depth.
1349 return false;
1350 }
1351
1352 Instruction *I = dyn_cast<Instruction>(V);
1353 if (!I) return false; // Only analyze instructions.
1354
1355 bool MadeChange = false;
1356 uint64_t UndefElts2;
1357 Value *TmpV;
1358 switch (I->getOpcode()) {
1359 default: break;
1360
1361 case Instruction::InsertElement: {
1362 // If this is a variable index, we don't know which element it overwrites.
1363 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001364 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001365 if (Idx == 0) {
1366 // Note that we can't propagate undef elt info, because we don't know
1367 // which elt is getting updated.
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1369 UndefElts2, Depth+1);
1370 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1371 break;
1372 }
1373
1374 // If this is inserting an element that isn't demanded, remove this
1375 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001376 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001377 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1378 return AddSoonDeadInstToWorklist(*I, 0);
1379
1380 // Otherwise, the element inserted overwrites whatever was there, so the
1381 // input demanded set is simpler than the output set.
1382 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1383 DemandedElts & ~(1ULL << IdxNo),
1384 UndefElts, Depth+1);
1385 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1386
1387 // The inserted element is defined.
1388 UndefElts |= 1ULL << IdxNo;
1389 break;
1390 }
1391
1392 case Instruction::And:
1393 case Instruction::Or:
1394 case Instruction::Xor:
1395 case Instruction::Add:
1396 case Instruction::Sub:
1397 case Instruction::Mul:
1398 // div/rem demand all inputs, because they don't want divide by zero.
1399 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1400 UndefElts, Depth+1);
1401 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1403 UndefElts2, Depth+1);
1404 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1405
1406 // Output elements are undefined if both are undefined. Consider things
1407 // like undef&0. The result is known zero, not undef.
1408 UndefElts &= UndefElts2;
1409 break;
1410
1411 case Instruction::Call: {
1412 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1413 if (!II) break;
1414 switch (II->getIntrinsicID()) {
1415 default: break;
1416
1417 // Binary vector operations that work column-wise. A dest element is a
1418 // function of the corresponding input elements from the two inputs.
1419 case Intrinsic::x86_sse_sub_ss:
1420 case Intrinsic::x86_sse_mul_ss:
1421 case Intrinsic::x86_sse_min_ss:
1422 case Intrinsic::x86_sse_max_ss:
1423 case Intrinsic::x86_sse2_sub_sd:
1424 case Intrinsic::x86_sse2_mul_sd:
1425 case Intrinsic::x86_sse2_min_sd:
1426 case Intrinsic::x86_sse2_max_sd:
1427 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1428 UndefElts, Depth+1);
1429 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1430 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1431 UndefElts2, Depth+1);
1432 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1433
1434 // If only the low elt is demanded and this is a scalarizable intrinsic,
1435 // scalarize it now.
1436 if (DemandedElts == 1) {
1437 switch (II->getIntrinsicID()) {
1438 default: break;
1439 case Intrinsic::x86_sse_sub_ss:
1440 case Intrinsic::x86_sse_mul_ss:
1441 case Intrinsic::x86_sse2_sub_sd:
1442 case Intrinsic::x86_sse2_mul_sd:
1443 // TODO: Lower MIN/MAX/ABS/etc
1444 Value *LHS = II->getOperand(1);
1445 Value *RHS = II->getOperand(2);
1446 // Extract the element as scalars.
1447 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1448 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1449
1450 switch (II->getIntrinsicID()) {
1451 default: assert(0 && "Case stmts out of sync!");
1452 case Intrinsic::x86_sse_sub_ss:
1453 case Intrinsic::x86_sse2_sub_sd:
1454 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1455 II->getName()), *II);
1456 break;
1457 case Intrinsic::x86_sse_mul_ss:
1458 case Intrinsic::x86_sse2_mul_sd:
1459 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1460 II->getName()), *II);
1461 break;
1462 }
1463
1464 Instruction *New =
1465 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1466 II->getName());
1467 InsertNewInstBefore(New, *II);
1468 AddSoonDeadInstToWorklist(*II, 0);
1469 return New;
1470 }
1471 }
1472
1473 // Output elements are undefined if both are undefined. Consider things
1474 // like undef&0. The result is known zero, not undef.
1475 UndefElts &= UndefElts2;
1476 break;
1477 }
1478 break;
1479 }
1480 }
1481 return MadeChange ? I : 0;
1482}
1483
Reid Spencer266e42b2006-12-23 06:05:41 +00001484/// @returns true if the specified compare instruction is
1485/// true when both operands are equal...
1486/// @brief Determine if the ICmpInst returns true if both operands are equal
1487static bool isTrueWhenEqual(ICmpInst &ICI) {
1488 ICmpInst::Predicate pred = ICI.getPredicate();
1489 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1490 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1491 pred == ICmpInst::ICMP_SLE;
1492}
1493
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494/// AssociativeOpt - Perform an optimization on an associative operator. This
1495/// function is designed to check a chain of associative operators for a
1496/// potential to apply a certain optimization. Since the optimization may be
1497/// applicable if the expression was reassociated, this checks the chain, then
1498/// reassociates the expression as necessary to expose the optimization
1499/// opportunity. This makes use of a special Functor, which must define
1500/// 'shouldApply' and 'apply' methods.
1501///
1502template<typename Functor>
1503Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1504 unsigned Opcode = Root.getOpcode();
1505 Value *LHS = Root.getOperand(0);
1506
1507 // Quick check, see if the immediate LHS matches...
1508 if (F.shouldApply(LHS))
1509 return F.apply(Root);
1510
1511 // Otherwise, if the LHS is not of the same opcode as the root, return.
1512 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001513 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001514 // Should we apply this transform to the RHS?
1515 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1516
1517 // If not to the RHS, check to see if we should apply to the LHS...
1518 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1519 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1520 ShouldApply = true;
1521 }
1522
1523 // If the functor wants to apply the optimization to the RHS of LHSI,
1524 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1525 if (ShouldApply) {
1526 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001527
Chris Lattnerb8b97502003-08-13 19:01:45 +00001528 // Now all of the instructions are in the current basic block, go ahead
1529 // and perform the reassociation.
1530 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1531
1532 // First move the selected RHS to the LHS of the root...
1533 Root.setOperand(0, LHSI->getOperand(1));
1534
1535 // Make what used to be the LHS of the root be the user of the root...
1536 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001537 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001538 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1539 return 0;
1540 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001541 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001542 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001543 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1544 BasicBlock::iterator ARI = &Root; ++ARI;
1545 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1546 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001547
1548 // Now propagate the ExtraOperand down the chain of instructions until we
1549 // get to LHSI.
1550 while (TmpLHSI != LHSI) {
1551 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001552 // Move the instruction to immediately before the chain we are
1553 // constructing to avoid breaking dominance properties.
1554 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1555 BB->getInstList().insert(ARI, NextLHSI);
1556 ARI = NextLHSI;
1557
Chris Lattnerb8b97502003-08-13 19:01:45 +00001558 Value *NextOp = NextLHSI->getOperand(1);
1559 NextLHSI->setOperand(1, ExtraOperand);
1560 TmpLHSI = NextLHSI;
1561 ExtraOperand = NextOp;
1562 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001563
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 // Now that the instructions are reassociated, have the functor perform
1565 // the transformation...
1566 return F.apply(Root);
1567 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001568
Chris Lattnerb8b97502003-08-13 19:01:45 +00001569 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1570 }
1571 return 0;
1572}
1573
1574
1575// AddRHS - Implements: X + X --> X << 1
1576struct AddRHS {
1577 Value *RHS;
1578 AddRHS(Value *rhs) : RHS(rhs) {}
1579 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1580 Instruction *apply(BinaryOperator &Add) const {
Reid Spencer0d5f9232007-02-02 14:08:20 +00001581 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer2341c222007-02-02 02:16:23 +00001582 ConstantInt::get(Add.getType(), 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583 }
1584};
1585
1586// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1587// iff C1&C2 == 0
1588struct AddMaskingAnd {
1589 Constant *C2;
1590 AddMaskingAnd(Constant *c) : C2(c) {}
1591 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001592 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001593 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001594 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001595 }
1596 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001597 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001598 }
1599};
1600
Chris Lattner86102b82005-01-01 16:22:27 +00001601static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001602 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001603 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001604 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001605 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001606
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001607 return IC->InsertNewInstBefore(CastInst::create(
1608 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001609 }
1610
Chris Lattner183b3362004-04-09 19:05:30 +00001611 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001612 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1613 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001614
Chris Lattner183b3362004-04-09 19:05:30 +00001615 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1616 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001617 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1618 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001619 }
1620
1621 Value *Op0 = SO, *Op1 = ConstOperand;
1622 if (!ConstIsRHS)
1623 std::swap(Op0, Op1);
1624 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001625 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1626 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001627 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1628 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1629 SO->getName()+".cmp");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001630 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001631 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001632 abort();
1633 }
Chris Lattner86102b82005-01-01 16:22:27 +00001634 return IC->InsertNewInstBefore(New, I);
1635}
1636
1637// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1638// constant as the other operand, try to fold the binary operator into the
1639// select arguments. This also works for Cast instructions, which obviously do
1640// not have a second operand.
1641static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1642 InstCombiner *IC) {
1643 // Don't modify shared select instructions
1644 if (!SI->hasOneUse()) return 0;
1645 Value *TV = SI->getOperand(1);
1646 Value *FV = SI->getOperand(2);
1647
1648 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001649 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001650 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001651
Chris Lattner86102b82005-01-01 16:22:27 +00001652 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1653 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1654
1655 return new SelectInst(SI->getCondition(), SelectTrueVal,
1656 SelectFalseVal);
1657 }
1658 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001659}
1660
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661
1662/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1663/// node as operand #0, see if we can fold the instruction into the PHI (which
1664/// is only possible if all operands to the PHI are constants).
1665Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1666 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001667 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001668 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001669
Chris Lattner04689872006-09-09 22:02:56 +00001670 // Check to see if all of the operands of the PHI are constants. If there is
1671 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001672 // or if *it* is a PHI, bail out.
Chris Lattner04689872006-09-09 22:02:56 +00001673 BasicBlock *NonConstBB = 0;
1674 for (unsigned i = 0; i != NumPHIValues; ++i)
1675 if (!isa<Constant>(PN->getIncomingValue(i))) {
1676 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerc4d8e7e2007-02-24 01:03:45 +00001677 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner04689872006-09-09 22:02:56 +00001678 NonConstBB = PN->getIncomingBlock(i);
1679
1680 // If the incoming non-constant value is in I's block, we have an infinite
1681 // loop.
1682 if (NonConstBB == I.getParent())
1683 return 0;
1684 }
1685
1686 // If there is exactly one non-constant value, we can insert a copy of the
1687 // operation in that block. However, if this is a critical edge, we would be
1688 // inserting the computation one some other paths (e.g. inside a loop). Only
1689 // do this if the pred block is unconditionally branching into the phi block.
1690 if (NonConstBB) {
1691 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1692 if (!BI || !BI->isUnconditional()) return 0;
1693 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001694
1695 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6e0123b2007-02-11 01:23:03 +00001696 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001697 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001698 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6e0123b2007-02-11 01:23:03 +00001699 NewPN->takeName(PN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001700
1701 // Next, add all of the operands to the PHI.
1702 if (I.getNumOperands() == 2) {
1703 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001704 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001705 Value *InV;
1706 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001707 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1709 else
1710 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001711 } else {
1712 assert(PN->getIncomingBlock(i) == NonConstBB);
1713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1714 InV = BinaryOperator::create(BO->getOpcode(),
1715 PN->getIncomingValue(i), C, "phitmp",
1716 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001717 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1718 InV = CmpInst::create(CI->getOpcode(),
1719 CI->getPredicate(),
1720 PN->getIncomingValue(i), C, "phitmp",
1721 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001722 else
1723 assert(0 && "Unknown binop!");
1724
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001725 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001726 }
1727 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001728 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001729 } else {
1730 CastInst *CI = cast<CastInst>(&I);
1731 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001732 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001733 Value *InV;
1734 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001735 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001736 } else {
1737 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001738 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1739 I.getType(), "phitmp",
1740 NonConstBB->getTerminator());
Chris Lattnerb15e2b12007-03-02 21:28:56 +00001741 AddToWorkList(cast<Instruction>(InV));
Chris Lattner04689872006-09-09 22:02:56 +00001742 }
1743 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001744 }
1745 }
1746 return ReplaceInstUsesWith(I, NewPN);
1747}
1748
Chris Lattner113f4f42002-06-25 16:13:24 +00001749Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001750 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001751 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001752
Chris Lattnercf4a9962004-04-10 22:01:55 +00001753 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001754 // X + undef -> undef
1755 if (isa<UndefValue>(RHS))
1756 return ReplaceInstUsesWith(I, RHS);
1757
Chris Lattnercf4a9962004-04-10 22:01:55 +00001758 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001759 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001760 if (RHSC->isNullValue())
1761 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001762 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1763 if (CFP->isExactlyValue(-0.0))
1764 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001765 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001766
Chris Lattnercf4a9962004-04-10 22:01:55 +00001767 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001768 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001769 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001770 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001771 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001772
1773 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1774 // (X & 254)+1 -> (X&254)|1
1775 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00001776 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00001777 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001778 KnownZero, KnownOne))
1779 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001780 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001781
1782 if (isa<PHINode>(LHS))
1783 if (Instruction *NV = FoldOpIntoPhi(I))
1784 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001785
Chris Lattner330628a2006-01-06 17:59:59 +00001786 ConstantInt *XorRHS = 0;
1787 Value *XorLHS = 0;
Chris Lattner4284f642007-01-30 22:32:46 +00001788 if (isa<ConstantInt>(RHSC) &&
1789 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner0b3557f2005-09-24 23:43:33 +00001790 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1791 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1792 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1793
1794 uint64_t C0080Val = 1ULL << 31;
1795 int64_t CFF80Val = -C0080Val;
1796 unsigned Size = 32;
1797 do {
1798 if (TySizeBits > Size) {
1799 bool Found = false;
1800 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1801 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1802 if (RHSSExt == CFF80Val) {
1803 if (XorRHS->getZExtValue() == C0080Val)
1804 Found = true;
1805 } else if (RHSZExt == C0080Val) {
1806 if (XorRHS->getSExtValue() == CFF80Val)
1807 Found = true;
1808 }
1809 if (Found) {
1810 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001811 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001812 Mask <<= 64-(TySizeBits-Size);
Reid Spencera94d3942007-01-19 21:13:56 +00001813 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001814 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001815 Size = 0; // Not a sign ext, but can't be any others either.
1816 goto FoundSExt;
1817 }
1818 }
1819 Size >>= 1;
1820 C0080Val >>= Size;
1821 CFF80Val >>= Size;
1822 } while (Size >= 8);
1823
1824FoundSExt:
1825 const Type *MiddleType = 0;
1826 switch (Size) {
1827 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001828 case 32: MiddleType = Type::Int32Ty; break;
1829 case 16: MiddleType = Type::Int16Ty; break;
1830 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001831 }
1832 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001833 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001834 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001835 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001836 }
1837 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001838 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001839
Chris Lattnerb8b97502003-08-13 19:01:45 +00001840 // X + X --> X << 1
Chris Lattner03c49532007-01-15 02:27:26 +00001841 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001842 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001843
1844 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1845 if (RHSI->getOpcode() == Instruction::Sub)
1846 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1847 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1848 }
1849 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1850 if (LHSI->getOpcode() == Instruction::Sub)
1851 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1852 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1853 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001854 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001855
Chris Lattner147e9752002-05-08 22:46:53 +00001856 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001857 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001858 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001859
1860 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001861 if (!isa<Constant>(RHS))
1862 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001863 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001864
Misha Brukmanb1c93172005-04-21 23:48:37 +00001865
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001866 ConstantInt *C2;
1867 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1868 if (X == RHS) // X*C + X --> X * (C+1)
1869 return BinaryOperator::createMul(RHS, AddOne(C2));
1870
1871 // X*C1 + X*C2 --> X * (C1+C2)
1872 ConstantInt *C1;
1873 if (X == dyn_castFoldableMul(RHS, C1))
1874 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001875 }
1876
1877 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001878 if (dyn_castFoldableMul(RHS, C2) == LHS)
1879 return BinaryOperator::createMul(LHS, AddOne(C2));
1880
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001881 // X + ~X --> -1 since ~X = -X-1
1882 if (dyn_castNotVal(LHS) == RHS ||
1883 dyn_castNotVal(RHS) == LHS)
1884 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1885
Chris Lattner57c8d992003-02-18 19:57:07 +00001886
Chris Lattnerb8b97502003-08-13 19:01:45 +00001887 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001888 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001889 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1890 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001891
Chris Lattnerb9cde762003-10-02 15:11:26 +00001892 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001893 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1895 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1896 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001897 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001898
Chris Lattnerbff91d92004-10-08 05:07:56 +00001899 // (X & FF00) + xx00 -> (X+xx00) & FF00
1900 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1901 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1902 if (Anded == CRHS) {
1903 // See if all bits from the first bit set in the Add RHS up are included
1904 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001905 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001906
1907 // Form a mask of all bits from the lowest bit added through the top.
1908 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Reid Spencera94d3942007-01-19 21:13:56 +00001909 AddRHSHighBits &= C2->getType()->getBitMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001910
1911 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001912 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001913
Chris Lattnerbff91d92004-10-08 05:07:56 +00001914 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1915 // Okay, the xform is safe. Insert the new add pronto.
1916 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1917 LHS->getName()), I);
1918 return BinaryOperator::createAnd(NewAdd, C2);
1919 }
1920 }
1921 }
1922
Chris Lattnerd4252a72004-07-30 07:50:03 +00001923 // Try to fold constant add into select arguments.
1924 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001925 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001926 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001927 }
1928
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001929 // add (cast *A to intptrtype) B ->
1930 // cast (GEP (cast *A to sbyte*) B) ->
1931 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001932 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001933 CastInst *CI = dyn_cast<CastInst>(LHS);
1934 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001935 if (!CI) {
1936 CI = dyn_cast<CastInst>(RHS);
1937 Other = LHS;
1938 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001939 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001940 (CI->getType()->getPrimitiveSizeInBits() ==
1941 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001942 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001943 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001944 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001945 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001946 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001947 }
1948 }
1949
Chris Lattner113f4f42002-06-25 16:13:24 +00001950 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001951}
1952
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001953// isSignBit - Return true if the value represented by the constant only has the
1954// highest order bit set.
1955static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001956 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001957 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001958}
1959
Chris Lattner113f4f42002-06-25 16:13:24 +00001960Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001962
Chris Lattnere6794492002-08-12 21:17:25 +00001963 if (Op0 == Op1) // sub X, X -> 0
1964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001965
Chris Lattnere6794492002-08-12 21:17:25 +00001966 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001967 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001968 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001969
Chris Lattner81a7a232004-10-16 18:11:37 +00001970 if (isa<UndefValue>(Op0))
1971 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1972 if (isa<UndefValue>(Op1))
1973 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1974
Chris Lattner8f2f5982003-11-05 01:06:05 +00001975 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1976 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001977 if (C->isAllOnesValue())
1978 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001979
Chris Lattner8f2f5982003-11-05 01:06:05 +00001980 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001981 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001982 if (match(Op1, m_Not(m_Value(X))))
1983 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001984 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner27df1db2007-01-15 07:02:54 +00001985 // -(X >>u 31) -> (X >>s 31)
1986 // -(X >>s 31) -> (X >>u 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001987 if (C->isNullValue()) {
Reid Spencer2341c222007-02-02 02:16:23 +00001988 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencerfdff9382006-11-08 06:47:33 +00001989 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001990 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001991 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001992 if (CU->getZExtValue() ==
1993 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001994 // Ok, the transformation is safe. Insert AShr.
Reid Spencer2341c222007-02-02 02:16:23 +00001995 return BinaryOperator::create(Instruction::AShr,
1996 SI->getOperand(0), CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001997 }
1998 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001999 }
2000 else if (SI->getOpcode() == Instruction::AShr) {
2001 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2002 // Check to see if we are shifting out everything but the sign bit.
2003 if (CU->getZExtValue() ==
2004 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002005 // Ok, the transformation is safe. Insert LShr.
Reid Spencer0d5f9232007-02-02 14:08:20 +00002006 return BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002007 SI->getOperand(0), CU, SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002008 }
2009 }
2010 }
Chris Lattner022167f2004-03-13 00:11:49 +00002011 }
Chris Lattner183b3362004-04-09 19:05:30 +00002012
2013 // Try to fold constant sub into select arguments.
2014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002016 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002017
2018 if (isa<PHINode>(Op0))
2019 if (Instruction *NV = FoldOpIntoPhi(I))
2020 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002021 }
2022
Chris Lattnera9be4492005-04-07 16:15:25 +00002023 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2024 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002025 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002026 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002027 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002028 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002029 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002030 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2031 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2032 // C1-(X+C2) --> (C1-C2)-X
2033 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2034 Op1I->getOperand(0));
2035 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002036 }
2037
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002038 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002039 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2040 // is not used by anyone else...
2041 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002042 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002043 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002044 // Swap the two operands of the subexpr...
2045 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2046 Op1I->setOperand(0, IIOp1);
2047 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002048
Chris Lattner3082c5a2003-02-18 19:28:33 +00002049 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051 }
2052
2053 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2054 //
2055 if (Op1I->getOpcode() == Instruction::And &&
2056 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2057 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2058
Chris Lattner396dbfe2004-06-09 05:08:07 +00002059 Value *NewNot =
2060 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002061 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002062 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002063
Reid Spencer3c514952006-10-16 23:08:08 +00002064 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002065 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002066 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002067 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002068 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002069 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002070 ConstantExpr::getNeg(DivRHS));
2071
Chris Lattner57c8d992003-02-18 19:57:07 +00002072 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002073 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002074 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002075 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002076 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002077 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002078 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002079 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002080 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002081
Chris Lattner7a002fe2006-12-02 00:13:08 +00002082 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002085 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2086 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2087 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2088 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002089 } else if (Op0I->getOpcode() == Instruction::Sub) {
2090 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2091 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002092 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002093
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002094 ConstantInt *C1;
2095 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2096 if (X == Op1) { // X*C - X --> X * (C-1)
2097 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2098 return BinaryOperator::createMul(Op1, CP1);
2099 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002100
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002101 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2102 if (X == dyn_castFoldableMul(Op1, C2))
2103 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2104 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002105 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002106}
2107
Reid Spencer266e42b2006-12-23 06:05:41 +00002108/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002109/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002110static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2111 switch (pred) {
2112 case ICmpInst::ICMP_SLT:
2113 // True if LHS s< RHS and RHS == 0
2114 return RHS->isNullValue();
2115 case ICmpInst::ICMP_SLE:
2116 // True if LHS s<= RHS and RHS == -1
2117 return RHS->isAllOnesValue();
2118 case ICmpInst::ICMP_UGE:
2119 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2120 return RHS->getZExtValue() == (1ULL <<
2121 (RHS->getType()->getPrimitiveSizeInBits()-1));
2122 case ICmpInst::ICMP_UGT:
2123 // True if LHS u> RHS and RHS == high-bit-mask - 1
2124 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002125 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002126 default:
2127 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002128 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002129}
2130
Chris Lattner113f4f42002-06-25 16:13:24 +00002131Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002132 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002134
Chris Lattner81a7a232004-10-16 18:11:37 +00002135 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2137
Chris Lattnere6794492002-08-12 21:17:25 +00002138 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002139 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2140 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002141
2142 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer2341c222007-02-02 02:16:23 +00002143 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerede3fe02003-08-13 04:18:28 +00002144 if (SI->getOpcode() == Instruction::Shl)
2145 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createMul(SI->getOperand(0),
2147 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002148
Chris Lattnercce81be2003-09-11 22:24:54 +00002149 if (CI->isNullValue())
2150 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2151 if (CI->equalsInt(1)) // X * 1 == X
2152 return ReplaceInstUsesWith(I, Op0);
2153 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002154 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002155
Reid Spencere0fc4df2006-10-20 07:07:24 +00002156 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002157 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2158 uint64_t C = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002159 return BinaryOperator::createShl(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002160 ConstantInt::get(Op0->getType(), C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002161 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002162 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002163 if (Op1F->isNullValue())
2164 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002165
Chris Lattner3082c5a2003-02-18 19:28:33 +00002166 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2167 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2168 if (Op1F->getValue() == 1.0)
2169 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2170 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002171
2172 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2173 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2174 isa<ConstantInt>(Op0I->getOperand(1))) {
2175 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2176 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2177 Op1, "tmp");
2178 InsertNewInstBefore(Add, I);
2179 Value *C1C2 = ConstantExpr::getMul(Op1,
2180 cast<Constant>(Op0I->getOperand(1)));
2181 return BinaryOperator::createAdd(Add, C1C2);
2182
2183 }
Chris Lattner183b3362004-04-09 19:05:30 +00002184
2185 // Try to fold constant mul into select arguments.
2186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002188 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002189
2190 if (isa<PHINode>(Op0))
2191 if (Instruction *NV = FoldOpIntoPhi(I))
2192 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002193 }
2194
Chris Lattner934a64cf2003-03-10 23:23:04 +00002195 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2196 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002197 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002198
Chris Lattner2635b522004-02-23 05:39:21 +00002199 // If one of the operands of the multiply is a cast from a boolean value, then
2200 // we know the bool is either zero or one, so this is a 'masking' multiply.
2201 // See if we can simplify things based on how the boolean was originally
2202 // formed.
2203 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002204 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002205 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002206 BoolCast = CI;
2207 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002208 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002209 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002210 BoolCast = CI;
2211 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002212 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002213 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2214 const Type *SCOpTy = SCIOp0->getType();
2215
Reid Spencer266e42b2006-12-23 06:05:41 +00002216 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002217 // multiply into a shift/and combination.
2218 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002219 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002220 // Shift the X value right to turn it into "all signbits".
Reid Spencer2341c222007-02-02 02:16:23 +00002221 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002222 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002223 Value *V =
Reid Spencer2341c222007-02-02 02:16:23 +00002224 InsertNewInstBefore(
2225 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002226 BoolCast->getOperand(0)->getName()+
2227 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002228
2229 // If the multiply type is not the same as the source type, sign extend
2230 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002231 if (I.getType() != V->getType()) {
2232 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2233 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2234 Instruction::CastOps opcode =
2235 (SrcBits == DstBits ? Instruction::BitCast :
2236 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2237 V = InsertCastBefore(opcode, V, I.getType(), I);
2238 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002239
Chris Lattner2635b522004-02-23 05:39:21 +00002240 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002241 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002242 }
2243 }
2244 }
2245
Chris Lattner113f4f42002-06-25 16:13:24 +00002246 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002247}
2248
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002249/// This function implements the transforms on div instructions that work
2250/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2251/// used by the visitors to those instructions.
2252/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002253Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002255
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002256 // undef / X -> 0
2257 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002259
2260 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002261 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002262 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002263
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002265 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2266 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002267 // same basic block, then we replace the select with Y, and the condition
2268 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002269 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002270 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002271 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2272 if (ST->isNullValue()) {
2273 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2274 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002275 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002276 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2277 I.setOperand(1, SI->getOperand(2));
2278 else
2279 UpdateValueUsesWith(SI, SI->getOperand(2));
2280 return &I;
2281 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002282
Chris Lattnerd79dc792006-09-09 20:26:32 +00002283 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2284 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2285 if (ST->isNullValue()) {
2286 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2287 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002288 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002289 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2290 I.setOperand(1, SI->getOperand(1));
2291 else
2292 UpdateValueUsesWith(SI, SI->getOperand(1));
2293 return &I;
2294 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002295 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002296
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002297 return 0;
2298}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002299
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002300/// This function implements the transforms common to both integer division
2301/// instructions (udiv and sdiv). It is called by the visitors to those integer
2302/// division instructions.
2303/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002304Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2306
2307 if (Instruction *Common = commonDivTransforms(I))
2308 return Common;
2309
2310 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2311 // div X, 1 == X
2312 if (RHS->equalsInt(1))
2313 return ReplaceInstUsesWith(I, Op0);
2314
2315 // (X / C1) / C2 -> X / (C1*C2)
2316 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2317 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2318 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2319 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2320 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002321 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002322
2323 if (!RHS->isNullValue()) { // avoid X udiv 0
2324 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2325 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2326 return R;
2327 if (isa<PHINode>(Op0))
2328 if (Instruction *NV = FoldOpIntoPhi(I))
2329 return NV;
2330 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002331 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002332
Chris Lattner3082c5a2003-02-18 19:28:33 +00002333 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002334 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002335 if (LHS->equalsInt(0))
2336 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2337
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338 return 0;
2339}
2340
2341Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2343
2344 // Handle the integer div common cases
2345 if (Instruction *Common = commonIDivTransforms(I))
2346 return Common;
2347
2348 // X udiv C^2 -> X >> C
2349 // Check to see if this is an unsigned division with an exact power of 2,
2350 // if so, convert to a right shift.
2351 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2352 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2353 if (isPowerOf2_64(Val)) {
2354 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002355 return BinaryOperator::createLShr(Op0,
Reid Spencer2341c222007-02-02 02:16:23 +00002356 ConstantInt::get(Op0->getType(), ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002357 }
2358 }
2359
2360 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer2341c222007-02-02 02:16:23 +00002361 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 if (RHSI->getOpcode() == Instruction::Shl &&
2363 isa<ConstantInt>(RHSI->getOperand(0))) {
2364 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2365 if (isPowerOf2_64(C1)) {
2366 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002367 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 Constant *C2V = ConstantInt::get(NTy, C2);
2370 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002371 }
Reid Spencer0d5f9232007-02-02 14:08:20 +00002372 return BinaryOperator::createLShr(Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002373 }
2374 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002375 }
2376
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2378 // where C1&C2 are powers of two.
2379 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2380 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2381 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2382 if (!STO->isNullValue() && !STO->isNullValue()) {
2383 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2384 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2385 // Compute the shift amounts
2386 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002387 // Construct the "on true" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002388 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002389 Instruction *TSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002390 Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002391 TSI = InsertNewInstBefore(TSI, I);
2392
2393 // Construct the "on false" case of the select
Reid Spencer2341c222007-02-02 02:16:23 +00002394 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Reid Spencer0d5f9232007-02-02 14:08:20 +00002395 Instruction *FSI = BinaryOperator::createLShr(
Reid Spencer2341c222007-02-02 02:16:23 +00002396 Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002397 FSI = InsertNewInstBefore(FSI, I);
2398
2399 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002400 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002401 }
2402 }
2403 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002404 return 0;
2405}
2406
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002407Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2408 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2409
2410 // Handle the integer div common cases
2411 if (Instruction *Common = commonIDivTransforms(I))
2412 return Common;
2413
2414 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2415 // sdiv X, -1 == -X
2416 if (RHS->isAllOnesValue())
2417 return BinaryOperator::createNeg(Op0);
2418
2419 // -X/C -> X/-C
2420 if (Value *LHSNeg = dyn_castNegVal(Op0))
2421 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2422 }
2423
2424 // If the sign bits of both operands are zero (i.e. we can prove they are
2425 // unsigned inputs), turn this into a udiv.
Chris Lattner03c49532007-01-15 02:27:26 +00002426 if (I.getType()->isInteger()) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002427 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2428 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2429 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2430 }
2431 }
2432
2433 return 0;
2434}
2435
2436Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2437 return commonDivTransforms(I);
2438}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002439
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440/// GetFactor - If we can prove that the specified value is at least a multiple
2441/// of some factor, return that factor.
2442static Constant *GetFactor(Value *V) {
2443 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2444 return CI;
2445
2446 // Unless we can be tricky, we know this is a multiple of 1.
2447 Constant *Result = ConstantInt::get(V->getType(), 1);
2448
2449 Instruction *I = dyn_cast<Instruction>(V);
2450 if (!I) return Result;
2451
2452 if (I->getOpcode() == Instruction::Mul) {
2453 // Handle multiplies by a constant, etc.
2454 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2455 GetFactor(I->getOperand(1)));
2456 } else if (I->getOpcode() == Instruction::Shl) {
2457 // (X<<C) -> X * (1 << C)
2458 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2459 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2460 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2461 }
2462 } else if (I->getOpcode() == Instruction::And) {
2463 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2464 // X & 0xFFF0 is known to be a multiple of 16.
2465 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2466 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2467 return ConstantExpr::getShl(Result,
Reid Spencer2341c222007-02-02 02:16:23 +00002468 ConstantInt::get(Result->getType(), Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002469 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002470 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002471 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002472 if (!CI->isIntegerCast())
2473 return Result;
2474 Value *Op = CI->getOperand(0);
2475 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002476 }
2477 return Result;
2478}
2479
Reid Spencer7eb55b32006-11-02 01:53:59 +00002480/// This function implements the transforms on rem instructions that work
2481/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2482/// is used by the visitors to those instructions.
2483/// @brief Transforms common to all three rem instructions
2484Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002485 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002486
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002487 // 0 % X == 0, we don't need to preserve faults!
2488 if (Constant *LHS = dyn_cast<Constant>(Op0))
2489 if (LHS->isNullValue())
2490 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2491
2492 if (isa<UndefValue>(Op0)) // undef % X -> 0
2493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494 if (isa<UndefValue>(Op1))
2495 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002496
2497 // Handle cases involving: rem X, (select Cond, Y, Z)
2498 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2499 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2500 // the same basic block, then we replace the select with Y, and the
2501 // condition of the select with false (if the cond value is in the same
2502 // BB). If the select has uses other than the div, this allows them to be
2503 // simplified also.
2504 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2505 if (ST->isNullValue()) {
2506 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2507 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002508 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002509 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2510 I.setOperand(1, SI->getOperand(2));
2511 else
2512 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002513 return &I;
2514 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002515 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2516 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2517 if (ST->isNullValue()) {
2518 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002520 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002521 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522 I.setOperand(1, SI->getOperand(1));
2523 else
2524 UpdateValueUsesWith(SI, SI->getOperand(1));
2525 return &I;
2526 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002527 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002528
Reid Spencer7eb55b32006-11-02 01:53:59 +00002529 return 0;
2530}
2531
2532/// This function implements the transforms common to both integer remainder
2533/// instructions (urem and srem). It is called by the visitors to those integer
2534/// remainder instructions.
2535/// @brief Common integer remainder transforms
2536Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539 if (Instruction *common = commonRemTransforms(I))
2540 return common;
2541
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002543 // X % 0 == undef, we don't need to preserve faults!
2544 if (RHS->equalsInt(0))
2545 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2546
Chris Lattner3082c5a2003-02-18 19:28:33 +00002547 if (RHS->equalsInt(1)) // X % 1 == 0
2548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2549
Chris Lattnerb70f1412006-02-28 05:49:21 +00002550 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2551 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2552 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2553 return R;
2554 } else if (isa<PHINode>(Op0I)) {
2555 if (Instruction *NV = FoldOpIntoPhi(I))
2556 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002557 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002558 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2559 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002561 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002562 }
2563
Reid Spencer7eb55b32006-11-02 01:53:59 +00002564 return 0;
2565}
2566
2567Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2568 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2569
2570 if (Instruction *common = commonIRemTransforms(I))
2571 return common;
2572
2573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574 // X urem C^2 -> X and C
2575 // Check to see if this is an unsigned remainder with an exact power of 2,
2576 // if so, convert to a bitwise and.
2577 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2578 if (isPowerOf2_64(C->getZExtValue()))
2579 return BinaryOperator::createAnd(Op0, SubOne(C));
2580 }
2581
Chris Lattner2e90b732006-02-05 07:54:04 +00002582 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002583 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2584 if (RHSI->getOpcode() == Instruction::Shl &&
2585 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002586 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002587 if (isPowerOf2_64(C1)) {
2588 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2589 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2590 "tmp"), I);
2591 return BinaryOperator::createAnd(Op0, Add);
2592 }
2593 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002594 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002595
Reid Spencer7eb55b32006-11-02 01:53:59 +00002596 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2597 // where C1&C2 are powers of two.
2598 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2599 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2600 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2601 // STO == 0 and SFO == 0 handled above.
2602 if (isPowerOf2_64(STO->getZExtValue()) &&
2603 isPowerOf2_64(SFO->getZExtValue())) {
2604 Value *TrueAnd = InsertNewInstBefore(
2605 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2606 Value *FalseAnd = InsertNewInstBefore(
2607 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2608 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2609 }
2610 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002611 }
2612
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002613 return 0;
2614}
2615
Reid Spencer7eb55b32006-11-02 01:53:59 +00002616Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2617 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2618
2619 if (Instruction *common = commonIRemTransforms(I))
2620 return common;
2621
2622 if (Value *RHSNeg = dyn_castNegVal(Op1))
2623 if (!isa<ConstantInt>(RHSNeg) ||
2624 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2625 // X % -Y -> X % Y
2626 AddUsesToWorkList(I);
2627 I.setOperand(1, RHSNeg);
2628 return &I;
2629 }
2630
2631 // If the top bits of both operands are zero (i.e. we can prove they are
2632 // unsigned inputs), turn this into a urem.
2633 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2634 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2635 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2636 return BinaryOperator::createURem(Op0, Op1, I.getName());
2637 }
2638
2639 return 0;
2640}
2641
2642Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002643 return commonRemTransforms(I);
2644}
2645
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002646// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002647static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2648 if (isSigned) {
2649 // Calculate 0111111111..11111
2650 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2651 int64_t Val = INT64_MAX; // All ones
2652 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2653 return C->getSExtValue() == Val-1;
2654 }
Reid Spencera94d3942007-01-19 21:13:56 +00002655 return C->getZExtValue() == C->getType()->getBitMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002656}
2657
2658// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002659static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2660 if (isSigned) {
2661 // Calculate 1111111111000000000000
2662 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663 int64_t Val = -1; // All ones
2664 Val <<= TypeBits-1; // Shift over to the right spot
2665 return C->getSExtValue() == Val+1;
2666 }
2667 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002668}
2669
Chris Lattner35167c32004-06-09 07:59:58 +00002670// isOneBitSet - Return true if there is exactly one bit set in the specified
2671// constant.
2672static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002673 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002674 return V && (V & (V-1)) == 0;
2675}
2676
Chris Lattner8fc5af42004-09-23 21:46:38 +00002677#if 0 // Currently unused
2678// isLowOnes - Return true if the constant is of the form 0+1+.
2679static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002680 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002681
2682 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002683 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002684
2685 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2686 return U && V && (U & V) == 0;
2687}
2688#endif
2689
2690// isHighOnes - Return true if the constant is of the form 1+0+.
2691// This is the same as lowones(~X).
2692static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002693 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002694 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002695
2696 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002697 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002698
2699 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2700 return U && V && (U & V) == 0;
2701}
2702
Reid Spencer266e42b2006-12-23 06:05:41 +00002703/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002704/// are carefully arranged to allow folding of expressions such as:
2705///
2706/// (A < B) | (A > B) --> (A != B)
2707///
Reid Spencer266e42b2006-12-23 06:05:41 +00002708/// Note that this is only valid if the first and second predicates have the
2709/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002710///
Reid Spencer266e42b2006-12-23 06:05:41 +00002711/// Three bits are used to represent the condition, as follows:
2712/// 0 A > B
2713/// 1 A == B
2714/// 2 A < B
2715///
2716/// <=> Value Definition
2717/// 000 0 Always false
2718/// 001 1 A > B
2719/// 010 2 A == B
2720/// 011 3 A >= B
2721/// 100 4 A < B
2722/// 101 5 A != B
2723/// 110 6 A <= B
2724/// 111 7 Always true
2725///
2726static unsigned getICmpCode(const ICmpInst *ICI) {
2727 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002728 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002729 case ICmpInst::ICMP_UGT: return 1; // 001
2730 case ICmpInst::ICMP_SGT: return 1; // 001
2731 case ICmpInst::ICMP_EQ: return 2; // 010
2732 case ICmpInst::ICMP_UGE: return 3; // 011
2733 case ICmpInst::ICMP_SGE: return 3; // 011
2734 case ICmpInst::ICMP_ULT: return 4; // 100
2735 case ICmpInst::ICMP_SLT: return 4; // 100
2736 case ICmpInst::ICMP_NE: return 5; // 101
2737 case ICmpInst::ICMP_ULE: return 6; // 110
2738 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002739 // True -> 7
2740 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002741 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002742 return 0;
2743 }
2744}
2745
Reid Spencer266e42b2006-12-23 06:05:41 +00002746/// getICmpValue - This is the complement of getICmpCode, which turns an
2747/// opcode and two operands into either a constant true or false, or a brand
2748/// new /// ICmp instruction. The sign is passed in to determine which kind
2749/// of predicate to use in new icmp instructions.
2750static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2751 switch (code) {
2752 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002753 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002754 case 1:
2755 if (sign)
2756 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2757 else
2758 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2759 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2760 case 3:
2761 if (sign)
2762 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2763 else
2764 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2765 case 4:
2766 if (sign)
2767 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2768 else
2769 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2770 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2771 case 6:
2772 if (sign)
2773 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2774 else
2775 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002776 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002777 }
2778}
2779
Reid Spencer266e42b2006-12-23 06:05:41 +00002780static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2781 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2782 (ICmpInst::isSignedPredicate(p1) &&
2783 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2784 (ICmpInst::isSignedPredicate(p2) &&
2785 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2786}
2787
2788namespace {
2789// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2790struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 InstCombiner &IC;
2792 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002793 ICmpInst::Predicate pred;
2794 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2795 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2796 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002797 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002798 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2799 if (PredicatesFoldable(pred, ICI->getPredicate()))
2800 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2801 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002802 return false;
2803 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002804 Instruction *apply(Instruction &Log) const {
2805 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2806 if (ICI->getOperand(0) != LHS) {
2807 assert(ICI->getOperand(1) == LHS);
2808 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002809 }
2810
Reid Spencer266e42b2006-12-23 06:05:41 +00002811 unsigned LHSCode = getICmpCode(ICI);
2812 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002813 unsigned Code;
2814 switch (Log.getOpcode()) {
2815 case Instruction::And: Code = LHSCode & RHSCode; break;
2816 case Instruction::Or: Code = LHSCode | RHSCode; break;
2817 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002818 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002819 }
2820
Reid Spencer266e42b2006-12-23 06:05:41 +00002821 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 if (Instruction *I = dyn_cast<Instruction>(RV))
2823 return I;
2824 // Otherwise, it's a constant boolean value...
2825 return IC.ReplaceInstUsesWith(Log, RV);
2826 }
2827};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002828} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002829
Chris Lattnerba1cb382003-09-19 17:17:26 +00002830// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2831// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer2341c222007-02-02 02:16:23 +00002832// guaranteed to be a binary operator.
Chris Lattnerba1cb382003-09-19 17:17:26 +00002833Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002834 ConstantInt *OpRHS,
2835 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002836 BinaryOperator &TheAnd) {
2837 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002838 Constant *Together = 0;
Reid Spencer2341c222007-02-02 02:16:23 +00002839 if (!Op->isShift())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002840 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002841
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842 switch (Op->getOpcode()) {
2843 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002844 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6e0123b2007-02-11 01:23:03 +00002846 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002847 InsertNewInstBefore(And, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002848 And->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 }
2851 break;
2852 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002853 if (Together == AndRHS) // (X | C) & C --> C
2854 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002855
Chris Lattner86102b82005-01-01 16:22:27 +00002856 if (Op->hasOneUse() && Together != OpRHS) {
2857 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6e0123b2007-02-11 01:23:03 +00002858 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner86102b82005-01-01 16:22:27 +00002859 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002860 Or->takeName(Op);
Chris Lattner86102b82005-01-01 16:22:27 +00002861 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002862 }
2863 break;
2864 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002865 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002866 // Adding a one to a single bit bit-field should be turned into an XOR
2867 // of the bit. First thing to check is to see if this AND is with a
2868 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002869 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002870
2871 // Clear bits that are not part of the constant.
Reid Spencera94d3942007-01-19 21:13:56 +00002872 AndRHSV &= AndRHS->getType()->getBitMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002873
2874 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002875 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002876 // Ok, at this point, we know that we are masking the result of the
2877 // ADD down to exactly one bit. If the constant we are adding has
2878 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002879 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002880
Chris Lattnerba1cb382003-09-19 17:17:26 +00002881 // Check to see if any bits below the one bit set in AndRHSV are set.
2882 if ((AddRHS & (AndRHSV-1)) == 0) {
2883 // If not, the only thing that can effect the output of the AND is
2884 // the bit specified by AndRHSV. If that bit is set, the effect of
2885 // the XOR is to toggle the bit. If it is clear, then the ADD has
2886 // no effect.
2887 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2888 TheAnd.setOperand(0, X);
2889 return &TheAnd;
2890 } else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002891 // Pull the XOR out of the AND.
Chris Lattner6e0123b2007-02-11 01:23:03 +00002892 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002893 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6e0123b2007-02-11 01:23:03 +00002894 NewAnd->takeName(Op);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002895 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002896 }
2897 }
2898 }
2899 }
2900 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002901
2902 case Instruction::Shl: {
2903 // We know that the AND will not produce any of the bits shifted in, so if
2904 // the anded constant includes them, clear them now!
2905 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002906 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002907 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2908 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002909
Chris Lattner7e794272004-09-24 15:21:34 +00002910 if (CI == ShlMask) { // Masking out bits that the shift already masks
2911 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2912 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002913 TheAnd.setOperand(1, CI);
2914 return &TheAnd;
2915 }
2916 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002917 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002918 case Instruction::LShr:
2919 {
Chris Lattner2da29172003-09-19 19:05:02 +00002920 // We know that the AND will not produce any of the bits shifted in, so if
2921 // the anded constant includes them, clear them now! This only applies to
2922 // unsigned shifts, because a signed shr may bring in set bits!
2923 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002924 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002925 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2926 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002927
Reid Spencerfdff9382006-11-08 06:47:33 +00002928 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2929 return ReplaceInstUsesWith(TheAnd, Op);
2930 } else if (CI != AndRHS) {
2931 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2932 return &TheAnd;
2933 }
2934 break;
2935 }
2936 case Instruction::AShr:
2937 // Signed shr.
2938 // See if this is shifting in some sign extension, then masking it out
2939 // with an and.
2940 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002941 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002942 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002943 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2944 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002945 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002946 // Make the argument unsigned.
2947 Value *ShVal = Op->getOperand(0);
Reid Spencer2341c222007-02-02 02:16:23 +00002948 ShVal = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00002949 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer2341c222007-02-02 02:16:23 +00002950 Op->getName()), TheAnd);
Reid Spencer2a499b02006-12-13 17:19:09 +00002951 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002952 }
Chris Lattner2da29172003-09-19 19:05:02 +00002953 }
2954 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002955 }
2956 return 0;
2957}
2958
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002959
Chris Lattner6862fbd2004-09-29 17:40:11 +00002960/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2961/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002962/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2963/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002964/// insert new instructions.
2965Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002966 bool isSigned, bool Inside,
2967 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002968 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002969 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002970 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002971
Chris Lattner6862fbd2004-09-29 17:40:11 +00002972 if (Inside) {
2973 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002975
Reid Spencer266e42b2006-12-23 06:05:41 +00002976 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002977 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002978 ICmpInst::Predicate pred = (isSigned ?
2979 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2980 return new ICmpInst(pred, V, Hi);
2981 }
2982
2983 // Emit V-Lo <u Hi-Lo
2984 Constant *NegLo = ConstantExpr::getNeg(Lo);
2985 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002986 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002987 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2988 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002989 }
2990
2991 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002992 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002993
Reid Spencer266e42b2006-12-23 06:05:41 +00002994 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002995 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002996 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002997 ICmpInst::Predicate pred = (isSigned ?
2998 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2999 return new ICmpInst(pred, V, Hi);
3000 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003001
Reid Spencer266e42b2006-12-23 06:05:41 +00003002 // Emit V-Lo > Hi-1-Lo
3003 Constant *NegLo = ConstantExpr::getNeg(Lo);
3004 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003005 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003006 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3007 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003008}
3009
Chris Lattnerb4b25302005-09-18 07:22:02 +00003010// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3011// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3012// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3013// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003014static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003015 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003016 if (!isShiftedMask_64(V)) return false;
3017
3018 // look for the first zero bit after the run of ones
3019 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3020 // look for the first non-zero bit
3021 ME = 64-CountLeadingZeros_64(V);
3022 return true;
3023}
3024
3025
3026
3027/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3028/// where isSub determines whether the operator is a sub. If we can fold one of
3029/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003030///
3031/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3032/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3033/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3034///
3035/// return (A +/- B).
3036///
3037Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003038 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003039 Instruction &I) {
3040 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3041 if (!LHSI || LHSI->getNumOperands() != 2 ||
3042 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3043
3044 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3045
3046 switch (LHSI->getOpcode()) {
3047 default: return 0;
3048 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003049 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3050 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003051 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003052 break;
3053
3054 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3055 // part, we don't need any explicit masks to take them out of A. If that
3056 // is all N is, ignore it.
3057 unsigned MB, ME;
3058 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencera94d3942007-01-19 21:13:56 +00003059 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003060 Mask >>= 64-MB+1;
3061 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003062 break;
3063 }
3064 }
Chris Lattneraf517572005-09-18 04:24:45 +00003065 return 0;
3066 case Instruction::Or:
3067 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003068 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003069 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003070 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003071 break;
3072 return 0;
3073 }
3074
3075 Instruction *New;
3076 if (isSub)
3077 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3078 else
3079 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3080 return InsertNewInstBefore(New, I);
3081}
3082
Chris Lattner113f4f42002-06-25 16:13:24 +00003083Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003084 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003085 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003086
Chris Lattner81a7a232004-10-16 18:11:37 +00003087 if (isa<UndefValue>(Op1)) // X & undef -> 0
3088 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3089
Chris Lattner86102b82005-01-01 16:22:27 +00003090 // and X, X = X
3091 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003092 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003093
Chris Lattner5b2edb12006-02-12 08:02:11 +00003094 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003095 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003096 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003097 if (!isa<VectorType>(I.getType())) {
Reid Spencera94d3942007-01-19 21:13:56 +00003098 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner120ab032007-01-18 22:16:33 +00003099 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003100 return &I;
Chris Lattner120ab032007-01-18 22:16:33 +00003101 } else {
Reid Spencerd84d35b2007-02-15 02:26:10 +00003102 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner120ab032007-01-18 22:16:33 +00003103 if (CP->isAllOnesValue())
3104 return ReplaceInstUsesWith(I, I.getOperand(0));
3105 }
3106 }
Chris Lattner5997cf92006-02-08 03:25:32 +00003107
Zhou Sheng75b871f2007-01-11 12:24:14 +00003108 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003109 uint64_t AndRHSMask = AndRHS->getZExtValue();
Reid Spencera94d3942007-01-19 21:13:56 +00003110 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003111 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003112
Chris Lattnerba1cb382003-09-19 17:17:26 +00003113 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer2341c222007-02-02 02:16:23 +00003114 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00003115 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003116 Value *Op0LHS = Op0I->getOperand(0);
3117 Value *Op0RHS = Op0I->getOperand(1);
3118 switch (Op0I->getOpcode()) {
3119 case Instruction::Xor:
3120 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003121 // If the mask is only needed on one incoming arm, push it up.
3122 if (Op0I->hasOneUse()) {
3123 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3124 // Not masking anything out for the LHS, move to RHS.
3125 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3126 Op0RHS->getName()+".masked");
3127 InsertNewInstBefore(NewRHS, I);
3128 return BinaryOperator::create(
3129 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003130 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003131 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003132 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3133 // Not masking anything out for the RHS, move to LHS.
3134 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3135 Op0LHS->getName()+".masked");
3136 InsertNewInstBefore(NewLHS, I);
3137 return BinaryOperator::create(
3138 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3139 }
3140 }
3141
Chris Lattner86102b82005-01-01 16:22:27 +00003142 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003143 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003144 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3145 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3146 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3148 return BinaryOperator::createAnd(V, AndRHS);
3149 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3150 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003151 break;
3152
3153 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003154 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3155 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3156 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3158 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003159 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003160 }
3161
Chris Lattner16464b32003-07-23 19:25:52 +00003162 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003163 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003164 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003165 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003166 // If this is an integer truncation or change from signed-to-unsigned, and
3167 // if the source is an and/or with immediate, transform it. This
3168 // frequently occurs for bitfield accesses.
3169 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003170 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003171 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003172 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003173 if (CastOp->getOpcode() == Instruction::And) {
3174 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003175 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3176 // This will fold the two constants together, which may allow
3177 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003178 Instruction *NewCast = CastInst::createTruncOrBitCast(
3179 CastOp->getOperand(0), I.getType(),
3180 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003181 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003182 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003183 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003184 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003185 return BinaryOperator::createAnd(NewCast, C3);
3186 } else if (CastOp->getOpcode() == Instruction::Or) {
3187 // Change: and (cast (or X, C1) to T), C2
3188 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003189 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003190 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3191 return ReplaceInstUsesWith(I, AndRHS);
3192 }
3193 }
Chris Lattner33217db2003-07-23 19:36:21 +00003194 }
Chris Lattner183b3362004-04-09 19:05:30 +00003195
3196 // Try to fold constant and into select arguments.
3197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003199 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003200 if (isa<PHINode>(Op0))
3201 if (Instruction *NV = FoldOpIntoPhi(I))
3202 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003203 }
3204
Chris Lattnerbb74e222003-03-10 23:06:50 +00003205 Value *Op0NotVal = dyn_castNotVal(Op0);
3206 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003207
Chris Lattner023a4832004-06-18 06:07:51 +00003208 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3209 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3210
Misha Brukman9c003d82004-07-30 12:50:08 +00003211 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003212 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003213 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3214 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003215 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003216 return BinaryOperator::createNot(Or);
3217 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003218
3219 {
3220 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003221 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3222 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3223 return ReplaceInstUsesWith(I, Op1);
3224 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3225 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3226 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003227
3228 if (Op0->hasOneUse() &&
3229 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3230 if (A == Op1) { // (A^B)&A -> A&(A^B)
3231 I.swapOperands(); // Simplify below
3232 std::swap(Op0, Op1);
3233 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3234 cast<BinaryOperator>(Op0)->swapOperands();
3235 I.swapOperands(); // Simplify below
3236 std::swap(Op0, Op1);
3237 }
3238 }
3239 if (Op1->hasOneUse() &&
3240 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3241 if (B == Op0) { // B&(A^B) -> B&(B^A)
3242 cast<BinaryOperator>(Op1)->swapOperands();
3243 std::swap(A, B);
3244 }
3245 if (A == Op0) { // A&(A^B) -> A & ~B
3246 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3247 InsertNewInstBefore(NotB, I);
3248 return BinaryOperator::createAnd(A, NotB);
3249 }
3250 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003251 }
3252
Reid Spencer266e42b2006-12-23 06:05:41 +00003253 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3254 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3255 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003256 return R;
3257
Chris Lattner623826c2004-09-28 21:48:02 +00003258 Value *LHSVal, *RHSVal;
3259 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003260 ICmpInst::Predicate LHSCC, RHSCC;
3261 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3262 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3263 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3264 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3265 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3266 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3267 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3268 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003269 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003270 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3271 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3272 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3273 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003274 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003275 std::swap(LHS, RHS);
3276 std::swap(LHSCst, RHSCst);
3277 std::swap(LHSCC, RHSCC);
3278 }
3279
Reid Spencer266e42b2006-12-23 06:05:41 +00003280 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003281 // comparing a value against two constants and and'ing the result
3282 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003283 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3284 // (from the FoldICmpLogical check above), that the two constants
3285 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003286 assert(LHSCst != RHSCst && "Compares not folded above?");
3287
3288 switch (LHSCC) {
3289 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003290 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003291 switch (RHSCC) {
3292 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003293 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3294 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3295 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003296 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003297 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3298 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3299 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003300 return ReplaceInstUsesWith(I, LHS);
3301 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003303 switch (RHSCC) {
3304 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003305 case ICmpInst::ICMP_ULT:
3306 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3307 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3308 break; // (X != 13 & X u< 15) -> no change
3309 case ICmpInst::ICMP_SLT:
3310 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3311 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3312 break; // (X != 13 & X s< 15) -> no change
3313 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3314 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3315 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003316 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003317 case ICmpInst::ICMP_NE:
3318 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003319 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3320 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3321 LHSVal->getName()+".off");
3322 InsertNewInstBefore(Add, I);
Chris Lattnerc8fb6de2007-01-27 23:08:34 +00003323 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3324 ConstantInt::get(Add->getType(), 1));
Chris Lattner623826c2004-09-28 21:48:02 +00003325 }
3326 break; // (X != 13 & X != 15) -> no change
3327 }
3328 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003329 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003330 switch (RHSCC) {
3331 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003332 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3333 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003334 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003335 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3336 break;
3337 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3338 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003339 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003340 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3341 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003342 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003343 break;
3344 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003345 switch (RHSCC) {
3346 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3348 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003349 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003350 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3351 break;
3352 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3353 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003354 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3356 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003357 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003358 break;
3359 case ICmpInst::ICMP_UGT:
3360 switch (RHSCC) {
3361 default: assert(0 && "Unknown integer condition code!");
3362 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3363 return ReplaceInstUsesWith(I, LHS);
3364 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3365 return ReplaceInstUsesWith(I, RHS);
3366 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3367 break;
3368 case ICmpInst::ICMP_NE:
3369 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3370 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3371 break; // (X u> 13 & X != 15) -> no change
3372 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3373 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3374 true, I);
3375 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3376 break;
3377 }
3378 break;
3379 case ICmpInst::ICMP_SGT:
3380 switch (RHSCC) {
3381 default: assert(0 && "Unknown integer condition code!");
3382 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3383 return ReplaceInstUsesWith(I, LHS);
3384 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3385 return ReplaceInstUsesWith(I, RHS);
3386 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3387 break;
3388 case ICmpInst::ICMP_NE:
3389 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3390 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3391 break; // (X s> 13 & X != 15) -> no change
3392 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3393 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3394 true, I);
3395 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3396 break;
3397 }
3398 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003399 }
3400 }
3401 }
3402
Chris Lattner3af10532006-05-05 06:39:07 +00003403 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003404 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3405 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3406 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3407 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003408 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003409 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003410 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3411 I.getType(), TD) &&
3412 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3413 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003414 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3415 Op1C->getOperand(0),
3416 I.getName());
3417 InsertNewInstBefore(NewOp, I);
3418 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3419 }
Chris Lattner3af10532006-05-05 06:39:07 +00003420 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003421
3422 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003423 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3424 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3425 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003426 SI0->getOperand(1) == SI1->getOperand(1) &&
3427 (SI0->hasOneUse() || SI1->hasOneUse())) {
3428 Instruction *NewOp =
3429 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3430 SI1->getOperand(0),
3431 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003432 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3433 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003434 }
Chris Lattner3af10532006-05-05 06:39:07 +00003435 }
3436
Chris Lattner113f4f42002-06-25 16:13:24 +00003437 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003438}
3439
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003440/// CollectBSwapParts - Look to see if the specified value defines a single byte
3441/// in the result. If it does, and if the specified byte hasn't been filled in
3442/// yet, fill it in and return false.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003443static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003444 Instruction *I = dyn_cast<Instruction>(V);
3445 if (I == 0) return true;
3446
3447 // If this is an or instruction, it is an inner node of the bswap.
3448 if (I->getOpcode() == Instruction::Or)
3449 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3450 CollectBSwapParts(I->getOperand(1), ByteValues);
3451
3452 // If this is a shift by a constant int, and it is "24", then its operand
3453 // defines a byte. We only handle unsigned types here.
Reid Spencer2341c222007-02-02 02:16:23 +00003454 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003455 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003456 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003457 8*(ByteValues.size()-1))
3458 return true;
3459
3460 unsigned DestNo;
3461 if (I->getOpcode() == Instruction::Shl) {
3462 // X << 24 defines the top byte with the lowest of the input bytes.
3463 DestNo = ByteValues.size()-1;
3464 } else {
3465 // X >>u 24 defines the low byte with the highest of the input bytes.
3466 DestNo = 0;
3467 }
3468
3469 // If the destination byte value is already defined, the values are or'd
3470 // together, which isn't a bswap (unless it's an or of the same bits).
3471 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3472 return true;
3473 ByteValues[DestNo] = I->getOperand(0);
3474 return false;
3475 }
3476
3477 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3478 // don't have this.
3479 Value *Shift = 0, *ShiftLHS = 0;
3480 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3481 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3482 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3483 return true;
3484 Instruction *SI = cast<Instruction>(Shift);
3485
3486 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003487 if (ShiftAmt->getZExtValue() & 7 ||
3488 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003489 return true;
3490
3491 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3492 unsigned DestByte;
3493 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003494 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003495 break;
3496 // Unknown mask for bswap.
3497 if (DestByte == ByteValues.size()) return true;
3498
Reid Spencere0fc4df2006-10-20 07:07:24 +00003499 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003500 unsigned SrcByte;
3501 if (SI->getOpcode() == Instruction::Shl)
3502 SrcByte = DestByte - ShiftBytes;
3503 else
3504 SrcByte = DestByte + ShiftBytes;
3505
3506 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3507 if (SrcByte != ByteValues.size()-DestByte-1)
3508 return true;
3509
3510 // If the destination byte value is already defined, the values are or'd
3511 // together, which isn't a bswap (unless it's an or of the same bits).
3512 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3513 return true;
3514 ByteValues[DestByte] = SI->getOperand(0);
3515 return false;
3516}
3517
3518/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3519/// If so, insert the new bswap intrinsic and return it.
3520Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Reid Spencer2341c222007-02-02 02:16:23 +00003521 // We cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003522 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003523 return 0;
3524
3525 /// ByteValues - For each byte of the result, we keep track of which value
3526 /// defines each byte.
Chris Lattner99c6cf62007-02-15 22:52:10 +00003527 SmallVector<Value*, 8> ByteValues;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00003528 ByteValues.resize(TD->getTypeSize(I.getType()));
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003529
3530 // Try to find all the pieces corresponding to the bswap.
3531 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3532 CollectBSwapParts(I.getOperand(1), ByteValues))
3533 return 0;
3534
3535 // Check to see if all of the bytes come from the same value.
3536 Value *V = ByteValues[0];
3537 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3538
3539 // Check to make sure that all of the bytes come from the same value.
3540 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3541 if (ByteValues[i] != V)
3542 return 0;
3543
3544 // If they do then *success* we can turn this into a bswap. Figure out what
3545 // bswap to make it into.
3546 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003547 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003548 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003549 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003550 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003551 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003552 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003553 FnName = "llvm.bswap.i64";
3554 else
3555 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003556 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003557 return new CallInst(F, V);
3558}
3559
3560
Chris Lattner113f4f42002-06-25 16:13:24 +00003561Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003562 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003563 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003564
Chris Lattner81a7a232004-10-16 18:11:37 +00003565 if (isa<UndefValue>(Op1))
3566 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003567 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003568
Chris Lattner5b2edb12006-02-12 08:02:11 +00003569 // or X, X = X
3570 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003571 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003572
Chris Lattner5b2edb12006-02-12 08:02:11 +00003573 // See if we can simplify any instructions used by the instruction whose sole
3574 // purpose is to compute bits we don't care about.
3575 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003576 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003577 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003578 KnownZero, KnownOne))
3579 return &I;
3580
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003581 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003583 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003584 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3585 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003586 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003587 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003588 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003589 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3590 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003591
Chris Lattnerd4252a72004-07-30 07:50:03 +00003592 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3593 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003594 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003595 InsertNewInstBefore(Or, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00003596 Or->takeName(Op0);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003597 return BinaryOperator::createXor(Or,
3598 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003599 }
Chris Lattner183b3362004-04-09 19:05:30 +00003600
3601 // Try to fold constant and into select arguments.
3602 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003603 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003604 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003605 if (isa<PHINode>(Op0))
3606 if (Instruction *NV = FoldOpIntoPhi(I))
3607 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003608 }
3609
Chris Lattner330628a2006-01-06 17:59:59 +00003610 Value *A = 0, *B = 0;
3611 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003612
3613 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3614 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3615 return ReplaceInstUsesWith(I, Op1);
3616 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3617 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3618 return ReplaceInstUsesWith(I, Op0);
3619
Chris Lattnerb7845d62006-07-10 20:25:24 +00003620 // (A | B) | C and A | (B | C) -> bswap if possible.
3621 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003622 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003623 match(Op1, m_Or(m_Value(), m_Value())) ||
3624 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3625 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003626 if (Instruction *BSwap = MatchBSwap(I))
3627 return BSwap;
3628 }
3629
Chris Lattnerb62f5082005-05-09 04:58:36 +00003630 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3631 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003632 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003633 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3634 InsertNewInstBefore(NOr, I);
3635 NOr->takeName(Op0);
3636 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003637 }
3638
3639 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3640 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003641 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00003642 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3643 InsertNewInstBefore(NOr, I);
3644 NOr->takeName(Op0);
3645 return BinaryOperator::createXor(NOr, C1);
Chris Lattnerb62f5082005-05-09 04:58:36 +00003646 }
3647
Chris Lattner15212982005-09-18 03:42:07 +00003648 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003649 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003650 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3651
3652 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3653 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3654
3655
Chris Lattner01f56c62005-09-18 06:02:59 +00003656 // If we have: ((V + N) & C1) | (V & C2)
3657 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3658 // replace with V+N.
3659 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003660 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003661 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003662 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3663 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003664 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003665 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003666 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003667 return ReplaceInstUsesWith(I, A);
3668 }
3669 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003670 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003671 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3672 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003673 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003674 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003675 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003676 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003677 }
3678 }
3679 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003680
3681 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00003682 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3683 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3684 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003685 SI0->getOperand(1) == SI1->getOperand(1) &&
3686 (SI0->hasOneUse() || SI1->hasOneUse())) {
3687 Instruction *NewOp =
3688 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3689 SI1->getOperand(0),
3690 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00003691 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3692 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003693 }
3694 }
Chris Lattner812aab72003-08-12 19:11:07 +00003695
Chris Lattnerd4252a72004-07-30 07:50:03 +00003696 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3697 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003698 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003699 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003700 } else {
3701 A = 0;
3702 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003703 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003704 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3705 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003706 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003707 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003708
Misha Brukman9c003d82004-07-30 12:50:08 +00003709 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003710 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3711 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3712 I.getName()+".demorgan"), I);
3713 return BinaryOperator::createNot(And);
3714 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003715 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003716
Reid Spencer266e42b2006-12-23 06:05:41 +00003717 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3718 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3719 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003720 return R;
3721
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003722 Value *LHSVal, *RHSVal;
3723 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003724 ICmpInst::Predicate LHSCC, RHSCC;
3725 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3726 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3727 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3728 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3729 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3730 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3731 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3732 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003733 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003734 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3735 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3736 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3737 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003738 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003739 std::swap(LHS, RHS);
3740 std::swap(LHSCst, RHSCst);
3741 std::swap(LHSCC, RHSCC);
3742 }
3743
Reid Spencer266e42b2006-12-23 06:05:41 +00003744 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003745 // comparing a value against two constants and or'ing the result
3746 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003747 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3748 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003749 // equal.
3750 assert(LHSCst != RHSCst && "Compares not folded above?");
3751
3752 switch (LHSCC) {
3753 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003754 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003755 switch (RHSCC) {
3756 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003757 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3759 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3760 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3761 LHSVal->getName()+".off");
3762 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003763 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003764 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003765 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003766 break; // (X == 13 | X == 15) -> no change
3767 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3768 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003769 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003770 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3771 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3772 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003773 return ReplaceInstUsesWith(I, RHS);
3774 }
3775 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003776 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003777 switch (RHSCC) {
3778 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3780 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3781 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003782 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003783 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3784 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3785 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003786 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003787 }
3788 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003789 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003790 switch (RHSCC) {
3791 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003792 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003793 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003794 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3795 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3796 false, I);
3797 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3798 break;
3799 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3800 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003801 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3803 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003804 }
3805 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003806 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003807 switch (RHSCC) {
3808 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003809 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3810 break;
3811 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3812 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3813 false, I);
3814 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3815 break;
3816 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3817 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3818 return ReplaceInstUsesWith(I, RHS);
3819 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3820 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003821 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003822 break;
3823 case ICmpInst::ICMP_UGT:
3824 switch (RHSCC) {
3825 default: assert(0 && "Unknown integer condition code!");
3826 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3827 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3828 return ReplaceInstUsesWith(I, LHS);
3829 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3830 break;
3831 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3832 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003833 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003834 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3835 break;
3836 }
3837 break;
3838 case ICmpInst::ICMP_SGT:
3839 switch (RHSCC) {
3840 default: assert(0 && "Unknown integer condition code!");
3841 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3842 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3843 return ReplaceInstUsesWith(I, LHS);
3844 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3845 break;
3846 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3847 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003848 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003849 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3850 break;
3851 }
3852 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003853 }
3854 }
3855 }
Chris Lattner3af10532006-05-05 06:39:07 +00003856
3857 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003858 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003859 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003860 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3861 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00003862 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00003863 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003864 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3865 I.getType(), TD) &&
3866 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3867 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003868 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3869 Op1C->getOperand(0),
3870 I.getName());
3871 InsertNewInstBefore(NewOp, I);
3872 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3873 }
Chris Lattner3af10532006-05-05 06:39:07 +00003874 }
Chris Lattner3af10532006-05-05 06:39:07 +00003875
Chris Lattner15212982005-09-18 03:42:07 +00003876
Chris Lattner113f4f42002-06-25 16:13:24 +00003877 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003878}
3879
Chris Lattnerc2076352004-02-16 01:20:27 +00003880// XorSelf - Implements: X ^ X --> 0
3881struct XorSelf {
3882 Value *RHS;
3883 XorSelf(Value *rhs) : RHS(rhs) {}
3884 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3885 Instruction *apply(BinaryOperator &Xor) const {
3886 return &Xor;
3887 }
3888};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003889
3890
Chris Lattner113f4f42002-06-25 16:13:24 +00003891Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003892 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003894
Chris Lattner81a7a232004-10-16 18:11:37 +00003895 if (isa<UndefValue>(Op1))
3896 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3897
Chris Lattnerc2076352004-02-16 01:20:27 +00003898 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3899 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3900 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003901 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003902 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003903
3904 // See if we can simplify any instructions used by the instruction whose sole
3905 // purpose is to compute bits we don't care about.
3906 uint64_t KnownZero, KnownOne;
Reid Spencerd84d35b2007-02-15 02:26:10 +00003907 if (!isa<VectorType>(I.getType()) &&
Reid Spencera94d3942007-01-19 21:13:56 +00003908 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003909 KnownZero, KnownOne))
3910 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003911
Zhou Sheng75b871f2007-01-11 12:24:14 +00003912 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003913 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3914 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003915 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003916 return new ICmpInst(ICI->getInversePredicate(),
3917 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003918
Reid Spencer266e42b2006-12-23 06:05:41 +00003919 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003920 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003921 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3922 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003923 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3924 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003925 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003926 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003927 }
Chris Lattner023a4832004-06-18 06:07:51 +00003928
3929 // ~(~X & Y) --> (X | ~Y)
3930 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3931 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3932 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3933 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003934 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003935 Op0I->getOperand(1)->getName()+".not");
3936 InsertNewInstBefore(NotY, I);
3937 return BinaryOperator::createOr(Op0NotVal, NotY);
3938 }
3939 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003940
Chris Lattner97638592003-07-23 21:37:07 +00003941 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003942 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003943 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003944 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003945 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3946 return BinaryOperator::createSub(
3947 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003948 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003949 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003950 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003951 } else if (Op0I->getOpcode() == Instruction::Or) {
3952 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3953 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3954 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3955 // Anything in both C1 and C2 is known to be zero, remove it from
3956 // NewRHS.
3957 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3958 NewRHS = ConstantExpr::getAnd(NewRHS,
3959 ConstantExpr::getNot(CommonBits));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00003960 AddToWorkList(Op0I);
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003961 I.setOperand(0, Op0I->getOperand(0));
3962 I.setOperand(1, NewRHS);
3963 return &I;
3964 }
Chris Lattner97638592003-07-23 21:37:07 +00003965 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003966 }
Chris Lattner183b3362004-04-09 19:05:30 +00003967
3968 // Try to fold constant and into select arguments.
3969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003971 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003972 if (isa<PHINode>(Op0))
3973 if (Instruction *NV = FoldOpIntoPhi(I))
3974 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003975 }
3976
Chris Lattnerbb74e222003-03-10 23:06:50 +00003977 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003978 if (X == Op1)
3979 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003980 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003981
Chris Lattnerbb74e222003-03-10 23:06:50 +00003982 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003983 if (X == Op0)
3984 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003985 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003986
Chris Lattnerdcd07922006-04-01 08:03:55 +00003987 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003988 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003989 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003990 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003991 I.swapOperands();
3992 std::swap(Op0, Op1);
3993 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003994 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003995 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003996 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003997 } else if (Op1I->getOpcode() == Instruction::Xor) {
3998 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3999 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4000 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4001 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004002 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4003 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4004 Op1I->swapOperands();
4005 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4006 I.swapOperands(); // Simplified below.
4007 std::swap(Op0, Op1);
4008 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004009 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004010
Chris Lattnerdcd07922006-04-01 08:03:55 +00004011 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004012 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004013 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004014 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004015 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004016 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4017 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004018 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004019 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004020 } else if (Op0I->getOpcode() == Instruction::Xor) {
4021 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4022 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4023 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4024 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004025 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4026 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4027 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004028 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4029 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004030 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4031 InsertNewInstBefore(N, I);
4032 return BinaryOperator::createAnd(N, Op1);
4033 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004034 }
4035
Reid Spencer266e42b2006-12-23 06:05:41 +00004036 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4037 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4038 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004039 return R;
4040
Chris Lattner3af10532006-05-05 06:39:07 +00004041 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004042 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004043 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004044 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4045 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner03c49532007-01-15 02:27:26 +00004046 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer799b5bf2006-12-13 08:27:15 +00004047 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004048 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4049 I.getType(), TD) &&
4050 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4051 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004052 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4053 Op1C->getOperand(0),
4054 I.getName());
4055 InsertNewInstBefore(NewOp, I);
4056 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4057 }
Chris Lattner3af10532006-05-05 06:39:07 +00004058 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004059
4060 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
Reid Spencer2341c222007-02-02 02:16:23 +00004061 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4062 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4063 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004064 SI0->getOperand(1) == SI1->getOperand(1) &&
4065 (SI0->hasOneUse() || SI1->hasOneUse())) {
4066 Instruction *NewOp =
4067 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4068 SI1->getOperand(0),
4069 SI0->getName()), I);
Reid Spencer2341c222007-02-02 02:16:23 +00004070 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4071 SI1->getOperand(1));
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004072 }
4073 }
Chris Lattner3af10532006-05-05 06:39:07 +00004074
Chris Lattner113f4f42002-06-25 16:13:24 +00004075 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004076}
4077
Chris Lattner6862fbd2004-09-29 17:40:11 +00004078static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004079 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004080}
4081
4082/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4083/// overflowed for this type.
4084static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4085 ConstantInt *In2) {
4086 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4087
Reid Spencerc635f472006-12-31 05:48:39 +00004088 return cast<ConstantInt>(Result)->getZExtValue() <
4089 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004090}
4091
Chris Lattner0798af32005-01-13 20:14:25 +00004092/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4093/// code necessary to compute the offset from the base pointer (without adding
4094/// in the base pointer). Return the result as a signed integer of intptr size.
4095static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4096 TargetData &TD = IC.getTargetData();
4097 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004098 const Type *IntPtrTy = TD.getIntPtrType();
4099 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004100
4101 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004102 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004103
Chris Lattner0798af32005-01-13 20:14:25 +00004104 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4105 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004106 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004107 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004108 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4109 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004110 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004111 Scale = ConstantExpr::getMul(OpC, Scale);
4112 if (Constant *RC = dyn_cast<Constant>(Result))
4113 Result = ConstantExpr::getAdd(RC, Scale);
4114 else {
4115 // Emit an add instruction.
4116 Result = IC.InsertNewInstBefore(
4117 BinaryOperator::createAdd(Result, Scale,
4118 GEP->getName()+".offs"), I);
4119 }
4120 }
4121 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004122 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004123 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004124 Op->getName()+".c"), I);
4125 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004126 // We'll let instcombine(mul) convert this to a shl if possible.
4127 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4128 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004129
4130 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004131 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004132 GEP->getName()+".offs"), I);
4133 }
4134 }
4135 return Result;
4136}
4137
Reid Spencer266e42b2006-12-23 06:05:41 +00004138/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004139/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004140Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4141 ICmpInst::Predicate Cond,
4142 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004143 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004144
4145 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4146 if (isa<PointerType>(CI->getOperand(0)->getType()))
4147 RHS = CI->getOperand(0);
4148
Chris Lattner0798af32005-01-13 20:14:25 +00004149 Value *PtrBase = GEPLHS->getOperand(0);
4150 if (PtrBase == RHS) {
4151 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004152 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4153 // each index is zero or not.
4154 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004155 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004156 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4157 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004158 bool EmitIt = true;
4159 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4160 if (isa<UndefValue>(C)) // undef index -> undef.
4161 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4162 if (C->isNullValue())
4163 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004164 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4165 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004166 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004167 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004168 ConstantInt::get(Type::Int1Ty,
4169 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004170 }
4171
4172 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004173 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004174 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004175 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4176 if (InVal == 0)
4177 InVal = Comp;
4178 else {
4179 InVal = InsertNewInstBefore(InVal, I);
4180 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004181 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004182 InVal = BinaryOperator::createOr(InVal, Comp);
4183 else // True if all are equal
4184 InVal = BinaryOperator::createAnd(InVal, Comp);
4185 }
4186 }
4187 }
4188
4189 if (InVal)
4190 return InVal;
4191 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004192 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004193 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4194 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004195 }
Chris Lattner0798af32005-01-13 20:14:25 +00004196
Reid Spencer266e42b2006-12-23 06:05:41 +00004197 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004198 // the result to fold to a constant!
4199 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4200 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4201 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004202 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4203 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004204 }
4205 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004206 // If the base pointers are different, but the indices are the same, just
4207 // compare the base pointer.
4208 if (PtrBase != GEPRHS->getOperand(0)) {
4209 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004210 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004211 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004212 if (IndicesTheSame)
4213 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4214 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4215 IndicesTheSame = false;
4216 break;
4217 }
4218
4219 // If all indices are the same, just compare the base pointers.
4220 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004221 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4222 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004223
4224 // Otherwise, the base pointers are different and the indices are
4225 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004226 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004227 }
Chris Lattner0798af32005-01-13 20:14:25 +00004228
Chris Lattner81e84172005-01-13 22:25:21 +00004229 // If one of the GEPs has all zero indices, recurse.
4230 bool AllZeros = true;
4231 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4232 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4233 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4234 AllZeros = false;
4235 break;
4236 }
4237 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004238 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4239 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004240
4241 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004242 AllZeros = true;
4243 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4244 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4245 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4246 AllZeros = false;
4247 break;
4248 }
4249 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004250 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004251
Chris Lattner4fa89822005-01-14 00:20:05 +00004252 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4253 // If the GEPs only differ by one index, compare it.
4254 unsigned NumDifferences = 0; // Keep track of # differences.
4255 unsigned DiffOperand = 0; // The operand that differs.
4256 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4257 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004258 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4259 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004260 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004261 NumDifferences = 2;
4262 break;
4263 } else {
4264 if (NumDifferences++) break;
4265 DiffOperand = i;
4266 }
4267 }
4268
4269 if (NumDifferences == 0) // SAME GEP?
4270 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004271 ConstantInt::get(Type::Int1Ty,
4272 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004273 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004274 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4275 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004276 // Make sure we do a signed comparison here.
4277 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004278 }
4279 }
4280
Reid Spencer266e42b2006-12-23 06:05:41 +00004281 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004282 // the result to fold to a constant!
4283 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4284 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4285 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4286 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4287 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004288 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004289 }
4290 }
4291 return 0;
4292}
4293
Reid Spencer266e42b2006-12-23 06:05:41 +00004294Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4295 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004296 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004297
Chris Lattner6ee923f2007-01-14 19:42:17 +00004298 // Fold trivial predicates.
4299 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4300 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4301 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4302 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4303
4304 // Simplify 'fcmp pred X, X'
4305 if (Op0 == Op1) {
4306 switch (I.getPredicate()) {
4307 default: assert(0 && "Unknown predicate!");
4308 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4309 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4310 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4311 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4312 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4313 case FCmpInst::FCMP_OLT: // True if ordered and less than
4314 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4315 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4316
4317 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4318 case FCmpInst::FCMP_ULT: // True if unordered or less than
4319 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4320 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4321 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4322 I.setPredicate(FCmpInst::FCMP_UNO);
4323 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4324 return &I;
4325
4326 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4327 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4328 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4329 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4330 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4331 I.setPredicate(FCmpInst::FCMP_ORD);
4332 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4333 return &I;
4334 }
4335 }
4336
Reid Spencer266e42b2006-12-23 06:05:41 +00004337 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004338 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004339
Reid Spencer266e42b2006-12-23 06:05:41 +00004340 // Handle fcmp with constant RHS
4341 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4342 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4343 switch (LHSI->getOpcode()) {
4344 case Instruction::PHI:
4345 if (Instruction *NV = FoldOpIntoPhi(I))
4346 return NV;
4347 break;
4348 case Instruction::Select:
4349 // If either operand of the select is a constant, we can fold the
4350 // comparison into the select arms, which will cause one to be
4351 // constant folded and the select turned into a bitwise or.
4352 Value *Op1 = 0, *Op2 = 0;
4353 if (LHSI->hasOneUse()) {
4354 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4355 // Fold the known value into the constant operand.
4356 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4357 // Insert a new FCmp of the other select operand.
4358 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4359 LHSI->getOperand(2), RHSC,
4360 I.getName()), I);
4361 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4362 // Fold the known value into the constant operand.
4363 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4364 // Insert a new FCmp of the other select operand.
4365 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4366 LHSI->getOperand(1), RHSC,
4367 I.getName()), I);
4368 }
4369 }
4370
4371 if (Op1)
4372 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4373 break;
4374 }
4375 }
4376
4377 return Changed ? &I : 0;
4378}
4379
4380Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4381 bool Changed = SimplifyCompare(I);
4382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4383 const Type *Ty = Op0->getType();
4384
4385 // icmp X, X
4386 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004387 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4388 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004389
4390 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004391 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004392
4393 // icmp of GlobalValues can never equal each other as long as they aren't
4394 // external weak linkage type.
4395 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4396 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4397 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004398 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4399 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004400
4401 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004402 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004403 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4404 isa<ConstantPointerNull>(Op0)) &&
4405 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004406 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004407 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4408 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004409
Reid Spencer266e42b2006-12-23 06:05:41 +00004410 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004411 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004412 switch (I.getPredicate()) {
4413 default: assert(0 && "Invalid icmp instruction!");
4414 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004415 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004416 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004417 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004418 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004419 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004420 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004421
Reid Spencer266e42b2006-12-23 06:05:41 +00004422 case ICmpInst::ICMP_UGT:
4423 case ICmpInst::ICMP_SGT:
4424 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004425 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004426 case ICmpInst::ICMP_ULT:
4427 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004428 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4429 InsertNewInstBefore(Not, I);
4430 return BinaryOperator::createAnd(Not, Op1);
4431 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 case ICmpInst::ICMP_UGE:
4433 case ICmpInst::ICMP_SGE:
4434 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004435 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004436 case ICmpInst::ICMP_ULE:
4437 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004438 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4439 InsertNewInstBefore(Not, I);
4440 return BinaryOperator::createOr(Not, Op1);
4441 }
4442 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004443 }
4444
Chris Lattner2dd01742004-06-09 04:24:29 +00004445 // See if we are doing a comparison between a constant and an instruction that
4446 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004447 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004448 switch (I.getPredicate()) {
4449 default: break;
4450 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4451 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004452 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004453 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4454 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4455 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4456 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4457 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004458
Reid Spencer266e42b2006-12-23 06:05:41 +00004459 case ICmpInst::ICMP_SLT:
4460 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004461 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004462 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4463 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4464 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4465 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4466 break;
4467
4468 case ICmpInst::ICMP_UGT:
4469 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004470 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004471 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4472 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4473 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4474 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4475 break;
4476
4477 case ICmpInst::ICMP_SGT:
4478 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004479 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004480 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4481 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4482 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4483 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4484 break;
4485
4486 case ICmpInst::ICMP_ULE:
4487 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004488 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004489 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4490 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4491 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4492 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4493 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004494
Reid Spencer266e42b2006-12-23 06:05:41 +00004495 case ICmpInst::ICMP_SLE:
4496 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004497 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004498 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4499 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4500 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4501 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4502 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004503
Reid Spencer266e42b2006-12-23 06:05:41 +00004504 case ICmpInst::ICMP_UGE:
4505 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004506 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004507 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4508 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4509 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4510 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4511 break;
4512
4513 case ICmpInst::ICMP_SGE:
4514 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004515 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004516 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4517 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4518 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4519 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4520 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004521 }
4522
Reid Spencer266e42b2006-12-23 06:05:41 +00004523 // If we still have a icmp le or icmp ge instruction, turn it into the
4524 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004525 // already been handled above, this requires little checking.
4526 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004527 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4528 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4529 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4530 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4531 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4532 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4533 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4534 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004535
4536 // See if we can fold the comparison based on bits known to be zero or one
4537 // in the input.
4538 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00004539 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
Chris Lattneree0f2802006-02-12 02:07:56 +00004540 KnownZero, KnownOne, 0))
4541 return &I;
4542
4543 // Given the known and unknown bits, compute a range that the LHS could be
4544 // in.
4545 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004546 // Compute the Min, Max and RHS values based on the known bits. For the
4547 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004548 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4549 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4551 SRHSVal = CI->getSExtValue();
4552 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4553 SMax);
4554 } else {
4555 URHSVal = CI->getZExtValue();
4556 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4557 UMax);
4558 }
4559 switch (I.getPredicate()) { // LE/GE have been folded already.
4560 default: assert(0 && "Unknown icmp opcode!");
4561 case ICmpInst::ICMP_EQ:
4562 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004563 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004564 break;
4565 case ICmpInst::ICMP_NE:
4566 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004567 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004568 break;
4569 case ICmpInst::ICMP_ULT:
4570 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004571 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004572 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004573 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004574 break;
4575 case ICmpInst::ICMP_UGT:
4576 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004577 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004578 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004579 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004580 break;
4581 case ICmpInst::ICMP_SLT:
4582 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004583 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004584 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004585 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004586 break;
4587 case ICmpInst::ICMP_SGT:
4588 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004589 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004590 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004592 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004593 }
4594 }
4595
Reid Spencer266e42b2006-12-23 06:05:41 +00004596 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004597 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004598 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004599 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004600 switch (LHSI->getOpcode()) {
4601 case Instruction::And:
4602 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4603 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004604 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4605
Reid Spencer266e42b2006-12-23 06:05:41 +00004606 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004607 // and/compare to be the input width without changing the value
4608 // produced, eliminating a cast.
4609 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4610 // We can do this transformation if either the AND constant does not
4611 // have its sign bit set or if it is an equality comparison.
4612 // Extending a relational comparison when we're checking the sign
4613 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004614 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004615 (I.isEquality() ||
4616 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4617 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4618 ConstantInt *NewCST;
4619 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004620 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4621 AndCST->getZExtValue());
4622 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4623 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004624 Instruction *NewAnd =
4625 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4626 LHSI->getName());
4627 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004628 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004629 }
4630 }
4631
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004632 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4633 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4634 // happens a LOT in code produced by the C front-end, for bitfield
4635 // access.
Reid Spencer2341c222007-02-02 02:16:23 +00004636 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4637 if (Shift && !Shift->isShift())
4638 Shift = 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004639
Reid Spencere0fc4df2006-10-20 07:07:24 +00004640 ConstantInt *ShAmt;
4641 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004642 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4643 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004644
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004645 // We can fold this as long as we can't shift unknown bits
4646 // into the mask. This can only happen with signed shift
4647 // rights, as they sign-extend.
4648 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004649 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004650 if (!CanFold) {
4651 // To test for the bad case of the signed shr, see if any
4652 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004653 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004654 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4655
Reid Spencer2341c222007-02-02 02:16:23 +00004656 Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004657 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004658 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4659 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004660 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4661 CanFold = true;
4662 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004663
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004664 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004665 Constant *NewCst;
4666 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004667 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004668 else
4669 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004670
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004671 // Check to see if we are shifting out any of the bits being
4672 // compared.
4673 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4674 // If we shifted bits out, the fold is not going to work out.
4675 // As a special case, check to see if this means that the
4676 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004677 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004678 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004679 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004680 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004681 } else {
4682 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004683 Constant *NewAndCST;
4684 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004685 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004686 else
4687 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4688 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004689 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00004690 AddToWorkList(Shift); // Shift is dead.
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004691 AddUsesToWorkList(I);
4692 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004693 }
4694 }
Chris Lattner35167c32004-06-09 07:59:58 +00004695 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004696
4697 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4698 // preferable because it allows the C<<Y expression to be hoisted out
4699 // of a loop if Y is invariant and X is not.
4700 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004701 I.isEquality() && !Shift->isArithmeticShift() &&
4702 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004703 // Compute C << Y.
4704 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004705 if (Shift->getOpcode() == Instruction::LShr) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00004706 NS = BinaryOperator::createShl(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004707 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004708 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004709 // Insert a logical shift.
Reid Spencer0d5f9232007-02-02 14:08:20 +00004710 NS = BinaryOperator::createLShr(AndCST,
Reid Spencer2341c222007-02-02 02:16:23 +00004711 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004712 }
4713 InsertNewInstBefore(cast<Instruction>(NS), I);
4714
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004715 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004716 Instruction *NewAnd = BinaryOperator::createAnd(
4717 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004718 InsertNewInstBefore(NewAnd, I);
4719
4720 I.setOperand(0, NewAnd);
4721 return &I;
4722 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004723 }
4724 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004725
Reid Spencer266e42b2006-12-23 06:05:41 +00004726 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004727 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004728 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004729 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4730
4731 // Check that the shift amount is in range. If not, don't perform
4732 // undefined shifts. When the shift is visited it will be
4733 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004734 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004735 break;
4736
Chris Lattner272d5ca2004-09-28 18:22:15 +00004737 // If we are comparing against bits always shifted out, the
4738 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004739 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004740 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004741 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004742 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004743 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004744 return ReplaceInstUsesWith(I, Cst);
4745 }
4746
4747 if (LHSI->hasOneUse()) {
4748 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004749 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004750 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004751 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004752
Chris Lattner272d5ca2004-09-28 18:22:15 +00004753 Instruction *AndI =
4754 BinaryOperator::createAnd(LHSI->getOperand(0),
4755 Mask, LHSI->getName()+".mask");
4756 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004757 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004758 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004759 }
4760 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004761 }
4762 break;
4763
Reid Spencer266e42b2006-12-23 06:05:41 +00004764 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004765 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004766 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004767 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004768 // Check that the shift amount is in range. If not, don't perform
4769 // undefined shifts. When the shift is visited it will be
4770 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004771 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004772 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004773 break;
4774
Chris Lattner1023b872004-09-27 16:18:50 +00004775 // If we are comparing against bits always shifted out, the
4776 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004777 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004778 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004779 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4780 ShAmt);
4781 else
4782 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4783 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004784
Chris Lattner1023b872004-09-27 16:18:50 +00004785 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004786 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004787 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004788 return ReplaceInstUsesWith(I, Cst);
4789 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004790
Chris Lattner1023b872004-09-27 16:18:50 +00004791 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004792 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004793
Chris Lattner1023b872004-09-27 16:18:50 +00004794 // Otherwise strength reduce the shift into an and.
4795 uint64_t Val = ~0ULL; // All ones.
4796 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004797 Val &= ~0ULL >> (64-TypeBits);
4798 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004799
Chris Lattner1023b872004-09-27 16:18:50 +00004800 Instruction *AndI =
4801 BinaryOperator::createAnd(LHSI->getOperand(0),
4802 Mask, LHSI->getName()+".mask");
4803 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004804 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004805 ConstantExpr::getShl(CI, ShAmt));
4806 }
Chris Lattner1023b872004-09-27 16:18:50 +00004807 }
4808 }
4809 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004810
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004811 case Instruction::SDiv:
4812 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004813 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004814 // Fold this div into the comparison, producing a range check.
4815 // Determine, based on the divide type, what the range is being
4816 // checked. If there is an overflow on the low or high side, remember
4817 // it, otherwise compute the range [low, hi) bounding the new value.
4818 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004819 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004820 // FIXME: If the operand types don't match the type of the divide
4821 // then don't attempt this transform. The code below doesn't have the
4822 // logic to deal with a signed divide and an unsigned compare (and
4823 // vice versa). This is because (x /s C1) <s C2 produces different
4824 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4825 // (x /u C1) <u C2. Simply casting the operands and result won't
4826 // work. :( The if statement below tests that condition and bails
4827 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004828 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4829 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004830 break;
4831
4832 // Initialize the variables that will indicate the nature of the
4833 // range check.
4834 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004835 ConstantInt *LoBound = 0, *HiBound = 0;
4836
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004837 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4838 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4839 // C2 (CI). By solving for X we can turn this into a range check
4840 // instead of computing a divide.
4841 ConstantInt *Prod =
4842 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004843
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004844 // Determine if the product overflows by seeing if the product is
4845 // not equal to the divide. Make sure we do the same kind of divide
4846 // as in the LHS instruction that we're folding.
4847 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004848 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004849 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4850
Reid Spencer266e42b2006-12-23 06:05:41 +00004851 // Get the ICmp opcode
4852 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004853
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004854 if (DivRHS->isNullValue()) {
4855 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004856 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004857 LoBound = Prod;
4858 LoOverflow = ProdOV;
4859 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004860 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004861 if (CI->isNullValue()) { // (X / pos) op 0
4862 // Can't overflow.
4863 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4864 HiBound = DivRHS;
4865 } else if (isPositive(CI)) { // (X / pos) op pos
4866 LoBound = Prod;
4867 LoOverflow = ProdOV;
4868 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4869 } else { // (X / pos) op neg
4870 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4871 LoOverflow = AddWithOverflow(LoBound, Prod,
4872 cast<ConstantInt>(DivRHSH));
4873 HiBound = Prod;
4874 HiOverflow = ProdOV;
4875 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004876 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 if (CI->isNullValue()) { // (X / neg) op 0
4878 LoBound = AddOne(DivRHS);
4879 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004880 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004881 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004882 } else if (isPositive(CI)) { // (X / neg) op pos
4883 HiOverflow = LoOverflow = ProdOV;
4884 if (!LoOverflow)
4885 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4886 HiBound = AddOne(Prod);
4887 } else { // (X / neg) op neg
4888 LoBound = Prod;
4889 LoOverflow = HiOverflow = ProdOV;
4890 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4891 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004892
Chris Lattnera92af962004-10-11 19:40:04 +00004893 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004894 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004895 }
4896
4897 if (LoBound) {
4898 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004899 switch (predicate) {
4900 default: assert(0 && "Unhandled icmp opcode!");
4901 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004902 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004903 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004904 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4906 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004907 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004908 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4909 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004910 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004911 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4912 true, I);
4913 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004914 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004915 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004916 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004917 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4918 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004919 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004920 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4921 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004922 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004923 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4924 false, I);
4925 case ICmpInst::ICMP_ULT:
4926 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004927 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004928 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004929 return new ICmpInst(predicate, X, LoBound);
4930 case ICmpInst::ICMP_UGT:
4931 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004932 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004933 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004934 if (predicate == ICmpInst::ICMP_UGT)
4935 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4936 else
4937 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004938 }
4939 }
4940 }
4941 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004942 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004943
Reid Spencer266e42b2006-12-23 06:05:41 +00004944 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004945 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004946 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004947
Reid Spencere0fc4df2006-10-20 07:07:24 +00004948 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4949 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4951 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004952 case Instruction::SRem:
4953 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4954 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4955 BO->hasOneUse()) {
4956 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4957 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004958 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4959 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004960 return new ICmpInst(I.getPredicate(), NewRem,
4961 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004962 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004963 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004964 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004965 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004966 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4967 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004968 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004969 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4970 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004971 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004972 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4973 // efficiently invertible, or if the add has just this one use.
4974 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004975
Chris Lattnerc992add2003-08-13 05:33:12 +00004976 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004977 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004978 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004979 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004980 else if (BO->hasOneUse()) {
Chris Lattner6e0123b2007-02-11 01:23:03 +00004981 Instruction *Neg = BinaryOperator::createNeg(BOp1);
Chris Lattnerc992add2003-08-13 05:33:12 +00004982 InsertNewInstBefore(Neg, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00004983 Neg->takeName(BO);
Reid Spencer266e42b2006-12-23 06:05:41 +00004984 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004985 }
4986 }
4987 break;
4988 case Instruction::Xor:
4989 // For the xor case, we can xor two constants together, eliminating
4990 // the explicit xor.
4991 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004992 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4993 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004994
4995 // FALLTHROUGH
4996 case Instruction::Sub:
4997 // Replace (([sub|xor] A, B) != 0) with (A != B)
4998 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004999 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5000 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005001 break;
5002
5003 case Instruction::Or:
5004 // If bits are being or'd in that are not present in the constant we
5005 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005006 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005007 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005008 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005009 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5010 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005011 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005012 break;
5013
5014 case Instruction::And:
5015 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005016 // If bits are being compared against that are and'd out, then the
5017 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005018 if (!ConstantExpr::getAnd(CI,
5019 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00005020 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5021 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005022
Chris Lattner35167c32004-06-09 07:59:58 +00005023 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005024 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5026 ICmpInst::ICMP_NE, Op0,
5027 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005028
Reid Spencer266e42b2006-12-23 06:05:41 +00005029 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005030 if (isSignBit(BOC)) {
5031 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005032 Constant *Zero = Constant::getNullValue(X->getType());
5033 ICmpInst::Predicate pred = isICMP_NE ?
5034 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5035 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005037
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005038 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005039 if (CI->isNullValue() && isHighOnes(BOC)) {
5040 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005041 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005042 ICmpInst::Predicate pred = isICMP_NE ?
5043 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5044 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005045 }
5046
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005047 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005048 default: break;
5049 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005050 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5051 // Handle set{eq|ne} <intrinsic>, intcst.
5052 switch (II->getIntrinsicID()) {
5053 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005054 case Intrinsic::bswap_i16:
5055 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005056 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005057 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005058 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005059 ByteSwap_16(CI->getZExtValue())));
5060 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005061 case Intrinsic::bswap_i32:
5062 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005063 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005064 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005065 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005066 ByteSwap_32(CI->getZExtValue())));
5067 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005068 case Intrinsic::bswap_i64:
5069 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00005070 AddToWorkList(II); // Dead?
Chris Lattnera7942b72006-11-29 05:02:16 +00005071 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005072 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005073 ByteSwap_64(CI->getZExtValue())));
5074 return &I;
5075 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005076 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005077 } else { // Not a ICMP_EQ/ICMP_NE
5078 // If the LHS is a cast from an integral value of the same size, then
5079 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005080 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5081 Value *CastOp = Cast->getOperand(0);
5082 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005083 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner03c49532007-01-15 02:27:26 +00005084 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005085 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005086 // If this is an unsigned comparison, try to make the comparison use
5087 // smaller constant values.
5088 switch (I.getPredicate()) {
5089 default: break;
5090 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5091 ConstantInt *CUI = cast<ConstantInt>(CI);
5092 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5093 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
Reid Spencer24f1a0e2007-03-01 19:33:52 +00005094 ConstantInt::get(SrcTy, -1ULL));
Reid Spencer266e42b2006-12-23 06:05:41 +00005095 break;
5096 }
5097 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5098 ConstantInt *CUI = cast<ConstantInt>(CI);
5099 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5100 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5101 Constant::getNullValue(SrcTy));
5102 break;
5103 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005104 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005105
Chris Lattner2b55ea32004-02-23 07:16:20 +00005106 }
5107 }
Chris Lattnere967b342003-06-04 05:10:11 +00005108 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005109 }
5110
Reid Spencer266e42b2006-12-23 06:05:41 +00005111 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005112 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5113 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5114 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005115 case Instruction::GetElementPtr:
5116 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005117 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005118 bool isAllZeros = true;
5119 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5120 if (!isa<Constant>(LHSI->getOperand(i)) ||
5121 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5122 isAllZeros = false;
5123 break;
5124 }
5125 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005126 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005127 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5128 }
5129 break;
5130
Chris Lattner77c32c32005-04-23 15:31:55 +00005131 case Instruction::PHI:
5132 if (Instruction *NV = FoldOpIntoPhi(I))
5133 return NV;
5134 break;
5135 case Instruction::Select:
5136 // If either operand of the select is a constant, we can fold the
5137 // comparison into the select arms, which will cause one to be
5138 // constant folded and the select turned into a bitwise or.
5139 Value *Op1 = 0, *Op2 = 0;
5140 if (LHSI->hasOneUse()) {
5141 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5142 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005143 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5144 // Insert a new ICmp of the other select operand.
5145 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5146 LHSI->getOperand(2), RHSC,
5147 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005148 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5149 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005150 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5151 // Insert a new ICmp of the other select operand.
5152 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5153 LHSI->getOperand(1), RHSC,
5154 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005155 }
5156 }
Jeff Cohen82639852005-04-23 21:38:35 +00005157
Chris Lattner77c32c32005-04-23 15:31:55 +00005158 if (Op1)
5159 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5160 break;
5161 }
5162 }
5163
Reid Spencer266e42b2006-12-23 06:05:41 +00005164 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005165 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005166 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005167 return NI;
5168 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005169 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5170 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005171 return NI;
5172
Reid Spencer266e42b2006-12-23 06:05:41 +00005173 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005174 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5175 // now.
5176 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5177 if (isa<PointerType>(Op0->getType()) &&
5178 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005179 // We keep moving the cast from the left operand over to the right
5180 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005181 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005182
Chris Lattner64d87b02007-01-06 01:45:59 +00005183 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5184 // so eliminate it as well.
5185 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5186 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005187
Chris Lattner16930792003-11-03 04:25:02 +00005188 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005189 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005190 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005191 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005192 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005193 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005194 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005195 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005196 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005197 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005198 }
5199
5200 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005201 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005202 // This comes up when you have code like
5203 // int X = A < B;
5204 // if (X) ...
5205 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005206 // with a constant or another cast from the same type.
5207 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005208 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005209 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005210 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005211
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005212 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005213 Value *A, *B, *C, *D;
5214 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5215 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5216 Value *OtherVal = A == Op1 ? B : A;
5217 return new ICmpInst(I.getPredicate(), OtherVal,
5218 Constant::getNullValue(A->getType()));
5219 }
5220
5221 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5222 // A^c1 == C^c2 --> A == C^(c1^c2)
5223 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5224 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5225 if (Op1->hasOneUse()) {
5226 Constant *NC = ConstantExpr::getXor(C1, C2);
5227 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5228 return new ICmpInst(I.getPredicate(), A,
5229 InsertNewInstBefore(Xor, I));
5230 }
5231
5232 // A^B == A^D -> B == D
5233 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5234 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5235 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5236 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5237 }
5238 }
5239
5240 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5241 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005242 // A == (A^B) -> B == 0
5243 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005244 return new ICmpInst(I.getPredicate(), OtherVal,
5245 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005246 }
5247 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005248 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005249 return new ICmpInst(I.getPredicate(), B,
5250 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005251 }
5252 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005253 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005254 return new ICmpInst(I.getPredicate(), B,
5255 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005256 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005257
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005258 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5259 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5260 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5261 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5262 Value *X = 0, *Y = 0, *Z = 0;
5263
5264 if (A == C) {
5265 X = B; Y = D; Z = A;
5266 } else if (A == D) {
5267 X = B; Y = C; Z = A;
5268 } else if (B == C) {
5269 X = A; Y = D; Z = B;
5270 } else if (B == D) {
5271 X = A; Y = C; Z = B;
5272 }
5273
5274 if (X) { // Build (X^Y) & Z
5275 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5276 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5277 I.setOperand(0, Op1);
5278 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5279 return &I;
5280 }
5281 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005282 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005283 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005284}
5285
Reid Spencer266e42b2006-12-23 06:05:41 +00005286// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005287// We only handle extending casts so far.
5288//
Reid Spencer266e42b2006-12-23 06:05:41 +00005289Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5290 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005291 Value *LHSCIOp = LHSCI->getOperand(0);
5292 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005293 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005294 Value *RHSCIOp;
5295
Reid Spencer266e42b2006-12-23 06:05:41 +00005296 // We only handle extension cast instructions, so far. Enforce this.
5297 if (LHSCI->getOpcode() != Instruction::ZExt &&
5298 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005299 return 0;
5300
Reid Spencer266e42b2006-12-23 06:05:41 +00005301 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5302 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005303
Reid Spencer266e42b2006-12-23 06:05:41 +00005304 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005305 // Not an extension from the same type?
5306 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005307 if (RHSCIOp->getType() != LHSCIOp->getType())
5308 return 0;
Chris Lattner387bf3f2007-01-13 23:11:38 +00005309
5310 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5311 // and the other is a zext), then we can't handle this.
5312 if (CI->getOpcode() != LHSCI->getOpcode())
5313 return 0;
5314
5315 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5316 // then we can't handle this.
5317 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5318 return 0;
5319
5320 // Okay, just insert a compare of the reduced operands now!
5321 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005322 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005323
Reid Spencer266e42b2006-12-23 06:05:41 +00005324 // If we aren't dealing with a constant on the RHS, exit early
5325 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5326 if (!CI)
5327 return 0;
5328
5329 // Compute the constant that would happen if we truncated to SrcTy then
5330 // reextended to DestTy.
5331 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5332 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5333
5334 // If the re-extended constant didn't change...
5335 if (Res2 == CI) {
5336 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5337 // For example, we might have:
5338 // %A = sext short %X to uint
5339 // %B = icmp ugt uint %A, 1330
5340 // It is incorrect to transform this into
5341 // %B = icmp ugt short %X, 1330
5342 // because %A may have negative value.
5343 //
5344 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5345 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005346 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005347 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5348 else
5349 return 0;
5350 }
5351
5352 // The re-extended constant changed so the constant cannot be represented
5353 // in the shorter type. Consequently, we cannot emit a simple comparison.
5354
5355 // First, handle some easy cases. We know the result cannot be equal at this
5356 // point so handle the ICI.isEquality() cases
5357 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005358 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005359 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005360 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005361
5362 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5363 // should have been folded away previously and not enter in here.
5364 Value *Result;
5365 if (isSignedCmp) {
5366 // We're performing a signed comparison.
5367 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005368 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005369 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005370 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005371 } else {
5372 // We're performing an unsigned comparison.
5373 if (isSignedExt) {
5374 // We're performing an unsigned comp with a sign extended value.
5375 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005376 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005377 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5378 NegOne, ICI.getName()), ICI);
5379 } else {
5380 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005381 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005382 }
5383 }
5384
5385 // Finally, return the value computed.
5386 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5387 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5388 return ReplaceInstUsesWith(ICI, Result);
5389 } else {
5390 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5391 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5392 "ICmp should be folded!");
5393 if (Constant *CI = dyn_cast<Constant>(Result))
5394 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5395 else
5396 return BinaryOperator::createNot(Result);
5397 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005398}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005399
Reid Spencer2341c222007-02-02 02:16:23 +00005400Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5401 return commonShiftTransforms(I);
5402}
5403
5404Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5405 return commonShiftTransforms(I);
5406}
5407
5408Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5409 return commonShiftTransforms(I);
5410}
5411
5412Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5413 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner113f4f42002-06-25 16:13:24 +00005414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005415
5416 // shl X, 0 == X and shr X, 0 == X
5417 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer2341c222007-02-02 02:16:23 +00005418 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005419 Op0 == Constant::getNullValue(Op0->getType()))
5420 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005421
Reid Spencer266e42b2006-12-23 06:05:41 +00005422 if (isa<UndefValue>(Op0)) {
5423 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005424 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005425 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005426 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5427 }
5428 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005429 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5430 return ReplaceInstUsesWith(I, Op0);
5431 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005433 }
5434
Chris Lattnerd4dee402006-11-10 23:38:52 +00005435 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5436 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005437 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005438 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005439 return ReplaceInstUsesWith(I, CSI);
5440
Chris Lattner183b3362004-04-09 19:05:30 +00005441 // Try to fold constant and into select arguments.
5442 if (isa<Constant>(Op0))
5443 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005444 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005445 return R;
5446
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005447 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005448 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005449 if (MaskedValueIsZero(Op0,
5450 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005451 return BinaryOperator::createLShr(Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005452 }
5453 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005454
Reid Spencere0fc4df2006-10-20 07:07:24 +00005455 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005456 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5457 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005458 return 0;
5459}
5460
Reid Spencere0fc4df2006-10-20 07:07:24 +00005461Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer2341c222007-02-02 02:16:23 +00005462 BinaryOperator &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005463 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner14553932006-01-06 07:12:35 +00005464
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005465 // See if we can simplify any instructions used by the instruction whose sole
5466 // purpose is to compute bits we don't care about.
5467 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00005468 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005469 KnownZero, KnownOne))
5470 return &I;
5471
Chris Lattner14553932006-01-06 07:12:35 +00005472 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5473 // of a signed value.
5474 //
5475 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005476 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005477 if (I.getOpcode() != Instruction::AShr)
Chris Lattner14553932006-01-06 07:12:35 +00005478 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5479 else {
Chris Lattnerd5fea612007-02-02 05:29:55 +00005480 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005481 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005482 }
Chris Lattner14553932006-01-06 07:12:35 +00005483 }
5484
5485 // ((X*C1) << C2) == (X * (C1 << C2))
5486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5487 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5488 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5489 return BinaryOperator::createMul(BO->getOperand(0),
5490 ConstantExpr::getShl(BOOp, Op1));
5491
5492 // Try to fold constant and into select arguments.
5493 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5494 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5495 return R;
5496 if (isa<PHINode>(Op0))
5497 if (Instruction *NV = FoldOpIntoPhi(I))
5498 return NV;
5499
5500 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005501 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5502 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5503 Value *V1, *V2;
5504 ConstantInt *CC;
5505 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005506 default: break;
5507 case Instruction::Add:
5508 case Instruction::And:
5509 case Instruction::Or:
Reid Spencer2f34b982007-02-02 14:41:37 +00005510 case Instruction::Xor: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005511 // These operators commute.
5512 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005513 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5514 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005515 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005516 Instruction *YS = BinaryOperator::createShl(
Chris Lattner14553932006-01-06 07:12:35 +00005517 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005518 Op0BO->getName());
5519 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005520 Instruction *X =
5521 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5522 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005523 InsertNewInstBefore(X, I); // (X + (Y << C))
5524 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005525 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005526 return BinaryOperator::createAnd(X, C2);
5527 }
Chris Lattner14553932006-01-06 07:12:35 +00005528
Chris Lattner797dee72005-09-18 06:30:59 +00005529 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencer2f34b982007-02-02 14:41:37 +00005530 Value *Op0BOOp1 = Op0BO->getOperand(1);
5531 if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5532 match(Op0BOOp1,
5533 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5534 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005535 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005536 Op0BO->getOperand(0), Op1,
5537 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005538 InsertNewInstBefore(YS, I); // (Y << C)
5539 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005540 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005541 V1->getName()+".mask");
5542 InsertNewInstBefore(XM, I); // X & (CC << C)
5543
5544 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5545 }
Reid Spencer2f34b982007-02-02 14:41:37 +00005546 }
Chris Lattner14553932006-01-06 07:12:35 +00005547
Reid Spencer2f34b982007-02-02 14:41:37 +00005548 // FALL THROUGH.
5549 case Instruction::Sub: {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005550 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005551 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5552 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005553 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005554 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005555 Op0BO->getOperand(1), Op1,
5556 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005557 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005558 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005559 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005560 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005561 InsertNewInstBefore(X, I); // (X + (Y << C))
5562 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005563 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005564 return BinaryOperator::createAnd(X, C2);
5565 }
Chris Lattner14553932006-01-06 07:12:35 +00005566
Chris Lattner1df0e982006-05-31 21:14:00 +00005567 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005568 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5569 match(Op0BO->getOperand(0),
5570 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005571 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005572 cast<BinaryOperator>(Op0BO->getOperand(0))
5573 ->getOperand(0)->hasOneUse()) {
Reid Spencer0d5f9232007-02-02 14:08:20 +00005574 Instruction *YS = BinaryOperator::createShl(
Reid Spencer2341c222007-02-02 02:16:23 +00005575 Op0BO->getOperand(1), Op1,
5576 Op0BO->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005577 InsertNewInstBefore(YS, I); // (Y << C)
5578 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005579 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005580 V1->getName()+".mask");
5581 InsertNewInstBefore(XM, I); // X & (CC << C)
5582
Chris Lattner1df0e982006-05-31 21:14:00 +00005583 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005584 }
Chris Lattner14553932006-01-06 07:12:35 +00005585
Chris Lattner27cb9db2005-09-18 05:12:10 +00005586 break;
Reid Spencer2f34b982007-02-02 14:41:37 +00005587 }
Chris Lattner14553932006-01-06 07:12:35 +00005588 }
5589
5590
5591 // If the operand is an bitwise operator with a constant RHS, and the
5592 // shift is the only use, we can pull it out of the shift.
5593 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5594 bool isValid = true; // Valid only for And, Or, Xor
5595 bool highBitSet = false; // Transform if high bit of constant set?
5596
5597 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005598 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005599 case Instruction::Add:
5600 isValid = isLeftShift;
5601 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005602 case Instruction::Or:
5603 case Instruction::Xor:
5604 highBitSet = false;
5605 break;
5606 case Instruction::And:
5607 highBitSet = true;
5608 break;
Chris Lattner14553932006-01-06 07:12:35 +00005609 }
5610
5611 // If this is a signed shift right, and the high bit is modified
5612 // by the logical operation, do not perform the transformation.
5613 // The highBitSet boolean indicates the value of the high bit of
5614 // the constant which would cause it to be modified for this
5615 // operation.
5616 //
Chris Lattner3e009e82007-02-05 00:57:54 +00005617 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005618 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005619 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5620 }
5621
5622 if (isValid) {
5623 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5624
5625 Instruction *NewShift =
Chris Lattner6e0123b2007-02-11 01:23:03 +00005626 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner14553932006-01-06 07:12:35 +00005627 InsertNewInstBefore(NewShift, I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005628 NewShift->takeName(Op0BO);
Chris Lattner14553932006-01-06 07:12:35 +00005629
5630 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5631 NewRHS);
5632 }
5633 }
5634 }
5635 }
5636
Chris Lattnereb372a02006-01-06 07:52:12 +00005637 // Find out if this is a shift of a shift by a constant.
Reid Spencer2341c222007-02-02 02:16:23 +00005638 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5639 if (ShiftOp && !ShiftOp->isShift())
5640 ShiftOp = 0;
Chris Lattnereb372a02006-01-06 07:52:12 +00005641
Reid Spencere0fc4df2006-10-20 07:07:24 +00005642 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005643 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Reid Spencere0fc4df2006-10-20 07:07:24 +00005644 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5645 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattner3e009e82007-02-05 00:57:54 +00005646 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5647 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5648 Value *X = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005649
Chris Lattner3e009e82007-02-05 00:57:54 +00005650 unsigned AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5651 if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5652 AmtSum = I.getType()->getPrimitiveSizeInBits();
5653
5654 const IntegerType *Ty = cast<IntegerType>(I.getType());
5655
5656 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner6c344e52007-02-03 23:28:07 +00005657 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner3e009e82007-02-05 00:57:54 +00005658 return BinaryOperator::create(I.getOpcode(), X,
5659 ConstantInt::get(Ty, AmtSum));
5660 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5661 I.getOpcode() == Instruction::AShr) {
5662 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5663 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5664 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5665 I.getOpcode() == Instruction::LShr) {
5666 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5667 Instruction *Shift =
5668 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5669 InsertNewInstBefore(Shift, I);
5670
5671 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5672 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005673 }
5674
Chris Lattner3e009e82007-02-05 00:57:54 +00005675 // Okay, if we get here, one shift must be left, and the other shift must be
5676 // right. See if the amounts are equal.
5677 if (ShiftAmt1 == ShiftAmt2) {
5678 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5679 if (I.getOpcode() == Instruction::Shl) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005680 uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005681 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5682 }
5683 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5684 if (I.getOpcode() == Instruction::LShr) {
Chris Lattner0a28e902007-02-05 04:09:35 +00005685 uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
Chris Lattner3e009e82007-02-05 00:57:54 +00005686 return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5687 }
5688 // We can simplify ((X << C) >>s C) into a trunc + sext.
5689 // NOTE: we could do this for any C, but that would make 'unusual' integer
5690 // types. For now, just stick to ones well-supported by the code
5691 // generators.
5692 const Type *SExtType = 0;
5693 switch (Ty->getBitWidth() - ShiftAmt1) {
5694 case 8 : SExtType = Type::Int8Ty; break;
5695 case 16: SExtType = Type::Int16Ty; break;
5696 case 32: SExtType = Type::Int32Ty; break;
5697 default: break;
5698 }
5699 if (SExtType) {
5700 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5701 InsertNewInstBefore(NewTrunc, I);
5702 return new SExtInst(NewTrunc, Ty);
5703 }
5704 // Otherwise, we can't handle it yet.
5705 } else if (ShiftAmt1 < ShiftAmt2) {
5706 unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnereb372a02006-01-06 07:52:12 +00005707
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005708 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005709 if (I.getOpcode() == Instruction::Shl) {
5710 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5711 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005712 Instruction *Shift =
Chris Lattner3e009e82007-02-05 00:57:54 +00005713 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005714 InsertNewInstBefore(Shift, I);
5715
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005716 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005717 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattnereb372a02006-01-06 07:52:12 +00005718 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005719
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005720 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005721 if (I.getOpcode() == Instruction::LShr) {
5722 assert(ShiftOp->getOpcode() == Instruction::Shl);
5723 Instruction *Shift =
5724 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5725 InsertNewInstBefore(Shift, I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005726
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005727 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
Chris Lattner3e009e82007-02-05 00:57:54 +00005728 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
Chris Lattner27cb9db2005-09-18 05:12:10 +00005729 }
Chris Lattner3e009e82007-02-05 00:57:54 +00005730
5731 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5732 } else {
5733 assert(ShiftAmt2 < ShiftAmt1);
5734 unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5735
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005736 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005737 if (I.getOpcode() == Instruction::Shl) {
5738 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5739 ShiftOp->getOpcode() == Instruction::AShr);
5740 Instruction *Shift =
5741 BinaryOperator::create(ShiftOp->getOpcode(), X,
5742 ConstantInt::get(Ty, ShiftDiff));
5743 InsertNewInstBefore(Shift, I);
5744
5745 uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5746 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5747 }
5748
Chris Lattner83ac5ae92007-02-05 05:57:49 +00005749 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattner3e009e82007-02-05 00:57:54 +00005750 if (I.getOpcode() == Instruction::LShr) {
5751 assert(ShiftOp->getOpcode() == Instruction::Shl);
5752 Instruction *Shift =
5753 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5754 InsertNewInstBefore(Shift, I);
5755
5756 uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5757 return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5758 }
5759
5760 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner86102b82005-01-01 16:22:27 +00005761 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005762 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005763 return 0;
5764}
5765
Chris Lattner48a44f72002-05-02 17:06:02 +00005766
Chris Lattner8f663e82005-10-29 04:36:15 +00005767/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5768/// expression. If so, decompose it, returning some value X, such that Val is
5769/// X*Scale+Offset.
5770///
5771static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5772 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005773 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005774 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005775 Offset = CI->getZExtValue();
5776 Scale = 1;
5777 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005778 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5779 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005780 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005781 if (I->getOpcode() == Instruction::Shl) {
5782 // This is a value scaled by '1 << the shift amt'.
5783 Scale = 1U << CUI->getZExtValue();
5784 Offset = 0;
5785 return I->getOperand(0);
5786 } else if (I->getOpcode() == Instruction::Mul) {
5787 // This value is scaled by 'CUI'.
5788 Scale = CUI->getZExtValue();
5789 Offset = 0;
5790 return I->getOperand(0);
5791 } else if (I->getOpcode() == Instruction::Add) {
5792 // We have X+C. Check to see if we really have (X*C2)+C1,
5793 // where C1 is divisible by C2.
5794 unsigned SubScale;
5795 Value *SubVal =
5796 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5797 Offset += CUI->getZExtValue();
5798 if (SubScale > 1 && (Offset % SubScale == 0)) {
5799 Scale = SubScale;
5800 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005801 }
5802 }
5803 }
5804 }
5805 }
5806
5807 // Otherwise, we can't look past this.
5808 Scale = 1;
5809 Offset = 0;
5810 return Val;
5811}
5812
5813
Chris Lattner216be912005-10-24 06:03:58 +00005814/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5815/// try to eliminate the cast by moving the type information into the alloc.
5816Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5817 AllocationInst &AI) {
5818 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005819 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005820
Chris Lattnerac87beb2005-10-24 06:22:12 +00005821 // Remove any uses of AI that are dead.
5822 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner99c6cf62007-02-15 22:52:10 +00005823
Chris Lattnerac87beb2005-10-24 06:22:12 +00005824 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5825 Instruction *User = cast<Instruction>(*UI++);
5826 if (isInstructionTriviallyDead(User)) {
5827 while (UI != E && *UI == User)
5828 ++UI; // If this instruction uses AI more than once, don't break UI.
5829
Chris Lattnerac87beb2005-10-24 06:22:12 +00005830 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005831 DOUT << "IC: DCE: " << *User;
Chris Lattner51f54572007-03-02 19:59:19 +00005832 EraseInstFromFunction(*User);
Chris Lattnerac87beb2005-10-24 06:22:12 +00005833 }
5834 }
5835
Chris Lattner216be912005-10-24 06:03:58 +00005836 // Get the type really allocated and the type casted to.
5837 const Type *AllocElTy = AI.getAllocatedType();
5838 const Type *CastElTy = PTy->getElementType();
5839 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005840
Chris Lattner945e4372007-02-14 05:52:17 +00005841 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5842 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005843 if (CastElTyAlign < AllocElTyAlign) return 0;
5844
Chris Lattner46705b22005-10-24 06:35:18 +00005845 // If the allocation has multiple uses, only promote it if we are strictly
5846 // increasing the alignment of the resultant allocation. If we keep it the
5847 // same, we open the door to infinite loops of various kinds.
5848 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5849
Chris Lattner216be912005-10-24 06:03:58 +00005850 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5851 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005852 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005853
Chris Lattner8270c332005-10-29 03:19:53 +00005854 // See if we can satisfy the modulus by pulling a scale out of the array
5855 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005856 unsigned ArraySizeScale, ArrayOffset;
5857 Value *NumElements = // See if the array size is a decomposable linear expr.
5858 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5859
Chris Lattner8270c332005-10-29 03:19:53 +00005860 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5861 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005862 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5863 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005864
Chris Lattner8270c332005-10-29 03:19:53 +00005865 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5866 Value *Amt = 0;
5867 if (Scale == 1) {
5868 Amt = NumElements;
5869 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005870 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005871 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5872 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005873 Amt = ConstantExpr::getMul(
5874 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5875 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005876 else if (Scale != 1) {
5877 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5878 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005879 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005880 }
5881
Chris Lattner8f663e82005-10-29 04:36:15 +00005882 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005883 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005884 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5885 Amt = InsertNewInstBefore(Tmp, AI);
5886 }
5887
Chris Lattner216be912005-10-24 06:03:58 +00005888 AllocationInst *New;
5889 if (isa<MallocInst>(AI))
Chris Lattner6e0123b2007-02-11 01:23:03 +00005890 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005891 else
Chris Lattner6e0123b2007-02-11 01:23:03 +00005892 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattner216be912005-10-24 06:03:58 +00005893 InsertNewInstBefore(New, AI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00005894 New->takeName(&AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005895
5896 // If the allocation has multiple uses, insert a cast and change all things
5897 // that used it to use the new cast. This will also hack on CI, but it will
5898 // die soon.
5899 if (!AI.hasOneUse()) {
5900 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005901 // New is the allocation instruction, pointer typed. AI is the original
5902 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5903 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005904 InsertNewInstBefore(NewCast, AI);
5905 AI.replaceAllUsesWith(NewCast);
5906 }
Chris Lattner216be912005-10-24 06:03:58 +00005907 return ReplaceInstUsesWith(CI, New);
5908}
5909
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005910/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005911/// and return it as type Ty without inserting any new casts and without
5912/// changing the computed value. This is used by code that tries to decide
5913/// whether promoting or shrinking integer operations to wider or smaller types
5914/// will allow us to eliminate a truncate or extend.
5915///
5916/// This is a truncation operation if Ty is smaller than V->getType(), or an
5917/// extension operation if Ty is larger.
5918static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005919 int &NumCastsRemoved) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005920 // We can always evaluate constants in another type.
5921 if (isa<ConstantInt>(V))
5922 return true;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005923
5924 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005925 if (!I) return false;
5926
5927 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005928
5929 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005930 case Instruction::Add:
5931 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005932 case Instruction::And:
5933 case Instruction::Or:
5934 case Instruction::Xor:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005935 if (!I->hasOneUse()) return false;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005936 // These operators can all arbitrarily be extended or truncated.
5937 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5938 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005939
Chris Lattner960acb02006-11-29 07:18:39 +00005940 case Instruction::Shl:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005941 if (!I->hasOneUse()) return false;
5942 // If we are truncating the result of this SHL, and if it's a shift of a
5943 // constant amount, we can always perform a SHL in a smaller type.
5944 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5945 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5946 CI->getZExtValue() < Ty->getBitWidth())
5947 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
5948 }
5949 break;
5950 case Instruction::LShr:
5951 if (!I->hasOneUse()) return false;
5952 // If this is a truncate of a logical shr, we can truncate it to a smaller
5953 // lshr iff we know that the bits we would otherwise be shifting in are
5954 // already zeros.
5955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5956 if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
5957 MaskedValueIsZero(I->getOperand(0),
5958 OrigTy->getBitMask() & ~Ty->getBitMask()) &&
5959 CI->getZExtValue() < Ty->getBitWidth()) {
5960 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5961 }
5962 }
Chris Lattner960acb02006-11-29 07:18:39 +00005963 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005964 case Instruction::Trunc:
5965 case Instruction::ZExt:
5966 case Instruction::SExt:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005967 // If this is a cast from the destination type, we can trivially eliminate
5968 // it, and this will remove a cast overall.
5969 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005970 // If the first operand is itself a cast, and is eliminable, do not count
5971 // this as an eliminable cast. We would prefer to eliminate those two
5972 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005973 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005974 return true;
5975
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005976 ++NumCastsRemoved;
5977 return true;
5978 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005979 break;
5980 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005981 // TODO: Can handle more cases here.
5982 break;
5983 }
5984
5985 return false;
5986}
5987
5988/// EvaluateInDifferentType - Given an expression that
5989/// CanEvaluateInDifferentType returns true for, actually insert the code to
5990/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005991Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerda1d04a2007-03-03 05:27:34 +00005992 bool isSigned) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005993 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005994 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005995
5996 // Otherwise, it must be an instruction.
5997 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005998 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005999 switch (I->getOpcode()) {
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006000 case Instruction::Add:
6001 case Instruction::Sub:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006002 case Instruction::And:
6003 case Instruction::Or:
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006004 case Instruction::Xor:
Chris Lattner960acb02006-11-29 07:18:39 +00006005 case Instruction::AShr:
6006 case Instruction::LShr:
6007 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00006008 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006009 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6010 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6011 LHS, RHS, I->getName());
Chris Lattner960acb02006-11-29 07:18:39 +00006012 break;
6013 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006014 case Instruction::Trunc:
6015 case Instruction::ZExt:
6016 case Instruction::SExt:
6017 case Instruction::BitCast:
6018 // If the source type of the cast is the type we're trying for then we can
6019 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006020 if (I->getOperand(0)->getType() == Ty)
6021 return I->getOperand(0);
6022
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006023 // Some other kind of cast, which shouldn't happen, so just ..
6024 // FALL THROUGH
6025 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00006026 // TODO: Can handle more cases here.
6027 assert(0 && "Unreachable!");
6028 break;
6029 }
6030
6031 return InsertNewInstBefore(Res, *I);
6032}
6033
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006034/// @brief Implement the transforms common to all CastInst visitors.
6035Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00006036 Value *Src = CI.getOperand(0);
6037
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006038 // Casting undef to anything results in undef so might as just replace it and
6039 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00006040 if (isa<UndefValue>(Src)) // cast undef -> undef
6041 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6042
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006043 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6044 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00006045 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006046 if (Instruction::CastOps opc =
6047 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6048 // The first cast (CSrc) is eliminable so we need to fix up or replace
6049 // the second cast (CI). CSrc will then have a good chance of being dead.
6050 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006051 }
6052 }
Chris Lattner03841652004-05-25 04:29:21 +00006053
Chris Lattnerd0d51602003-06-21 23:12:02 +00006054 // If casting the result of a getelementptr instruction with no offset, turn
6055 // this into a cast of the original pointer!
6056 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006057 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006058 bool AllZeroOperands = true;
6059 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6060 if (!isa<Constant>(GEP->getOperand(i)) ||
6061 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6062 AllZeroOperands = false;
6063 break;
6064 }
6065 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006066 // Changing the cast operand is usually not a good idea but it is safe
6067 // here because the pointer operand is being replaced with another
6068 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006069 CI.setOperand(0, GEP->getOperand(0));
6070 return &CI;
6071 }
6072 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006073
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006074 // If we are casting a malloc or alloca to a pointer to a type of the same
6075 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006076 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006077 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6078 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006079
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006080 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006081 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6082 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6083 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006084
6085 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006086 if (isa<PHINode>(Src))
6087 if (Instruction *NV = FoldOpIntoPhi(CI))
6088 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006089
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006090 return 0;
6091}
6092
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006093/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6094/// integer types. This function implements the common transforms for all those
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006095/// cases.
6096/// @brief Implement the transforms common to CastInst with integer operands
6097Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6098 if (Instruction *Result = commonCastTransforms(CI))
6099 return Result;
6100
6101 Value *Src = CI.getOperand(0);
6102 const Type *SrcTy = Src->getType();
6103 const Type *DestTy = CI.getType();
6104 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6105 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6106
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006107 // See if we can simplify any instructions used by the LHS whose sole
6108 // purpose is to compute bits we don't care about.
6109 uint64_t KnownZero = 0, KnownOne = 0;
Reid Spencera94d3942007-01-19 21:13:56 +00006110 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006111 KnownZero, KnownOne))
6112 return &CI;
6113
6114 // If the source isn't an instruction or has more than one use then we
6115 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006116 Instruction *SrcI = dyn_cast<Instruction>(Src);
6117 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006118 return 0;
6119
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006120 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006121 int NumCastsRemoved = 0;
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006122 if (!isa<BitCastInst>(CI) &&
6123 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6124 NumCastsRemoved)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006125 // If this cast is a truncate, evaluting in a different type always
6126 // eliminates the cast, so it is always a win. If this is a noop-cast
6127 // this just removes a noop cast which isn't pointful, but simplifies
6128 // the code. If this is a zero-extension, we need to do an AND to
6129 // maintain the clear top-part of the computation, so we require that
6130 // the input have eliminated at least one cast. If this is a sign
6131 // extension, we insert two new casts (to do the extension) so we
6132 // require that two casts have been eliminated.
Chris Lattnerda1d04a2007-03-03 05:27:34 +00006133 bool DoXForm;
6134 switch (CI.getOpcode()) {
6135 default:
6136 // All the others use floating point so we shouldn't actually
6137 // get here because of the check above.
6138 assert(0 && "Unknown cast type");
6139 case Instruction::Trunc:
6140 DoXForm = true;
6141 break;
6142 case Instruction::ZExt:
6143 DoXForm = NumCastsRemoved >= 1;
6144 break;
6145 case Instruction::SExt:
6146 DoXForm = NumCastsRemoved >= 2;
6147 break;
6148 case Instruction::BitCast:
6149 DoXForm = false;
6150 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006151 }
6152
6153 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006154 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6155 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006156 assert(Res->getType() == DestTy);
6157 switch (CI.getOpcode()) {
6158 default: assert(0 && "Unknown cast type!");
6159 case Instruction::Trunc:
6160 case Instruction::BitCast:
6161 // Just replace this cast with the result.
6162 return ReplaceInstUsesWith(CI, Res);
6163 case Instruction::ZExt: {
6164 // We need to emit an AND to clear the high bits.
6165 assert(SrcBitSize < DestBitSize && "Not a zext?");
6166 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006167 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006168 if (DestBitSize < 64)
6169 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006170 return BinaryOperator::createAnd(Res, C);
6171 }
6172 case Instruction::SExt:
6173 // We need to emit a cast to truncate, then a cast to sext.
6174 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006175 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6176 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006177 }
6178 }
6179 }
6180
6181 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6182 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6183
6184 switch (SrcI->getOpcode()) {
6185 case Instruction::Add:
6186 case Instruction::Mul:
6187 case Instruction::And:
6188 case Instruction::Or:
6189 case Instruction::Xor:
6190 // If we are discarding information, or just changing the sign,
6191 // rewrite.
6192 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6193 // Don't insert two casts if they cannot be eliminated. We allow
6194 // two casts to be inserted if the sizes are the same. This could
6195 // only be converting signedness, which is a noop.
6196 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006197 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6198 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006199 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006200 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6201 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6202 return BinaryOperator::create(
6203 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006204 }
6205 }
6206
6207 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6208 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6209 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006210 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006211 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006212 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006213 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6214 }
6215 break;
6216 case Instruction::SDiv:
6217 case Instruction::UDiv:
6218 case Instruction::SRem:
6219 case Instruction::URem:
6220 // If we are just changing the sign, rewrite.
6221 if (DestBitSize == SrcBitSize) {
6222 // Don't insert two casts if they cannot be eliminated. We allow
6223 // two casts to be inserted if the sizes are the same. This could
6224 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006225 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6226 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006227 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6228 Op0, DestTy, SrcI);
6229 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6230 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006231 return BinaryOperator::create(
6232 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6233 }
6234 }
6235 break;
6236
6237 case Instruction::Shl:
6238 // Allow changing the sign of the source operand. Do not allow
6239 // changing the size of the shift, UNLESS the shift amount is a
6240 // constant. We must not change variable sized shifts to a smaller
6241 // size, because it is undefined to shift more bits out than exist
6242 // in the value.
6243 if (DestBitSize == SrcBitSize ||
6244 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006245 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6246 Instruction::BitCast : Instruction::Trunc);
6247 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer2341c222007-02-02 02:16:23 +00006248 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006249 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006250 }
6251 break;
6252 case Instruction::AShr:
6253 // If this is a signed shr, and if all bits shifted in are about to be
6254 // truncated off, turn it into an unsigned shr to allow greater
6255 // simplifications.
6256 if (DestBitSize < SrcBitSize &&
6257 isa<ConstantInt>(Op1)) {
6258 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6259 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6260 // Insert the new logical shift right.
Reid Spencer0d5f9232007-02-02 14:08:20 +00006261 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006262 }
6263 }
6264 break;
6265
Reid Spencer266e42b2006-12-23 06:05:41 +00006266 case Instruction::ICmp:
6267 // If we are just checking for a icmp eq of a single bit and casting it
6268 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006269 // cast to integer to avoid the comparison.
6270 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6271 uint64_t Op1CV = Op1C->getZExtValue();
6272 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6273 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6274 // cast (X == 1) to int --> X iff X has only the low bit set.
6275 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6276 // cast (X != 0) to int --> X iff X has only the low bit set.
6277 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6278 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6279 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6280 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6281 // If Op1C some other power of two, convert:
6282 uint64_t KnownZero, KnownOne;
Reid Spencera94d3942007-01-19 21:13:56 +00006283 uint64_t TypeMask = Op1C->getType()->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006284 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006285
6286 // This only works for EQ and NE
6287 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6288 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6289 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006290
6291 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006292 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006293 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6294 // (X&4) == 2 --> false
6295 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006296 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006297 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006298 return ReplaceInstUsesWith(CI, Res);
6299 }
6300
6301 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6302 Value *In = Op0;
6303 if (ShiftAmt) {
6304 // Perform a logical shr by shiftamt.
6305 // Insert the shift to put the result in the low bit.
6306 In = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006307 BinaryOperator::createLShr(In,
Reid Spencer2341c222007-02-02 02:16:23 +00006308 ConstantInt::get(In->getType(), ShiftAmt),
6309 In->getName()+".lobit"), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006310 }
6311
Reid Spencer266e42b2006-12-23 06:05:41 +00006312 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006313 Constant *One = ConstantInt::get(In->getType(), 1);
6314 In = BinaryOperator::createXor(In, One, "tmp");
6315 InsertNewInstBefore(cast<Instruction>(In), CI);
6316 }
6317
6318 if (CI.getType() == In->getType())
6319 return ReplaceInstUsesWith(CI, In);
6320 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006321 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006322 }
6323 }
6324 }
6325 break;
6326 }
6327 return 0;
6328}
6329
6330Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006331 if (Instruction *Result = commonIntCastTransforms(CI))
6332 return Result;
6333
6334 Value *Src = CI.getOperand(0);
6335 const Type *Ty = CI.getType();
6336 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6337
6338 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6339 switch (SrcI->getOpcode()) {
6340 default: break;
6341 case Instruction::LShr:
6342 // We can shrink lshr to something smaller if we know the bits shifted in
6343 // are already zeros.
6344 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6345 unsigned ShAmt = ShAmtV->getZExtValue();
6346
6347 // Get a mask for the bits shifting in.
6348 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006349 Value* SrcIOp0 = SrcI->getOperand(0);
6350 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006351 if (ShAmt >= DestBitWidth) // All zeros.
6352 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6353
6354 // Okay, we can shrink this. Truncate the input, then return a new
6355 // shift.
Reid Spencer2341c222007-02-02 02:16:23 +00006356 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6357 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6358 Ty, CI);
Reid Spencer0d5f9232007-02-02 14:08:20 +00006359 return BinaryOperator::createLShr(V1, V2);
Chris Lattnerd747f012006-11-29 07:04:07 +00006360 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006361 } else { // This is a variable shr.
6362
6363 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6364 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6365 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006366 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006367 Value *One = ConstantInt::get(SrcI->getType(), 1);
6368
Reid Spencer2341c222007-02-02 02:16:23 +00006369 Value *V = InsertNewInstBefore(
Reid Spencer0d5f9232007-02-02 14:08:20 +00006370 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer2341c222007-02-02 02:16:23 +00006371 "tmp"), CI);
Chris Lattnerc209b582006-12-05 01:26:29 +00006372 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6373 SrcI->getOperand(0),
6374 "tmp"), CI);
6375 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006376 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006377 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006378 }
6379 break;
6380 }
6381 }
6382
6383 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006384}
6385
6386Instruction *InstCombiner::visitZExt(CastInst &CI) {
6387 // If one of the common conversion will work ..
6388 if (Instruction *Result = commonIntCastTransforms(CI))
6389 return Result;
6390
6391 Value *Src = CI.getOperand(0);
6392
6393 // If this is a cast of a cast
6394 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006395 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6396 // types and if the sizes are just right we can convert this into a logical
6397 // 'and' which will be much cheaper than the pair of casts.
6398 if (isa<TruncInst>(CSrc)) {
6399 // Get the sizes of the types involved
6400 Value *A = CSrc->getOperand(0);
6401 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6402 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6403 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6404 // If we're actually extending zero bits and the trunc is a no-op
6405 if (MidSize < DstSize && SrcSize == DstSize) {
6406 // Replace both of the casts with an And of the type mask.
Reid Spencera94d3942007-01-19 21:13:56 +00006407 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006408 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6409 Instruction *And =
6410 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6411 // Unfortunately, if the type changed, we need to cast it back.
6412 if (And->getType() != CI.getType()) {
6413 And->setName(CSrc->getName()+".mask");
6414 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006415 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 }
6417 return And;
6418 }
6419 }
6420 }
6421
6422 return 0;
6423}
6424
6425Instruction *InstCombiner::visitSExt(CastInst &CI) {
6426 return commonIntCastTransforms(CI);
6427}
6428
6429Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6430 return commonCastTransforms(CI);
6431}
6432
6433Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6434 return commonCastTransforms(CI);
6435}
6436
6437Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006438 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006439}
6440
6441Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006442 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443}
6444
6445Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6446 return commonCastTransforms(CI);
6447}
6448
6449Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6450 return commonCastTransforms(CI);
6451}
6452
6453Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006454 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006455}
6456
6457Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6458 return commonCastTransforms(CI);
6459}
6460
6461Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6462
6463 // If the operands are integer typed then apply the integer transforms,
6464 // otherwise just apply the common ones.
6465 Value *Src = CI.getOperand(0);
6466 const Type *SrcTy = Src->getType();
6467 const Type *DestTy = CI.getType();
6468
Chris Lattner03c49532007-01-15 02:27:26 +00006469 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006470 if (Instruction *Result = commonIntCastTransforms(CI))
6471 return Result;
6472 } else {
6473 if (Instruction *Result = commonCastTransforms(CI))
6474 return Result;
6475 }
6476
6477
6478 // Get rid of casts from one type to the same type. These are useless and can
6479 // be replaced by the operand.
6480 if (DestTy == Src->getType())
6481 return ReplaceInstUsesWith(CI, Src);
6482
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006483 // If the source and destination are pointers, and this cast is equivalent to
6484 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6485 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006486 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6487 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6488 const Type *DstElTy = DstPTy->getElementType();
6489 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006490
Reid Spencerc635f472006-12-31 05:48:39 +00006491 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006492 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006493 while (SrcElTy != DstElTy &&
6494 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6495 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6496 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006497 ++NumZeros;
6498 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006499
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006500 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006501 if (SrcElTy == DstElTy) {
Chris Lattner416a8932007-01-31 20:08:52 +00006502 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6503 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006504 }
6505 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006506 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006507
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006508 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6509 if (SVI->hasOneUse()) {
6510 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6511 // a bitconvert to a vector with the same # elts.
Reid Spencerd84d35b2007-02-15 02:26:10 +00006512 if (isa<VectorType>(DestTy) &&
6513 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006514 SVI->getType()->getNumElements()) {
6515 CastInst *Tmp;
6516 // If either of the operands is a cast from CI.getType(), then
6517 // evaluating the shuffle in the casted destination's type will allow
6518 // us to eliminate at least one cast.
6519 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6520 Tmp->getOperand(0)->getType() == DestTy) ||
6521 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6522 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006523 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6524 SVI->getOperand(0), DestTy, &CI);
6525 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6526 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006527 // Return a new shuffle vector. Use the same element ID's, as we
6528 // know the vector types match #elts.
6529 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006530 }
6531 }
6532 }
6533 }
Chris Lattner260ab202002-04-18 17:39:14 +00006534 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006535}
6536
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006537/// GetSelectFoldableOperands - We want to turn code that looks like this:
6538/// %C = or %A, %B
6539/// %D = select %cond, %C, %A
6540/// into:
6541/// %C = select %cond, %B, 0
6542/// %D = or %A, %C
6543///
6544/// Assuming that the specified instruction is an operand to the select, return
6545/// a bitmask indicating which operands of this instruction are foldable if they
6546/// equal the other incoming value of the select.
6547///
6548static unsigned GetSelectFoldableOperands(Instruction *I) {
6549 switch (I->getOpcode()) {
6550 case Instruction::Add:
6551 case Instruction::Mul:
6552 case Instruction::And:
6553 case Instruction::Or:
6554 case Instruction::Xor:
6555 return 3; // Can fold through either operand.
6556 case Instruction::Sub: // Can only fold on the amount subtracted.
6557 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006558 case Instruction::LShr:
6559 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006560 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006561 default:
6562 return 0; // Cannot fold
6563 }
6564}
6565
6566/// GetSelectFoldableConstant - For the same transformation as the previous
6567/// function, return the identity constant that goes into the select.
6568static Constant *GetSelectFoldableConstant(Instruction *I) {
6569 switch (I->getOpcode()) {
6570 default: assert(0 && "This cannot happen!"); abort();
6571 case Instruction::Add:
6572 case Instruction::Sub:
6573 case Instruction::Or:
6574 case Instruction::Xor:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006575 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006576 case Instruction::LShr:
6577 case Instruction::AShr:
Reid Spencer2341c222007-02-02 02:16:23 +00006578 return Constant::getNullValue(I->getType());
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006579 case Instruction::And:
6580 return ConstantInt::getAllOnesValue(I->getType());
6581 case Instruction::Mul:
6582 return ConstantInt::get(I->getType(), 1);
6583 }
6584}
6585
Chris Lattner411336f2005-01-19 21:50:18 +00006586/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6587/// have the same opcode and only one use each. Try to simplify this.
6588Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6589 Instruction *FI) {
6590 if (TI->getNumOperands() == 1) {
6591 // If this is a non-volatile load or a cast from the same type,
6592 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006593 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006594 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6595 return 0;
6596 } else {
6597 return 0; // unknown unary op.
6598 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006599
Chris Lattner411336f2005-01-19 21:50:18 +00006600 // Fold this by inserting a select from the input values.
6601 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6602 FI->getOperand(0), SI.getName()+".v");
6603 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006604 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6605 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006606 }
6607
Reid Spencer2341c222007-02-02 02:16:23 +00006608 // Only handle binary operators here.
6609 if (!isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006610 return 0;
6611
6612 // Figure out if the operations have any operands in common.
6613 Value *MatchOp, *OtherOpT, *OtherOpF;
6614 bool MatchIsOpZero;
6615 if (TI->getOperand(0) == FI->getOperand(0)) {
6616 MatchOp = TI->getOperand(0);
6617 OtherOpT = TI->getOperand(1);
6618 OtherOpF = FI->getOperand(1);
6619 MatchIsOpZero = true;
6620 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6621 MatchOp = TI->getOperand(1);
6622 OtherOpT = TI->getOperand(0);
6623 OtherOpF = FI->getOperand(0);
6624 MatchIsOpZero = false;
6625 } else if (!TI->isCommutative()) {
6626 return 0;
6627 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6628 MatchOp = TI->getOperand(0);
6629 OtherOpT = TI->getOperand(1);
6630 OtherOpF = FI->getOperand(0);
6631 MatchIsOpZero = true;
6632 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6633 MatchOp = TI->getOperand(1);
6634 OtherOpT = TI->getOperand(0);
6635 OtherOpF = FI->getOperand(1);
6636 MatchIsOpZero = true;
6637 } else {
6638 return 0;
6639 }
6640
6641 // If we reach here, they do have operations in common.
6642 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6643 OtherOpF, SI.getName()+".v");
6644 InsertNewInstBefore(NewSI, SI);
6645
6646 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6647 if (MatchIsOpZero)
6648 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6649 else
6650 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006651 }
Reid Spencer2f34b982007-02-02 14:41:37 +00006652 assert(0 && "Shouldn't get here");
6653 return 0;
Chris Lattner411336f2005-01-19 21:50:18 +00006654}
6655
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006656Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006657 Value *CondVal = SI.getCondition();
6658 Value *TrueVal = SI.getTrueValue();
6659 Value *FalseVal = SI.getFalseValue();
6660
6661 // select true, X, Y -> X
6662 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006663 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006664 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006665
6666 // select C, X, X -> X
6667 if (TrueVal == FalseVal)
6668 return ReplaceInstUsesWith(SI, TrueVal);
6669
Chris Lattner81a7a232004-10-16 18:11:37 +00006670 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6671 return ReplaceInstUsesWith(SI, FalseVal);
6672 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6673 return ReplaceInstUsesWith(SI, TrueVal);
6674 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6675 if (isa<Constant>(TrueVal))
6676 return ReplaceInstUsesWith(SI, TrueVal);
6677 else
6678 return ReplaceInstUsesWith(SI, FalseVal);
6679 }
6680
Reid Spencer542964f2007-01-11 18:21:29 +00006681 if (SI.getType() == Type::Int1Ty) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006682 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006683 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006684 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006685 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006686 } else {
6687 // Change: A = select B, false, C --> A = and !B, C
6688 Value *NotCond =
6689 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6690 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006691 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006692 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +00006693 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006694 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006695 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006696 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006697 } else {
6698 // Change: A = select B, C, true --> A = or !B, C
6699 Value *NotCond =
6700 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6701 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006702 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006703 }
6704 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006705 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006706
Chris Lattner183b3362004-04-09 19:05:30 +00006707 // Selecting between two integer constants?
6708 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6709 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6710 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006711 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006712 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006713 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006714 // select C, 0, 1 -> cast !C to int
6715 Value *NotCond =
6716 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006717 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006718 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006719 }
Chris Lattner35167c32004-06-09 07:59:58 +00006720
Reid Spencer266e42b2006-12-23 06:05:41 +00006721 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006722
Reid Spencer266e42b2006-12-23 06:05:41 +00006723 // (x <s 0) ? -1 : 0 -> ashr x, 31
6724 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006725 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6726 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6727 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006728 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006729 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006730 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006731 else {
6732 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006733 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006734 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006735 }
6736
6737 if (CanXForm) {
6738 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006739 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006740 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006741 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer2341c222007-02-02 02:16:23 +00006742 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6743 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6744 ShAmt, "ones");
Chris Lattner380c7e92006-09-20 04:44:59 +00006745 InsertNewInstBefore(SRA, SI);
6746
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006747 // Finally, convert to the type of the select RHS. We figure out
6748 // if this requires a SExt, Trunc or BitCast based on the sizes.
6749 Instruction::CastOps opc = Instruction::BitCast;
6750 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6751 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6752 if (SRASize < SISize)
6753 opc = Instruction::SExt;
6754 else if (SRASize > SISize)
6755 opc = Instruction::Trunc;
6756 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006757 }
6758 }
6759
6760
6761 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006762 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006763 // non-constant value, eliminate this whole mess. This corresponds to
6764 // cases like this: ((X & 27) ? 27 : 0)
6765 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006766 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006767 cast<Constant>(IC->getOperand(1))->isNullValue())
6768 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6769 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006770 isa<ConstantInt>(ICA->getOperand(1)) &&
6771 (ICA->getOperand(1) == TrueValC ||
6772 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006773 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6774 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006775 // know whether we have a icmp_ne or icmp_eq and whether the
6776 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006777 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006778 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006779 Value *V = ICA;
6780 if (ShouldNotVal)
6781 V = InsertNewInstBefore(BinaryOperator::create(
6782 Instruction::Xor, V, ICA->getOperand(1)), SI);
6783 return ReplaceInstUsesWith(SI, V);
6784 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006785 }
Chris Lattner533bc492004-03-30 19:37:13 +00006786 }
Chris Lattner623fba12004-04-10 22:21:27 +00006787
6788 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006789 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6790 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006791 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006792 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006793 return ReplaceInstUsesWith(SI, FalseVal);
6794 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006795 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006796 return ReplaceInstUsesWith(SI, TrueVal);
6797 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6798
Reid Spencer266e42b2006-12-23 06:05:41 +00006799 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006800 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006801 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006802 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006803 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006804 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6805 return ReplaceInstUsesWith(SI, TrueVal);
6806 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6807 }
6808 }
6809
6810 // See if we are selecting two values based on a comparison of the two values.
6811 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6812 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6813 // Transform (X == Y) ? X : Y -> Y
6814 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6815 return ReplaceInstUsesWith(SI, FalseVal);
6816 // Transform (X != Y) ? X : Y -> X
6817 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6818 return ReplaceInstUsesWith(SI, TrueVal);
6819 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6820
6821 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6822 // Transform (X == Y) ? Y : X -> X
6823 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6824 return ReplaceInstUsesWith(SI, FalseVal);
6825 // Transform (X != Y) ? Y : X -> Y
6826 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006827 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006828 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6829 }
6830 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006831
Chris Lattnera04c9042005-01-13 22:52:24 +00006832 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6833 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6834 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006835 Instruction *AddOp = 0, *SubOp = 0;
6836
Chris Lattner411336f2005-01-19 21:50:18 +00006837 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6838 if (TI->getOpcode() == FI->getOpcode())
6839 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6840 return IV;
6841
6842 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6843 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006844 if (TI->getOpcode() == Instruction::Sub &&
6845 FI->getOpcode() == Instruction::Add) {
6846 AddOp = FI; SubOp = TI;
6847 } else if (FI->getOpcode() == Instruction::Sub &&
6848 TI->getOpcode() == Instruction::Add) {
6849 AddOp = TI; SubOp = FI;
6850 }
6851
6852 if (AddOp) {
6853 Value *OtherAddOp = 0;
6854 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6855 OtherAddOp = AddOp->getOperand(1);
6856 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6857 OtherAddOp = AddOp->getOperand(0);
6858 }
6859
6860 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006861 // So at this point we know we have (Y -> OtherAddOp):
6862 // select C, (add X, Y), (sub X, Z)
6863 Value *NegVal; // Compute -Z
6864 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6865 NegVal = ConstantExpr::getNeg(C);
6866 } else {
6867 NegVal = InsertNewInstBefore(
6868 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006869 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006870
6871 Value *NewTrueOp = OtherAddOp;
6872 Value *NewFalseOp = NegVal;
6873 if (AddOp != TI)
6874 std::swap(NewTrueOp, NewFalseOp);
6875 Instruction *NewSel =
6876 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6877
6878 NewSel = InsertNewInstBefore(NewSel, SI);
6879 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006880 }
6881 }
6882 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006883
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006884 // See if we can fold the select into one of our operands.
Chris Lattner03c49532007-01-15 02:27:26 +00006885 if (SI.getType()->isInteger()) {
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006886 // See the comment above GetSelectFoldableOperands for a description of the
6887 // transformation we are doing here.
6888 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6889 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6890 !isa<Constant>(FalseVal))
6891 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6892 unsigned OpToFold = 0;
6893 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6894 OpToFold = 1;
6895 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6896 OpToFold = 2;
6897 }
6898
6899 if (OpToFold) {
6900 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006901 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006902 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006903 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006904 NewSel->takeName(TVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6906 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006907 else {
6908 assert(0 && "Unknown instruction!!");
6909 }
6910 }
6911 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006912
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006913 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6914 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6915 !isa<Constant>(TrueVal))
6916 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6917 unsigned OpToFold = 0;
6918 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6919 OpToFold = 1;
6920 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6921 OpToFold = 2;
6922 }
6923
6924 if (OpToFold) {
6925 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006926 Instruction *NewSel =
Chris Lattner6e0123b2007-02-11 01:23:03 +00006927 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006928 InsertNewInstBefore(NewSel, SI);
Chris Lattner6e0123b2007-02-11 01:23:03 +00006929 NewSel->takeName(FVI);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006930 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6931 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer2341c222007-02-02 02:16:23 +00006932 else
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006933 assert(0 && "Unknown instruction!!");
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006934 }
6935 }
6936 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006937
6938 if (BinaryOperator::isNot(CondVal)) {
6939 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6940 SI.setOperand(1, FalseVal);
6941 SI.setOperand(2, TrueVal);
6942 return &SI;
6943 }
6944
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006945 return 0;
6946}
6947
Chris Lattner82f2ef22006-03-06 20:18:44 +00006948/// GetKnownAlignment - If the specified pointer has an alignment that we can
6949/// determine, return it, otherwise return 0.
6950static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6951 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6952 unsigned Align = GV->getAlignment();
6953 if (Align == 0 && TD)
Chris Lattner945e4372007-02-14 05:52:17 +00006954 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006955 return Align;
6956 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6957 unsigned Align = AI->getAlignment();
6958 if (Align == 0 && TD) {
6959 if (isa<AllocaInst>(AI))
Chris Lattner945e4372007-02-14 05:52:17 +00006960 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner82f2ef22006-03-06 20:18:44 +00006961 else if (isa<MallocInst>(AI)) {
6962 // Malloc returns maximally aligned memory.
Chris Lattner945e4372007-02-14 05:52:17 +00006963 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner50ee0e42007-01-20 22:35:55 +00006964 Align =
6965 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006966 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner50ee0e42007-01-20 22:35:55 +00006967 Align =
6968 std::max(Align,
Chris Lattner945e4372007-02-14 05:52:17 +00006969 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006970 }
6971 }
6972 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006973 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006974 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006975 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006976 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006977 if (isa<PointerType>(CI->getOperand(0)->getType()))
6978 return GetKnownAlignment(CI->getOperand(0), TD);
6979 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006980 } else if (isa<GetElementPtrInst>(V) ||
6981 (isa<ConstantExpr>(V) &&
6982 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6983 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006984 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6985 if (BaseAlignment == 0) return 0;
6986
6987 // If all indexes are zero, it is just the alignment of the base pointer.
6988 bool AllZeroOperands = true;
6989 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6990 if (!isa<Constant>(GEPI->getOperand(i)) ||
6991 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6992 AllZeroOperands = false;
6993 break;
6994 }
6995 if (AllZeroOperands)
6996 return BaseAlignment;
6997
6998 // Otherwise, if the base alignment is >= the alignment we expect for the
6999 // base pointer type, then we know that the resultant pointer is aligned at
7000 // least as much as its type requires.
7001 if (!TD) return 0;
7002
7003 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007004 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007005 if (TD->getABITypeAlignment(PtrTy->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00007006 <= BaseAlignment) {
7007 const Type *GEPTy = GEPI->getType();
Chris Lattner50ee0e42007-01-20 22:35:55 +00007008 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Chris Lattner945e4372007-02-14 05:52:17 +00007009 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
Chris Lattner53ef5a02006-03-07 01:28:57 +00007010 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007011 return 0;
7012 }
7013 return 0;
7014}
7015
Chris Lattnerb909e8b2004-03-12 05:52:32 +00007016
Chris Lattnerc66b2232006-01-13 20:11:04 +00007017/// visitCallInst - CallInst simplification. This mostly only handles folding
7018/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7019/// the heavy lifting.
7020///
Chris Lattner970c33a2003-06-19 17:00:31 +00007021Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00007022 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7023 if (!II) return visitCallSite(&CI);
7024
Chris Lattner51ea1272004-02-28 05:22:00 +00007025 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7026 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00007027 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007028 bool Changed = false;
7029
7030 // memmove/cpy/set of zero bytes is a noop.
7031 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7032 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7033
Chris Lattner00648e12004-10-12 04:52:52 +00007034 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007035 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00007036 // Replace the instruction with just byte operations. We would
7037 // transform other cases to loads/stores, but we don't know if
7038 // alignment is sufficient.
7039 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007040 }
7041
Chris Lattner00648e12004-10-12 04:52:52 +00007042 // If we have a memmove and the source operation is a constant global,
7043 // then the source and dest pointers can't alias, so we can change this
7044 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007045 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007046 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7047 if (GVSrc->isConstant()) {
7048 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007049 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007050 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00007051 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00007052 Name = "llvm.memcpy.i32";
7053 else
7054 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00007055 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007056 CI.getCalledFunction()->getFunctionType());
7057 CI.setOperand(0, MemCpy);
7058 Changed = true;
7059 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007060 }
Chris Lattner00648e12004-10-12 04:52:52 +00007061
Chris Lattner82f2ef22006-03-06 20:18:44 +00007062 // If we can determine a pointer alignment that is bigger than currently
7063 // set, update the alignment.
7064 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7065 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7066 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7067 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007068 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00007069 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007070 Changed = true;
7071 }
7072 } else if (isa<MemSetInst>(MI)) {
7073 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007074 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00007075 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007076 Changed = true;
7077 }
7078 }
7079
Chris Lattnerc66b2232006-01-13 20:11:04 +00007080 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007081 } else {
7082 switch (II->getIntrinsicID()) {
7083 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007084 case Intrinsic::ppc_altivec_lvx:
7085 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007086 case Intrinsic::x86_sse_loadu_ps:
7087 case Intrinsic::x86_sse2_loadu_pd:
7088 case Intrinsic::x86_sse2_loadu_dq:
7089 // Turn PPC lvx -> load if the pointer is known aligned.
7090 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007091 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007092 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007093 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007094 return new LoadInst(Ptr);
7095 }
7096 break;
7097 case Intrinsic::ppc_altivec_stvx:
7098 case Intrinsic::ppc_altivec_stvxl:
7099 // Turn stvx -> store if the pointer is known aligned.
7100 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007101 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007102 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7103 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007104 return new StoreInst(II->getOperand(1), Ptr);
7105 }
7106 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007107 case Intrinsic::x86_sse_storeu_ps:
7108 case Intrinsic::x86_sse2_storeu_pd:
7109 case Intrinsic::x86_sse2_storeu_dq:
7110 case Intrinsic::x86_sse2_storel_dq:
7111 // Turn X86 storeu -> store if the pointer is known aligned.
7112 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7113 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007114 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7115 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007116 return new StoreInst(II->getOperand(2), Ptr);
7117 }
7118 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007119
7120 case Intrinsic::x86_sse_cvttss2si: {
7121 // These intrinsics only demands the 0th element of its input vector. If
7122 // we can simplify the input based on that, do so now.
7123 uint64_t UndefElts;
7124 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7125 UndefElts)) {
7126 II->setOperand(1, V);
7127 return II;
7128 }
7129 break;
7130 }
7131
Chris Lattnere79d2492006-04-06 19:19:17 +00007132 case Intrinsic::ppc_altivec_vperm:
7133 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +00007134 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007135 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7136
7137 // Check that all of the elements are integer constants or undefs.
7138 bool AllEltsOk = true;
7139 for (unsigned i = 0; i != 16; ++i) {
7140 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7141 !isa<UndefValue>(Mask->getOperand(i))) {
7142 AllEltsOk = false;
7143 break;
7144 }
7145 }
7146
7147 if (AllEltsOk) {
7148 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007149 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7150 II->getOperand(1), Mask->getType(), CI);
7151 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7152 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007153 Value *Result = UndefValue::get(Op0->getType());
7154
7155 // Only extract each element once.
7156 Value *ExtractedElts[32];
7157 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7158
7159 for (unsigned i = 0; i != 16; ++i) {
7160 if (isa<UndefValue>(Mask->getOperand(i)))
7161 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007162 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007163 Idx &= 31; // Match the hardware behavior.
7164
7165 if (ExtractedElts[Idx] == 0) {
7166 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007167 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007168 InsertNewInstBefore(Elt, CI);
7169 ExtractedElts[Idx] = Elt;
7170 }
7171
7172 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007173 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007174 InsertNewInstBefore(cast<Instruction>(Result), CI);
7175 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007176 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007177 }
7178 }
7179 break;
7180
Chris Lattner503221f2006-01-13 21:28:09 +00007181 case Intrinsic::stackrestore: {
7182 // If the save is right next to the restore, remove the restore. This can
7183 // happen when variable allocas are DCE'd.
7184 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7185 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7186 BasicBlock::iterator BI = SS;
7187 if (&*++BI == II)
7188 return EraseInstFromFunction(CI);
7189 }
7190 }
7191
7192 // If the stack restore is in a return/unwind block and if there are no
7193 // allocas or calls between the restore and the return, nuke the restore.
7194 TerminatorInst *TI = II->getParent()->getTerminator();
7195 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7196 BasicBlock::iterator BI = II;
7197 bool CannotRemove = false;
7198 for (++BI; &*BI != TI; ++BI) {
7199 if (isa<AllocaInst>(BI) ||
7200 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7201 CannotRemove = true;
7202 break;
7203 }
7204 }
7205 if (!CannotRemove)
7206 return EraseInstFromFunction(CI);
7207 }
7208 break;
7209 }
7210 }
Chris Lattner00648e12004-10-12 04:52:52 +00007211 }
7212
Chris Lattnerc66b2232006-01-13 20:11:04 +00007213 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007214}
7215
7216// InvokeInst simplification
7217//
7218Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007219 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007220}
7221
Chris Lattneraec3d942003-10-07 22:32:43 +00007222// visitCallSite - Improvements for call and invoke instructions.
7223//
7224Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007225 bool Changed = false;
7226
7227 // If the callee is a constexpr cast of a function, attempt to move the cast
7228 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007229 if (transformConstExprCastCall(CS)) return 0;
7230
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007231 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007232
Chris Lattner61d9d812005-05-13 07:09:09 +00007233 if (Function *CalleeF = dyn_cast<Function>(Callee))
7234 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7235 Instruction *OldCall = CS.getInstruction();
7236 // If the call and callee calling conventions don't match, this call must
7237 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007238 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007239 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007240 if (!OldCall->use_empty())
7241 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7242 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7243 return EraseInstFromFunction(*OldCall);
7244 return 0;
7245 }
7246
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007247 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7248 // This instruction is not reachable, just remove it. We insert a store to
7249 // undef so that we know that this code is not reachable, despite the fact
7250 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007251 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007252 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007253 CS.getInstruction());
7254
7255 if (!CS.getInstruction()->use_empty())
7256 CS.getInstruction()->
7257 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7258
7259 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7260 // Don't break the CFG, insert a dummy cond branch.
7261 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007262 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007263 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007264 return EraseInstFromFunction(*CS.getInstruction());
7265 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007266
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007267 const PointerType *PTy = cast<PointerType>(Callee->getType());
7268 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7269 if (FTy->isVarArg()) {
7270 // See if we can optimize any arguments passed through the varargs area of
7271 // the call.
7272 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7273 E = CS.arg_end(); I != E; ++I)
7274 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7275 // If this cast does not effect the value passed through the varargs
7276 // area, we can eliminate the use of the cast.
7277 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007278 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007279 *I = Op;
7280 Changed = true;
7281 }
7282 }
7283 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007284
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007285 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007286}
7287
Chris Lattner970c33a2003-06-19 17:00:31 +00007288// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7289// attempt to move the cast to the arguments of the call/invoke.
7290//
7291bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7292 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7293 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007294 if (CE->getOpcode() != Instruction::BitCast ||
7295 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007296 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007297 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007298 Instruction *Caller = CS.getInstruction();
7299
7300 // Okay, this is a cast from a function to a different type. Unless doing so
7301 // would cause a type conversion of one of our arguments, change this call to
7302 // be a direct call with arguments casted to the appropriate types.
7303 //
7304 const FunctionType *FT = Callee->getFunctionType();
7305 const Type *OldRetTy = Caller->getType();
7306
Chris Lattner1f7942f2004-01-14 06:06:08 +00007307 // Check to see if we are changing the return type...
7308 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00007309 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007310 OldRetTy != FT->getReturnType() &&
7311 // Conversion is ok if changing from pointer to int of same size.
7312 !(isa<PointerType>(FT->getReturnType()) &&
7313 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007314 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007315
7316 // If the callsite is an invoke instruction, and the return value is used by
7317 // a PHI node in a successor, we cannot change the return type of the call
7318 // because there is no place to put the cast instruction (without breaking
7319 // the critical edge). Bail out in this case.
7320 if (!Caller->use_empty())
7321 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7322 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7323 UI != E; ++UI)
7324 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7325 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007326 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007327 return false;
7328 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007329
7330 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7331 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007332
Chris Lattner970c33a2003-06-19 17:00:31 +00007333 CallSite::arg_iterator AI = CS.arg_begin();
7334 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7335 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007336 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007337 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007338 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007339 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007340 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner03c49532007-01-15 02:27:26 +00007341 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007342 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7343 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7344 && c->getSExtValue() > 0);
Reid Spencer5301e7c2007-01-30 20:08:39 +00007345 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007346 }
7347
7348 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5301e7c2007-01-30 20:08:39 +00007349 Callee->isDeclaration())
Chris Lattner970c33a2003-06-19 17:00:31 +00007350 return false; // Do not delete arguments unless we have a function body...
7351
7352 // Okay, we decided that this is a safe thing to do: go ahead and start
7353 // inserting cast instructions as necessary...
7354 std::vector<Value*> Args;
7355 Args.reserve(NumActualArgs);
7356
7357 AI = CS.arg_begin();
7358 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7359 const Type *ParamTy = FT->getParamType(i);
7360 if ((*AI)->getType() == ParamTy) {
7361 Args.push_back(*AI);
7362 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007363 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007364 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007365 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007366 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007367 }
7368 }
7369
7370 // If the function takes more arguments than the call was taking, add them
7371 // now...
7372 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7373 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7374
7375 // If we are removing arguments to the function, emit an obnoxious warning...
7376 if (FT->getNumParams() < NumActualArgs)
7377 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007378 cerr << "WARNING: While resolving call to function '"
7379 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007380 } else {
7381 // Add all of the arguments in their promoted form to the arg list...
7382 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7383 const Type *PTy = getPromotedType((*AI)->getType());
7384 if (PTy != (*AI)->getType()) {
7385 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007386 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7387 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007388 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007389 InsertNewInstBefore(Cast, *Caller);
7390 Args.push_back(Cast);
7391 } else {
7392 Args.push_back(*AI);
7393 }
7394 }
7395 }
7396
7397 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6e0123b2007-02-11 01:23:03 +00007398 Caller->setName(""); // Void type should not have a name.
Chris Lattner970c33a2003-06-19 17:00:31 +00007399
7400 Instruction *NC;
7401 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007402 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007403 &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007404 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007405 } else {
Chris Lattnera06a8fd2007-02-13 02:10:56 +00007406 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007407 if (cast<CallInst>(Caller)->isTailCall())
7408 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007409 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007410 }
7411
Chris Lattner6e0123b2007-02-11 01:23:03 +00007412 // Insert a cast of the return type as necessary.
Chris Lattner970c33a2003-06-19 17:00:31 +00007413 Value *NV = NC;
7414 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7415 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007416 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007417 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7418 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007419 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007420
7421 // If this is an invoke instruction, we should insert it after the first
7422 // non-phi, instruction in the normal successor block.
7423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7424 BasicBlock::iterator I = II->getNormalDest()->begin();
7425 while (isa<PHINode>(I)) ++I;
7426 InsertNewInstBefore(NC, *I);
7427 } else {
7428 // Otherwise, it's a call, just insert cast right after the call instr
7429 InsertNewInstBefore(NC, *Caller);
7430 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007431 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007432 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007433 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007434 }
7435 }
7436
7437 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7438 Caller->replaceAllUsesWith(NV);
Chris Lattner51f54572007-03-02 19:59:19 +00007439 Caller->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00007440 RemoveFromWorkList(Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007441 return true;
7442}
7443
Chris Lattnercadac0c2006-11-01 04:51:18 +00007444/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7445/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7446/// and a single binop.
7447Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7448 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer2341c222007-02-02 02:16:23 +00007449 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7450 isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007451 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007452 Value *LHSVal = FirstInst->getOperand(0);
7453 Value *RHSVal = FirstInst->getOperand(1);
7454
7455 const Type *LHSType = LHSVal->getType();
7456 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007457
7458 // Scan to see if all operands are the same opcode, all have one use, and all
7459 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007460 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007461 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007462 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007463 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007464 // types or GEP's with different index types.
7465 I->getOperand(0)->getType() != LHSType ||
7466 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007467 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007468
7469 // If they are CmpInst instructions, check their predicates
7470 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7471 if (cast<CmpInst>(I)->getPredicate() !=
7472 cast<CmpInst>(FirstInst)->getPredicate())
7473 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007474
7475 // Keep track of which operand needs a phi node.
7476 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7477 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007478 }
7479
Chris Lattner4f218d52006-11-08 19:42:28 +00007480 // Otherwise, this is safe to transform, determine if it is profitable.
7481
7482 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7483 // Indexes are often folded into load/store instructions, so we don't want to
7484 // hide them behind a phi.
7485 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7486 return 0;
7487
Chris Lattnercadac0c2006-11-01 04:51:18 +00007488 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007489 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007490 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007491 if (LHSVal == 0) {
7492 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7493 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7494 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007495 InsertNewInstBefore(NewLHS, PN);
7496 LHSVal = NewLHS;
7497 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007498
7499 if (RHSVal == 0) {
7500 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7501 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7502 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007503 InsertNewInstBefore(NewRHS, PN);
7504 RHSVal = NewRHS;
7505 }
7506
Chris Lattnercd62f112006-11-08 19:29:23 +00007507 // Add all operands to the new PHIs.
7508 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7509 if (NewLHS) {
7510 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7511 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7512 }
7513 if (NewRHS) {
7514 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7515 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7516 }
7517 }
7518
Chris Lattnercadac0c2006-11-01 04:51:18 +00007519 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007520 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007521 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7522 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7523 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007524 else {
7525 assert(isa<GetElementPtrInst>(FirstInst));
7526 return new GetElementPtrInst(LHSVal, RHSVal);
7527 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007528}
7529
Chris Lattner14f82c72006-11-01 07:13:54 +00007530/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7531/// of the block that defines it. This means that it must be obvious the value
7532/// of the load is not changed from the point of the load to the end of the
7533/// block it is in.
Chris Lattnerc9042052007-02-01 22:30:07 +00007534///
7535/// Finally, it is safe, but not profitable, to sink a load targetting a
7536/// non-address-taken alloca. Doing so will cause us to not promote the alloca
7537/// to a register.
Chris Lattner14f82c72006-11-01 07:13:54 +00007538static bool isSafeToSinkLoad(LoadInst *L) {
7539 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7540
7541 for (++BBI; BBI != E; ++BBI)
7542 if (BBI->mayWriteToMemory())
7543 return false;
Chris Lattnerc9042052007-02-01 22:30:07 +00007544
7545 // Check for non-address taken alloca. If not address-taken already, it isn't
7546 // profitable to do this xform.
7547 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7548 bool isAddressTaken = false;
7549 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7550 UI != E; ++UI) {
7551 if (isa<LoadInst>(UI)) continue;
7552 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7553 // If storing TO the alloca, then the address isn't taken.
7554 if (SI->getOperand(1) == AI) continue;
7555 }
7556 isAddressTaken = true;
7557 break;
7558 }
7559
7560 if (!isAddressTaken)
7561 return false;
7562 }
7563
Chris Lattner14f82c72006-11-01 07:13:54 +00007564 return true;
7565}
7566
Chris Lattner970c33a2003-06-19 17:00:31 +00007567
Chris Lattner7515cab2004-11-14 19:13:23 +00007568// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7569// operator and they all are only used by the PHI, PHI together their
7570// inputs, and do the operation once, to the result of the PHI.
7571Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7572 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7573
7574 // Scan the instruction, looking for input operations that can be folded away.
7575 // If all input operands to the phi are the same instruction (e.g. a cast from
7576 // the same type or "+42") we can pull the operation through the PHI, reducing
7577 // code size and simplifying code.
7578 Constant *ConstantOp = 0;
7579 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007580 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007581 if (isa<CastInst>(FirstInst)) {
7582 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer2341c222007-02-02 02:16:23 +00007583 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007584 // Can fold binop, compare or shift here if the RHS is a constant,
7585 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007586 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007587 if (ConstantOp == 0)
7588 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007589 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7590 isVolatile = LI->isVolatile();
7591 // We can't sink the load if the loaded value could be modified between the
7592 // load and the PHI.
7593 if (LI->getParent() != PN.getIncomingBlock(0) ||
7594 !isSafeToSinkLoad(LI))
7595 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007596 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007597 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007598 return FoldPHIArgBinOpIntoPHI(PN);
7599 // Can't handle general GEPs yet.
7600 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007601 } else {
7602 return 0; // Cannot fold this operation.
7603 }
7604
7605 // Check to see if all arguments are the same operation.
7606 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7607 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7608 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007609 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007610 return 0;
7611 if (CastSrcTy) {
7612 if (I->getOperand(0)->getType() != CastSrcTy)
7613 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007614 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007615 // We can't sink the load if the loaded value could be modified between
7616 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007617 if (LI->isVolatile() != isVolatile ||
7618 LI->getParent() != PN.getIncomingBlock(i) ||
7619 !isSafeToSinkLoad(LI))
7620 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007621 } else if (I->getOperand(1) != ConstantOp) {
7622 return 0;
7623 }
7624 }
7625
7626 // Okay, they are all the same operation. Create a new PHI node of the
7627 // correct type, and PHI together all of the LHS's of the instructions.
7628 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7629 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007630 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007631
7632 Value *InVal = FirstInst->getOperand(0);
7633 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007634
7635 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007636 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7637 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7638 if (NewInVal != InVal)
7639 InVal = 0;
7640 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7641 }
7642
7643 Value *PhiVal;
7644 if (InVal) {
7645 // The new PHI unions all of the same values together. This is really
7646 // common, so we handle it intelligently here for compile-time speed.
7647 PhiVal = InVal;
7648 delete NewPN;
7649 } else {
7650 InsertNewInstBefore(NewPN, PN);
7651 PhiVal = NewPN;
7652 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007653
Chris Lattner7515cab2004-11-14 19:13:23 +00007654 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007655 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7656 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007657 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007658 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007659 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007660 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007661 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7662 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7663 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007664 else
Reid Spencer2341c222007-02-02 02:16:23 +00007665 assert(0 && "Unknown operation");
Jeff Cohenb622c112007-03-05 00:00:42 +00007666 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007667}
Chris Lattner48a44f72002-05-02 17:06:02 +00007668
Chris Lattner71536432005-01-17 05:10:15 +00007669/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7670/// that is dead.
7671static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7672 if (PN->use_empty()) return true;
7673 if (!PN->hasOneUse()) return false;
7674
7675 // Remember this node, and if we find the cycle, return.
7676 if (!PotentiallyDeadPHIs.insert(PN).second)
7677 return true;
7678
7679 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7680 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007681
Chris Lattner71536432005-01-17 05:10:15 +00007682 return false;
7683}
7684
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007685// PHINode simplification
7686//
Chris Lattner113f4f42002-06-25 16:13:24 +00007687Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007688 // If LCSSA is around, don't mess with Phi nodes
Chris Lattner8258b442007-03-04 04:27:24 +00007689 if (MustPreserveLCSSA) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007690
Owen Andersonae8aa642006-07-10 22:03:18 +00007691 if (Value *V = PN.hasConstantValue())
7692 return ReplaceInstUsesWith(PN, V);
7693
Owen Andersonae8aa642006-07-10 22:03:18 +00007694 // If all PHI operands are the same operation, pull them through the PHI,
7695 // reducing code size.
7696 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7697 PN.getIncomingValue(0)->hasOneUse())
7698 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7699 return Result;
7700
7701 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7702 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7703 // PHI)... break the cycle.
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007704 if (PN.hasOneUse()) {
7705 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7706 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Owen Andersonae8aa642006-07-10 22:03:18 +00007707 std::set<PHINode*> PotentiallyDeadPHIs;
7708 PotentiallyDeadPHIs.insert(&PN);
7709 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7710 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7711 }
Chris Lattnerc8dcede2007-01-15 07:30:06 +00007712
7713 // If this phi has a single use, and if that use just computes a value for
7714 // the next iteration of a loop, delete the phi. This occurs with unused
7715 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7716 // common case here is good because the only other things that catch this
7717 // are induction variable analysis (sometimes) and ADCE, which is only run
7718 // late.
7719 if (PHIUser->hasOneUse() &&
7720 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7721 PHIUser->use_back() == &PN) {
7722 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7723 }
7724 }
Owen Andersonae8aa642006-07-10 22:03:18 +00007725
Chris Lattner91daeb52003-12-19 05:58:40 +00007726 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007727}
7728
Reid Spencer13bc5d72006-12-12 09:18:51 +00007729static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7730 Instruction *InsertPoint,
7731 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007732 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7733 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007734 // We must cast correctly to the pointer type. Ensure that we
7735 // sign extend the integer value if it is smaller as this is
7736 // used for address computation.
7737 Instruction::CastOps opcode =
7738 (VTySize < PtrSize ? Instruction::SExt :
7739 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7740 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007741}
7742
Chris Lattner48a44f72002-05-02 17:06:02 +00007743
Chris Lattner113f4f42002-06-25 16:13:24 +00007744Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007745 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007746 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007747 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007748 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007749 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007750
Chris Lattner81a7a232004-10-16 18:11:37 +00007751 if (isa<UndefValue>(GEP.getOperand(0)))
7752 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7753
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007754 bool HasZeroPointerIndex = false;
7755 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7756 HasZeroPointerIndex = C->isNullValue();
7757
7758 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007759 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007760
Chris Lattner69193f92004-04-05 01:30:19 +00007761 // Eliminate unneeded casts for indices.
7762 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007763 gep_type_iterator GTI = gep_type_begin(GEP);
7764 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7765 if (isa<SequentialType>(*GTI)) {
7766 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner27df1db2007-01-15 07:02:54 +00007767 if (CI->getOpcode() == Instruction::ZExt ||
7768 CI->getOpcode() == Instruction::SExt) {
7769 const Type *SrcTy = CI->getOperand(0)->getType();
7770 // We can eliminate a cast from i32 to i64 iff the target
7771 // is a 32-bit pointer target.
7772 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7773 MadeChange = true;
7774 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner69193f92004-04-05 01:30:19 +00007775 }
7776 }
7777 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007778 // If we are using a wider index than needed for this platform, shrink it
7779 // to what we need. If the incoming value needs a cast instruction,
7780 // insert it. This explicit cast can make subsequent optimizations more
7781 // obvious.
7782 Value *Op = GEP.getOperand(i);
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007783 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007784 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007785 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007786 MadeChange = true;
7787 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007788 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7789 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007790 GEP.setOperand(i, Op);
7791 MadeChange = true;
7792 }
Chris Lattner69193f92004-04-05 01:30:19 +00007793 }
7794 if (MadeChange) return &GEP;
7795
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007796 // Combine Indices - If the source pointer to this getelementptr instruction
7797 // is a getelementptr instruction, combine the indices of the two
7798 // getelementptr instructions into a single instruction.
7799 //
Chris Lattneraf6094f2007-02-15 22:48:32 +00007800 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007801 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattneraf6094f2007-02-15 22:48:32 +00007802 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007803
7804 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007805 // Note that if our source is a gep chain itself that we wait for that
7806 // chain to be resolved before we perform this transformation. This
7807 // avoids us creating a TON of code in some cases.
7808 //
7809 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7810 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7811 return 0; // Wait until our source is folded to completion.
7812
Chris Lattneraf6094f2007-02-15 22:48:32 +00007813 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007814
7815 // Find out whether the last index in the source GEP is a sequential idx.
7816 bool EndsWithSequential = false;
7817 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7818 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007819 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007820
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007821 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007822 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007823 // Replace: gep (gep %P, long B), long A, ...
7824 // With: T = long A+B; gep %P, T, ...
7825 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007826 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007827 if (SO1 == Constant::getNullValue(SO1->getType())) {
7828 Sum = GO1;
7829 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7830 Sum = SO1;
7831 } else {
7832 // If they aren't the same type, convert both to an integer of the
7833 // target's pointer size.
7834 if (SO1->getType() != GO1->getType()) {
7835 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007836 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007837 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007838 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007839 } else {
7840 unsigned PS = TD->getPointerSize();
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007841 if (TD->getTypeSize(SO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007842 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007843 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007844
Reid Spencer7a9c62b2007-01-12 07:05:14 +00007845 } else if (TD->getTypeSize(GO1->getType()) == PS) {
Chris Lattner69193f92004-04-05 01:30:19 +00007846 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007847 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007848 } else {
7849 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007850 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7851 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007852 }
7853 }
7854 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007855 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7856 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7857 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007858 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7859 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007860 }
Chris Lattner69193f92004-04-05 01:30:19 +00007861 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007862
7863 // Recycle the GEP we already have if possible.
7864 if (SrcGEPOperands.size() == 2) {
7865 GEP.setOperand(0, SrcGEPOperands[0]);
7866 GEP.setOperand(1, Sum);
7867 return &GEP;
7868 } else {
7869 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7870 SrcGEPOperands.end()-1);
7871 Indices.push_back(Sum);
7872 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007874 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007875 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007876 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007877 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007878 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7879 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007880 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7881 }
7882
7883 if (!Indices.empty())
Chris Lattnera7315132007-02-12 22:56:41 +00007884 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7885 Indices.size(), GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007886
Chris Lattner5f667a62004-05-07 22:09:22 +00007887 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007888 // GEP of global variable. If all of the indices for this GEP are
7889 // constants, we can promote this to a constexpr instead of an instruction.
7890
7891 // Scan for nonconstants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007892 SmallVector<Constant*, 8> Indices;
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007893 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7894 for (; I != E && isa<Constant>(*I); ++I)
7895 Indices.push_back(cast<Constant>(*I));
7896
7897 if (I == E) { // If they are all constants...
Chris Lattnerf96f4a82007-01-31 04:40:53 +00007898 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7899 &Indices[0],Indices.size());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007900
7901 // Replace all uses of the GEP with the new constexpr...
7902 return ReplaceInstUsesWith(GEP, CE);
7903 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007904 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007905 if (!isa<PointerType>(X->getType())) {
7906 // Not interesting. Source pointer must be a cast from pointer.
7907 } else if (HasZeroPointerIndex) {
7908 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7909 // into : GEP [10 x ubyte]* X, long 0, ...
7910 //
7911 // This occurs when the program declares an array extern like "int X[];"
7912 //
7913 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7914 const PointerType *XTy = cast<PointerType>(X->getType());
7915 if (const ArrayType *XATy =
7916 dyn_cast<ArrayType>(XTy->getElementType()))
7917 if (const ArrayType *CATy =
7918 dyn_cast<ArrayType>(CPTy->getElementType()))
7919 if (CATy->getElementType() == XATy->getElementType()) {
7920 // At this point, we know that the cast source type is a pointer
7921 // to an array of the same type as the destination pointer
7922 // array. Because the array type is never stepped over (there
7923 // is a leading zero) we can fold the cast into this GEP.
7924 GEP.setOperand(0, X);
7925 return &GEP;
7926 }
7927 } else if (GEP.getNumOperands() == 2) {
7928 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007929 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7930 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007931 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7932 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7933 if (isa<ArrayType>(SrcElTy) &&
7934 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7935 TD->getTypeSize(ResElTy)) {
7936 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007937 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007938 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007939 // V and GEP are both pointer types --> BitCast
7940 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007941 }
Chris Lattner2a893292005-09-13 18:36:04 +00007942
7943 // Transform things like:
7944 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7945 // (where tmp = 8*tmp2) into:
7946 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7947
7948 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007949 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007950 uint64_t ArrayEltSize =
7951 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7952
7953 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7954 // allow either a mul, shift, or constant here.
7955 Value *NewIdx = 0;
7956 ConstantInt *Scale = 0;
7957 if (ArrayEltSize == 1) {
7958 NewIdx = GEP.getOperand(1);
7959 Scale = ConstantInt::get(NewIdx->getType(), 1);
7960 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007961 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007962 Scale = CI;
7963 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7964 if (Inst->getOpcode() == Instruction::Shl &&
7965 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007966 unsigned ShAmt =
7967 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007968 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007969 NewIdx = Inst->getOperand(0);
7970 } else if (Inst->getOpcode() == Instruction::Mul &&
7971 isa<ConstantInt>(Inst->getOperand(1))) {
7972 Scale = cast<ConstantInt>(Inst->getOperand(1));
7973 NewIdx = Inst->getOperand(0);
7974 }
7975 }
7976
7977 // If the index will be to exactly the right offset with the scale taken
7978 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007979 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007980 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007981 Scale = ConstantInt::get(Scale->getType(),
7982 Scale->getZExtValue() / ArrayEltSize);
7983 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007984 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7985 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007986 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7987 NewIdx = InsertNewInstBefore(Sc, GEP);
7988 }
7989
7990 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007991 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007992 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007993 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007994 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7995 // The NewGEP must be pointer typed, so must the old one -> BitCast
7996 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007997 }
7998 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007999 }
Chris Lattnerca081252001-12-14 16:52:21 +00008000 }
8001
Chris Lattnerca081252001-12-14 16:52:21 +00008002 return 0;
8003}
8004
Chris Lattner1085bdf2002-11-04 16:18:53 +00008005Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8006 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8007 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00008008 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8009 const Type *NewTy =
8010 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008011 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00008012
8013 // Create and insert the replacement instruction...
8014 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00008015 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008016 else {
8017 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00008018 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00008019 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008020
8021 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008022
Chris Lattner1085bdf2002-11-04 16:18:53 +00008023 // Scan to the end of the allocation instructions, to skip over a block of
8024 // allocas if possible...
8025 //
8026 BasicBlock::iterator It = New;
8027 while (isa<AllocationInst>(*It)) ++It;
8028
8029 // Now that I is pointing to the first non-allocation-inst in the block,
8030 // insert our getelementptr instruction...
8031 //
Reid Spencerc635f472006-12-31 05:48:39 +00008032 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00008033 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8034 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00008035
8036 // Now make everything use the getelementptr instead of the original
8037 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00008038 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00008039 } else if (isa<UndefValue>(AI.getArraySize())) {
8040 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00008041 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00008042
8043 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8044 // Note that we only do this for alloca's, because malloc should allocate and
8045 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00008046 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00008047 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00008048 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8049
Chris Lattner1085bdf2002-11-04 16:18:53 +00008050 return 0;
8051}
8052
Chris Lattner8427bff2003-12-07 01:24:23 +00008053Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8054 Value *Op = FI.getOperand(0);
8055
8056 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8057 if (CastInst *CI = dyn_cast<CastInst>(Op))
8058 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8059 FI.setOperand(0, CI->getOperand(0));
8060 return &FI;
8061 }
8062
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008063 // free undef -> unreachable.
8064 if (isa<UndefValue>(Op)) {
8065 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00008066 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00008067 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008068 return EraseInstFromFunction(FI);
8069 }
8070
Chris Lattnerf3a36602004-02-28 04:57:37 +00008071 // If we have 'free null' delete the instruction. This can happen in stl code
8072 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008073 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008074 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008075
Chris Lattner8427bff2003-12-07 01:24:23 +00008076 return 0;
8077}
8078
8079
Chris Lattner72684fe2005-01-31 05:51:45 +00008080/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008081static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8082 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008083 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008084
8085 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008086 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008087 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008088
Reid Spencer31a4ef42007-01-22 05:51:25 +00008089 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008090 isa<VectorType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008091 // If the source is an array, the code below will not succeed. Check to
8092 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8093 // constants.
8094 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8095 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8096 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008097 Value *Idxs[2];
8098 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8099 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008100 SrcTy = cast<PointerType>(CastOp->getType());
8101 SrcPTy = SrcTy->getElementType();
8102 }
8103
Reid Spencer31a4ef42007-01-22 05:51:25 +00008104 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencerd84d35b2007-02-15 02:26:10 +00008105 isa<VectorType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008106 // Do not allow turning this into a load of an integer, which is then
8107 // casted to a pointer, this pessimizes pointer analysis a lot.
8108 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer31a4ef42007-01-22 05:51:25 +00008109 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8110 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008111
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008112 // Okay, we are casting from one integer or pointer type to another of
8113 // the same size. Instead of casting the pointer before the load, cast
8114 // the result of the loaded value.
8115 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8116 CI->getName(),
8117 LI.isVolatile()),LI);
8118 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008119 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008120 }
Chris Lattner35e24772004-07-13 01:49:43 +00008121 }
8122 }
8123 return 0;
8124}
8125
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008126/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008127/// from this value cannot trap. If it is not obviously safe to load from the
8128/// specified pointer, we do a quick local scan of the basic block containing
8129/// ScanFrom, to determine if the address is already accessed.
8130static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8131 // If it is an alloca or global variable, it is always safe to load from.
8132 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8133
8134 // Otherwise, be a little bit agressive by scanning the local block where we
8135 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008136 // from/to. If so, the previous load or store would have already trapped,
8137 // so there is no harm doing an extra load (also, CSE will later eliminate
8138 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008139 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8140
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008141 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008142 --BBI;
8143
8144 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8145 if (LI->getOperand(0) == V) return true;
8146 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8147 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008148
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008149 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008150 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008151}
8152
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008153Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8154 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008155
Chris Lattnera9d84e32005-05-01 04:24:53 +00008156 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008157 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008158 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8159 return Res;
8160
8161 // None of the following transforms are legal for volatile loads.
8162 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008163
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008164 if (&LI.getParent()->front() != &LI) {
8165 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008166 // If the instruction immediately before this is a store to the same
8167 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008168 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8169 if (SI->getOperand(1) == LI.getOperand(0))
8170 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008171 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8172 if (LIB->getOperand(0) == LI.getOperand(0))
8173 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008174 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008175
8176 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8177 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8178 isa<UndefValue>(GEPI->getOperand(0))) {
8179 // Insert a new store to null instruction before the load to indicate
8180 // that this code is not reachable. We do this instead of inserting
8181 // an unreachable instruction directly because we cannot modify the
8182 // CFG.
8183 new StoreInst(UndefValue::get(LI.getType()),
8184 Constant::getNullValue(Op->getType()), &LI);
8185 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8186 }
8187
Chris Lattner81a7a232004-10-16 18:11:37 +00008188 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008189 // load null/undef -> undef
8190 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008191 // Insert a new store to null instruction before the load to indicate that
8192 // this code is not reachable. We do this instead of inserting an
8193 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008194 new StoreInst(UndefValue::get(LI.getType()),
8195 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008196 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008197 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008198
Chris Lattner81a7a232004-10-16 18:11:37 +00008199 // Instcombine load (constant global) into the value loaded.
8200 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008201 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner81a7a232004-10-16 18:11:37 +00008202 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008203
Chris Lattner81a7a232004-10-16 18:11:37 +00008204 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8205 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8206 if (CE->getOpcode() == Instruction::GetElementPtr) {
8207 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00008208 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008209 if (Constant *V =
8210 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008211 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008212 if (CE->getOperand(0)->isNullValue()) {
8213 // Insert a new store to null instruction before the load to indicate
8214 // that this code is not reachable. We do this instead of inserting
8215 // an unreachable instruction directly because we cannot modify the
8216 // CFG.
8217 new StoreInst(UndefValue::get(LI.getType()),
8218 Constant::getNullValue(Op->getType()), &LI);
8219 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8220 }
8221
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008222 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008223 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8224 return Res;
8225 }
8226 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008227
Chris Lattnera9d84e32005-05-01 04:24:53 +00008228 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008229 // Change select and PHI nodes to select values instead of addresses: this
8230 // helps alias analysis out a lot, allows many others simplifications, and
8231 // exposes redundancy in the code.
8232 //
8233 // Note that we cannot do the transformation unless we know that the
8234 // introduced loads cannot trap! Something like this is valid as long as
8235 // the condition is always false: load (select bool %C, int* null, int* %G),
8236 // but it would not be valid if we transformed it to load from null
8237 // unconditionally.
8238 //
8239 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8240 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008241 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8242 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008243 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008244 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008245 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008246 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008247 return new SelectInst(SI->getCondition(), V1, V2);
8248 }
8249
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008250 // load (select (cond, null, P)) -> load P
8251 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8252 if (C->isNullValue()) {
8253 LI.setOperand(0, SI->getOperand(2));
8254 return &LI;
8255 }
8256
8257 // load (select (cond, P, null)) -> load P
8258 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8259 if (C->isNullValue()) {
8260 LI.setOperand(0, SI->getOperand(1));
8261 return &LI;
8262 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008263 }
8264 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008265 return 0;
8266}
8267
Reid Spencere928a152007-01-19 21:20:31 +00008268/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner72684fe2005-01-31 05:51:45 +00008269/// when possible.
8270static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8271 User *CI = cast<User>(SI.getOperand(1));
8272 Value *CastOp = CI->getOperand(0);
8273
8274 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8275 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8276 const Type *SrcPTy = SrcTy->getElementType();
8277
Reid Spencer31a4ef42007-01-22 05:51:25 +00008278 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008279 // If the source is an array, the code below will not succeed. Check to
8280 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8281 // constants.
8282 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8283 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8284 if (ASrcTy->getNumElements() != 0) {
Chris Lattnerf96f4a82007-01-31 04:40:53 +00008285 Value* Idxs[2];
8286 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8287 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattner72684fe2005-01-31 05:51:45 +00008288 SrcTy = cast<PointerType>(CastOp->getType());
8289 SrcPTy = SrcTy->getElementType();
8290 }
8291
Reid Spencer9a4bed02007-01-20 23:35:48 +00008292 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8293 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8294 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattner72684fe2005-01-31 05:51:45 +00008295
8296 // Okay, we are casting from one integer or pointer type to another of
Reid Spencerc050af92007-01-18 18:54:33 +00008297 // the same size. Instead of casting the pointer before
8298 // the store, cast the value to be stored.
Chris Lattner72684fe2005-01-31 05:51:45 +00008299 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008300 Value *SIOp0 = SI.getOperand(0);
Reid Spencerc050af92007-01-18 18:54:33 +00008301 Instruction::CastOps opcode = Instruction::BitCast;
8302 const Type* CastSrcTy = SIOp0->getType();
8303 const Type* CastDstTy = SrcPTy;
8304 if (isa<PointerType>(CastDstTy)) {
8305 if (CastSrcTy->isInteger())
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008306 opcode = Instruction::IntToPtr;
Reid Spencer9a4bed02007-01-20 23:35:48 +00008307 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008308 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008309 opcode = Instruction::PtrToInt;
8310 }
8311 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencerc050af92007-01-18 18:54:33 +00008312 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008313 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008314 NewCast = IC.InsertNewInstBefore(
Reid Spencerc050af92007-01-18 18:54:33 +00008315 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8316 SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008317 return new StoreInst(NewCast, CastOp);
8318 }
8319 }
8320 }
8321 return 0;
8322}
8323
Chris Lattner31f486c2005-01-31 05:36:43 +00008324Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8325 Value *Val = SI.getOperand(0);
8326 Value *Ptr = SI.getOperand(1);
8327
8328 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008329 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008330 ++NumCombined;
8331 return 0;
8332 }
Chris Lattnera4beeef2007-01-15 06:51:56 +00008333
8334 // If the RHS is an alloca with a single use, zapify the store, making the
8335 // alloca dead.
8336 if (Ptr->hasOneUse()) {
8337 if (isa<AllocaInst>(Ptr)) {
8338 EraseInstFromFunction(SI);
8339 ++NumCombined;
8340 return 0;
8341 }
8342
8343 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8344 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8345 GEP->getOperand(0)->hasOneUse()) {
8346 EraseInstFromFunction(SI);
8347 ++NumCombined;
8348 return 0;
8349 }
8350 }
Chris Lattner31f486c2005-01-31 05:36:43 +00008351
Chris Lattner5997cf92006-02-08 03:25:32 +00008352 // Do really simple DSE, to catch cases where there are several consequtive
8353 // stores to the same location, separated by a few arithmetic operations. This
8354 // situation often occurs with bitfield accesses.
8355 BasicBlock::iterator BBI = &SI;
8356 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8357 --ScanInsts) {
8358 --BBI;
8359
8360 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8361 // Prev store isn't volatile, and stores to the same location?
8362 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8363 ++NumDeadStore;
8364 ++BBI;
8365 EraseInstFromFunction(*PrevSI);
8366 continue;
8367 }
8368 break;
8369 }
8370
Chris Lattnerdab43b22006-05-26 19:19:20 +00008371 // If this is a load, we have to stop. However, if the loaded value is from
8372 // the pointer we're loading and is producing the pointer we're storing,
8373 // then *this* store is dead (X = load P; store X -> P).
8374 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8375 if (LI == Val && LI->getOperand(0) == Ptr) {
8376 EraseInstFromFunction(SI);
8377 ++NumCombined;
8378 return 0;
8379 }
8380 // Otherwise, this is a load from some other location. Stores before it
8381 // may not be dead.
8382 break;
8383 }
8384
Chris Lattner5997cf92006-02-08 03:25:32 +00008385 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008386 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008387 break;
8388 }
8389
8390
8391 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008392
8393 // store X, null -> turns into 'unreachable' in SimplifyCFG
8394 if (isa<ConstantPointerNull>(Ptr)) {
8395 if (!isa<UndefValue>(Val)) {
8396 SI.setOperand(0, UndefValue::get(Val->getType()));
8397 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008398 AddToWorkList(U); // Dropped a use.
Chris Lattner31f486c2005-01-31 05:36:43 +00008399 ++NumCombined;
8400 }
8401 return 0; // Do not modify these!
8402 }
8403
8404 // store undef, Ptr -> noop
8405 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008406 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008407 ++NumCombined;
8408 return 0;
8409 }
8410
Chris Lattner72684fe2005-01-31 05:51:45 +00008411 // If the pointer destination is a cast, see if we can fold the cast into the
8412 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008413 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008414 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8415 return Res;
8416 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008417 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008418 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8419 return Res;
8420
Chris Lattner219175c2005-09-12 23:23:25 +00008421
8422 // If this store is the last instruction in the basic block, and if the block
8423 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008424 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008425 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8426 if (BI->isUnconditional()) {
8427 // Check to see if the successor block has exactly two incoming edges. If
8428 // so, see if the other predecessor contains a store to the same location.
8429 // if so, insert a PHI node (if needed) and move the stores down.
8430 BasicBlock *Dest = BI->getSuccessor(0);
8431
8432 pred_iterator PI = pred_begin(Dest);
8433 BasicBlock *Other = 0;
8434 if (*PI != BI->getParent())
8435 Other = *PI;
8436 ++PI;
8437 if (PI != pred_end(Dest)) {
8438 if (*PI != BI->getParent())
8439 if (Other)
8440 Other = 0;
8441 else
8442 Other = *PI;
8443 if (++PI != pred_end(Dest))
8444 Other = 0;
8445 }
8446 if (Other) { // If only one other pred...
8447 BBI = Other->getTerminator();
8448 // Make sure this other block ends in an unconditional branch and that
8449 // there is an instruction before the branch.
8450 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8451 BBI != Other->begin()) {
8452 --BBI;
8453 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8454
8455 // If this instruction is a store to the same location.
8456 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8457 // Okay, we know we can perform this transformation. Insert a PHI
8458 // node now if we need it.
8459 Value *MergedVal = OtherStore->getOperand(0);
8460 if (MergedVal != SI.getOperand(0)) {
8461 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8462 PN->reserveOperandSpace(2);
8463 PN->addIncoming(SI.getOperand(0), SI.getParent());
8464 PN->addIncoming(OtherStore->getOperand(0), Other);
8465 MergedVal = InsertNewInstBefore(PN, Dest->front());
8466 }
8467
8468 // Advance to a place where it is safe to insert the new store and
8469 // insert it.
8470 BBI = Dest->begin();
8471 while (isa<PHINode>(BBI)) ++BBI;
8472 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8473 OtherStore->isVolatile()), *BBI);
8474
8475 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008476 EraseInstFromFunction(SI);
8477 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008478 ++NumCombined;
8479 return 0;
8480 }
8481 }
8482 }
8483 }
8484
Chris Lattner31f486c2005-01-31 05:36:43 +00008485 return 0;
8486}
8487
8488
Chris Lattner9eef8a72003-06-04 04:46:00 +00008489Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8490 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008491 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008492 BasicBlock *TrueDest;
8493 BasicBlock *FalseDest;
8494 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8495 !isa<Constant>(X)) {
8496 // Swap Destinations and condition...
8497 BI.setCondition(X);
8498 BI.setSuccessor(0, FalseDest);
8499 BI.setSuccessor(1, TrueDest);
8500 return &BI;
8501 }
8502
Reid Spencer266e42b2006-12-23 06:05:41 +00008503 // Cannonicalize fcmp_one -> fcmp_oeq
8504 FCmpInst::Predicate FPred; Value *Y;
8505 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8506 TrueDest, FalseDest)))
8507 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8508 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8509 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008510 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008511 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8512 NewSCC->takeName(I);
Reid Spencer266e42b2006-12-23 06:05:41 +00008513 // Swap Destinations and condition...
8514 BI.setCondition(NewSCC);
8515 BI.setSuccessor(0, FalseDest);
8516 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008517 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008518 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008519 AddToWorkList(NewSCC);
Reid Spencer266e42b2006-12-23 06:05:41 +00008520 return &BI;
8521 }
8522
8523 // Cannonicalize icmp_ne -> icmp_eq
8524 ICmpInst::Predicate IPred;
8525 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8526 TrueDest, FalseDest)))
8527 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8528 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8529 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8530 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencer266e42b2006-12-23 06:05:41 +00008531 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008532 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8533 NewSCC->takeName(I);
Chris Lattnere967b342003-06-04 05:10:11 +00008534 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008535 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008536 BI.setSuccessor(0, FalseDest);
8537 BI.setSuccessor(1, TrueDest);
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008538 RemoveFromWorkList(I);
Chris Lattner6e0123b2007-02-11 01:23:03 +00008539 I->eraseFromParent();;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008540 AddToWorkList(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008541 return &BI;
8542 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008543
Chris Lattner9eef8a72003-06-04 04:46:00 +00008544 return 0;
8545}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008546
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008547Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8548 Value *Cond = SI.getCondition();
8549 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8550 if (I->getOpcode() == Instruction::Add)
8551 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8552 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8553 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008554 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008555 AddRHS));
8556 SI.setOperand(0, I->getOperand(0));
Chris Lattnerb15e2b12007-03-02 21:28:56 +00008557 AddToWorkList(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008558 return &SI;
8559 }
8560 }
8561 return 0;
8562}
8563
Chris Lattner6bc98652006-03-05 00:22:33 +00008564/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8565/// is to leave as a vector operation.
8566static bool CheapToScalarize(Value *V, bool isConstant) {
8567 if (isa<ConstantAggregateZero>(V))
8568 return true;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008569 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008570 if (isConstant) return true;
8571 // If all elts are the same, we can extract.
8572 Constant *Op0 = C->getOperand(0);
8573 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8574 if (C->getOperand(i) != Op0)
8575 return false;
8576 return true;
8577 }
8578 Instruction *I = dyn_cast<Instruction>(V);
8579 if (!I) return false;
8580
8581 // Insert element gets simplified to the inserted element or is deleted if
8582 // this is constant idx extract element and its a constant idx insertelt.
8583 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8584 isa<ConstantInt>(I->getOperand(2)))
8585 return true;
8586 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8587 return true;
8588 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8589 if (BO->hasOneUse() &&
8590 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8591 CheapToScalarize(BO->getOperand(1), isConstant)))
8592 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008593 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8594 if (CI->hasOneUse() &&
8595 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8596 CheapToScalarize(CI->getOperand(1), isConstant)))
8597 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008598
8599 return false;
8600}
8601
Chris Lattner945e4372007-02-14 05:52:17 +00008602/// Read and decode a shufflevector mask.
8603///
8604/// It turns undef elements into values that are larger than the number of
8605/// elements in the input.
Chris Lattner12249be2006-05-25 23:48:38 +00008606static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8607 unsigned NElts = SVI->getType()->getNumElements();
8608 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8609 return std::vector<unsigned>(NElts, 0);
8610 if (isa<UndefValue>(SVI->getOperand(2)))
8611 return std::vector<unsigned>(NElts, 2*NElts);
8612
8613 std::vector<unsigned> Result;
Reid Spencerd84d35b2007-02-15 02:26:10 +00008614 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner12249be2006-05-25 23:48:38 +00008615 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8616 if (isa<UndefValue>(CP->getOperand(i)))
8617 Result.push_back(NElts*2); // undef -> 8
8618 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008619 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008620 return Result;
8621}
8622
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008623/// FindScalarElement - Given a vector and an element number, see if the scalar
8624/// value is already around as a register, for example if it were inserted then
8625/// extracted from the vector.
8626static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008627 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8628 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008629 unsigned Width = PTy->getNumElements();
8630 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008631 return UndefValue::get(PTy->getElementType());
8632
8633 if (isa<UndefValue>(V))
8634 return UndefValue::get(PTy->getElementType());
8635 else if (isa<ConstantAggregateZero>(V))
8636 return Constant::getNullValue(PTy->getElementType());
Reid Spencerd84d35b2007-02-15 02:26:10 +00008637 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008638 return CP->getOperand(EltNo);
8639 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8640 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008641 if (!isa<ConstantInt>(III->getOperand(2)))
8642 return 0;
8643 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008644
8645 // If this is an insert to the element we are looking for, return the
8646 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008647 if (EltNo == IIElt)
8648 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008649
8650 // Otherwise, the insertelement doesn't modify the value, recurse on its
8651 // vector input.
8652 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008653 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008654 unsigned InEl = getShuffleMask(SVI)[EltNo];
8655 if (InEl < Width)
8656 return FindScalarElement(SVI->getOperand(0), InEl);
8657 else if (InEl < Width*2)
8658 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8659 else
8660 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008661 }
8662
8663 // Otherwise, we don't know.
8664 return 0;
8665}
8666
Robert Bocchinoa8352962006-01-13 22:48:06 +00008667Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008668
Chris Lattner92346c32006-03-31 18:25:14 +00008669 // If packed val is undef, replace extract with scalar undef.
8670 if (isa<UndefValue>(EI.getOperand(0)))
8671 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8672
8673 // If packed val is constant 0, replace extract with scalar 0.
8674 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8675 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8676
Reid Spencerd84d35b2007-02-15 02:26:10 +00008677 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008678 // If packed val is constant with uniform operands, replace EI
8679 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008680 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008681 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008682 if (C->getOperand(i) != op0) {
8683 op0 = 0;
8684 break;
8685 }
8686 if (op0)
8687 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008688 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008689
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008690 // If extracting a specified index from the vector, see if we can recursively
8691 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008692 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008693 // This instruction only demands the single element from the input vector.
8694 // If the input vector has a single use, simplify it based on this use
8695 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008696 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008697 if (EI.getOperand(0)->hasOneUse()) {
8698 uint64_t UndefElts;
8699 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008700 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008701 UndefElts)) {
8702 EI.setOperand(0, V);
8703 return &EI;
8704 }
8705 }
8706
Reid Spencere0fc4df2006-10-20 07:07:24 +00008707 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008708 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008709 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008710
Chris Lattner83f65782006-05-25 22:53:38 +00008711 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008712 if (I->hasOneUse()) {
8713 // Push extractelement into predecessor operation if legal and
8714 // profitable to do so
8715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008716 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8717 if (CheapToScalarize(BO, isConstantElt)) {
8718 ExtractElementInst *newEI0 =
8719 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8720 EI.getName()+".lhs");
8721 ExtractElementInst *newEI1 =
8722 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8723 EI.getName()+".rhs");
8724 InsertNewInstBefore(newEI0, EI);
8725 InsertNewInstBefore(newEI1, EI);
8726 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8727 }
Reid Spencerde46e482006-11-02 20:25:50 +00008728 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008729 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008730 PointerType::get(EI.getType()), EI);
8731 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008732 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008733 InsertNewInstBefore(GEP, EI);
8734 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008735 }
8736 }
8737 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8738 // Extracting the inserted element?
8739 if (IE->getOperand(2) == EI.getOperand(1))
8740 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8741 // If the inserted and extracted elements are constants, they must not
8742 // be the same value, extract from the pre-inserted value instead.
8743 if (isa<Constant>(IE->getOperand(2)) &&
8744 isa<Constant>(EI.getOperand(1))) {
8745 AddUsesToWorkList(EI);
8746 EI.setOperand(0, IE->getOperand(0));
8747 return &EI;
8748 }
8749 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8750 // If this is extracting an element from a shufflevector, figure out where
8751 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008752 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8753 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008754 Value *Src;
8755 if (SrcIdx < SVI->getType()->getNumElements())
8756 Src = SVI->getOperand(0);
8757 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8758 SrcIdx -= SVI->getType()->getNumElements();
8759 Src = SVI->getOperand(1);
8760 } else {
8761 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008762 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008763 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008764 }
8765 }
Chris Lattner83f65782006-05-25 22:53:38 +00008766 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008767 return 0;
8768}
8769
Chris Lattner90951862006-04-16 00:51:47 +00008770/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8771/// elements from either LHS or RHS, return the shuffle mask and true.
8772/// Otherwise, return false.
8773static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8774 std::vector<Constant*> &Mask) {
8775 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8776 "Invalid CollectSingleShuffleElements");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008777 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner90951862006-04-16 00:51:47 +00008778
8779 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008780 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008781 return true;
8782 } else if (V == LHS) {
8783 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008784 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008785 return true;
8786 } else if (V == RHS) {
8787 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008788 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008789 return true;
8790 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8791 // If this is an insert of an extract from some other vector, include it.
8792 Value *VecOp = IEI->getOperand(0);
8793 Value *ScalarOp = IEI->getOperand(1);
8794 Value *IdxOp = IEI->getOperand(2);
8795
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008796 if (!isa<ConstantInt>(IdxOp))
8797 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008798 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008799
8800 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8801 // Okay, we can handle this if the vector we are insertinting into is
8802 // transitively ok.
8803 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8804 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008805 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008806 return true;
8807 }
8808 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8809 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008810 EI->getOperand(0)->getType() == V->getType()) {
8811 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008812 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008813
8814 // This must be extracting from either LHS or RHS.
8815 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8816 // Okay, we can handle this if the vector we are insertinting into is
8817 // transitively ok.
8818 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8819 // If so, update the mask to reflect the inserted value.
8820 if (EI->getOperand(0) == LHS) {
8821 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008822 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008823 } else {
8824 assert(EI->getOperand(0) == RHS);
8825 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008826 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008827
8828 }
8829 return true;
8830 }
8831 }
8832 }
8833 }
8834 }
8835 // TODO: Handle shufflevector here!
8836
8837 return false;
8838}
8839
8840/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8841/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8842/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008843static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008844 Value *&RHS) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00008845 assert(isa<VectorType>(V->getType()) &&
Chris Lattner90951862006-04-16 00:51:47 +00008846 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008847 "Invalid shuffle!");
Reid Spencerd84d35b2007-02-15 02:26:10 +00008848 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner39fac442006-04-15 01:39:45 +00008849
8850 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008851 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008852 return V;
8853 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008854 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008855 return V;
8856 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8857 // If this is an insert of an extract from some other vector, include it.
8858 Value *VecOp = IEI->getOperand(0);
8859 Value *ScalarOp = IEI->getOperand(1);
8860 Value *IdxOp = IEI->getOperand(2);
8861
8862 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8863 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8864 EI->getOperand(0)->getType() == V->getType()) {
8865 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008866 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8867 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008868
8869 // Either the extracted from or inserted into vector must be RHSVec,
8870 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008871 if (EI->getOperand(0) == RHS || RHS == 0) {
8872 RHS = EI->getOperand(0);
8873 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008874 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008875 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008876 return V;
8877 }
8878
Chris Lattner90951862006-04-16 00:51:47 +00008879 if (VecOp == RHS) {
8880 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008881 // Everything but the extracted element is replaced with the RHS.
8882 for (unsigned i = 0; i != NumElts; ++i) {
8883 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008884 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008885 }
8886 return V;
8887 }
Chris Lattner90951862006-04-16 00:51:47 +00008888
8889 // If this insertelement is a chain that comes from exactly these two
8890 // vectors, return the vector and the effective shuffle.
8891 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8892 return EI->getOperand(0);
8893
Chris Lattner39fac442006-04-15 01:39:45 +00008894 }
8895 }
8896 }
Chris Lattner90951862006-04-16 00:51:47 +00008897 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008898
8899 // Otherwise, can't do anything fancy. Return an identity vector.
8900 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008901 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008902 return V;
8903}
8904
8905Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8906 Value *VecOp = IE.getOperand(0);
8907 Value *ScalarOp = IE.getOperand(1);
8908 Value *IdxOp = IE.getOperand(2);
8909
8910 // If the inserted element was extracted from some other vector, and if the
8911 // indexes are constant, try to turn this into a shufflevector operation.
8912 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8913 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8914 EI->getOperand(0)->getType() == IE.getType()) {
8915 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008916 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8917 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008918
8919 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8920 return ReplaceInstUsesWith(IE, VecOp);
8921
8922 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8923 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8924
8925 // If we are extracting a value from a vector, then inserting it right
8926 // back into the same place, just use the input vector.
8927 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8928 return ReplaceInstUsesWith(IE, VecOp);
8929
8930 // We could theoretically do this for ANY input. However, doing so could
8931 // turn chains of insertelement instructions into a chain of shufflevector
8932 // instructions, and right now we do not merge shufflevectors. As such,
8933 // only do this in a situation where it is clear that there is benefit.
8934 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8935 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8936 // the values of VecOp, except then one read from EIOp0.
8937 // Build a new shuffle mask.
8938 std::vector<Constant*> Mask;
8939 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008940 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008941 else {
8942 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008943 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008944 NumVectorElts));
8945 }
Reid Spencerc635f472006-12-31 05:48:39 +00008946 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008947 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencerd84d35b2007-02-15 02:26:10 +00008948 ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008949 }
8950
8951 // If this insertelement isn't used by some other insertelement, turn it
8952 // (and any insertelements it points to), into one big shuffle.
8953 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8954 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008955 Value *RHS = 0;
8956 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8957 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8958 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencerd84d35b2007-02-15 02:26:10 +00008959 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008960 }
8961 }
8962 }
8963
8964 return 0;
8965}
8966
8967
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008968Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8969 Value *LHS = SVI.getOperand(0);
8970 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008971 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008972
8973 bool MadeChange = false;
8974
Chris Lattner2deeaea2006-10-05 06:55:50 +00008975 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008976 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008977 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8978
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008979 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008980 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008981 if (isa<UndefValue>(SVI.getOperand(1))) {
8982 // Scan to see if there are any references to the RHS. If so, replace them
8983 // with undef element refs and set MadeChange to true.
8984 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8985 if (Mask[i] >= e && Mask[i] != 2*e) {
8986 Mask[i] = 2*e;
8987 MadeChange = true;
8988 }
8989 }
8990
8991 if (MadeChange) {
8992 // Remap any references to RHS to use LHS.
8993 std::vector<Constant*> Elts;
8994 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8995 if (Mask[i] == 2*e)
8996 Elts.push_back(UndefValue::get(Type::Int32Ty));
8997 else
8998 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8999 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00009000 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00009001 }
9002 }
Chris Lattner39fac442006-04-15 01:39:45 +00009003
Chris Lattner12249be2006-05-25 23:48:38 +00009004 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9005 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9006 if (LHS == RHS || isa<UndefValue>(LHS)) {
9007 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009008 // shuffle(undef,undef,mask) -> undef.
9009 return ReplaceInstUsesWith(SVI, LHS);
9010 }
9011
Chris Lattner12249be2006-05-25 23:48:38 +00009012 // Remap any references to RHS to use LHS.
9013 std::vector<Constant*> Elts;
9014 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00009015 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00009016 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009017 else {
9018 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9019 (Mask[i] < e && isa<UndefValue>(LHS)))
9020 Mask[i] = 2*e; // Turn into undef.
9021 else
9022 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00009023 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009024 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009025 }
Chris Lattner12249be2006-05-25 23:48:38 +00009026 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009027 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencerd84d35b2007-02-15 02:26:10 +00009028 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009029 LHS = SVI.getOperand(0);
9030 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009031 MadeChange = true;
9032 }
9033
Chris Lattner0e477162006-05-26 00:29:06 +00009034 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00009035 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00009036
Chris Lattner12249be2006-05-25 23:48:38 +00009037 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9038 if (Mask[i] >= e*2) continue; // Ignore undef values.
9039 // Is this an identity shuffle of the LHS value?
9040 isLHSID &= (Mask[i] == i);
9041
9042 // Is this an identity shuffle of the RHS value?
9043 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00009044 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009045
Chris Lattner12249be2006-05-25 23:48:38 +00009046 // Eliminate identity shuffles.
9047 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9048 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009049
Chris Lattner0e477162006-05-26 00:29:06 +00009050 // If the LHS is a shufflevector itself, see if we can combine it with this
9051 // one without producing an unusual shuffle. Here we are really conservative:
9052 // we are absolutely afraid of producing a shuffle mask not in the input
9053 // program, because the code gen may not be smart enough to turn a merged
9054 // shuffle into two specific shuffles: it may produce worse code. As such,
9055 // we only merge two shuffles if the result is one of the two input shuffle
9056 // masks. In this case, merging the shuffles just removes one instruction,
9057 // which we know is safe. This is good for things like turning:
9058 // (splat(splat)) -> splat.
9059 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9060 if (isa<UndefValue>(RHS)) {
9061 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9062
9063 std::vector<unsigned> NewMask;
9064 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9065 if (Mask[i] >= 2*e)
9066 NewMask.push_back(2*e);
9067 else
9068 NewMask.push_back(LHSMask[Mask[i]]);
9069
9070 // If the result mask is equal to the src shuffle or this shuffle mask, do
9071 // the replacement.
9072 if (NewMask == LHSMask || NewMask == Mask) {
9073 std::vector<Constant*> Elts;
9074 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9075 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00009076 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00009077 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00009078 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00009079 }
9080 }
9081 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9082 LHSSVI->getOperand(1),
Reid Spencerd84d35b2007-02-15 02:26:10 +00009083 ConstantVector::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00009084 }
9085 }
9086 }
Chris Lattner4284f642007-01-30 22:32:46 +00009087
Chris Lattnerfbb77a42006-04-10 22:45:52 +00009088 return MadeChange ? &SVI : 0;
9089}
9090
9091
Robert Bocchinoa8352962006-01-13 22:48:06 +00009092
Chris Lattner39c98bb2004-12-08 23:43:58 +00009093
9094/// TryToSinkInstruction - Try to move the specified instruction from its
9095/// current block into the beginning of DestBlock, which can only happen if it's
9096/// safe to move the instruction past all of the instructions between it and the
9097/// end of its block.
9098static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9099 assert(I->hasOneUse() && "Invariants didn't hold!");
9100
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009101 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9102 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009103
Chris Lattner39c98bb2004-12-08 23:43:58 +00009104 // Do not sink alloca instructions out of the entry block.
9105 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9106 return false;
9107
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009108 // We can only sink load instructions if there is nothing between the load and
9109 // the end of block that could change the value.
9110 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009111 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9112 Scan != E; ++Scan)
9113 if (Scan->mayWriteToMemory())
9114 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009115 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009116
9117 BasicBlock::iterator InsertPos = DestBlock->begin();
9118 while (isa<PHINode>(InsertPos)) ++InsertPos;
9119
Chris Lattner9f269e42005-08-08 19:11:57 +00009120 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009121 ++NumSunkInst;
9122 return true;
9123}
9124
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009125
9126/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9127/// all reachable code to the worklist.
9128///
9129/// This has a couple of tricks to make the code faster and more powerful. In
9130/// particular, we constant fold and DCE instructions as we go, to avoid adding
9131/// them to the worklist (this significantly speeds up instcombine on code where
9132/// many instructions are dead or constant). Additionally, if we find a branch
9133/// whose condition is a known constant, we only visit the reachable successors.
9134///
9135static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner7907e5f2007-02-15 19:41:52 +00009136 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009137 InstCombiner &IC,
Chris Lattner1443bc52006-05-11 17:11:52 +00009138 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009139 // We have now visited this block! If we've already been here, bail out.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009140 if (!Visited.insert(BB)) return;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009141
9142 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9143 Instruction *Inst = BBI++;
9144
9145 // DCE instruction if trivially dead.
9146 if (isInstructionTriviallyDead(Inst)) {
9147 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009148 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009149 Inst->eraseFromParent();
9150 continue;
9151 }
9152
9153 // ConstantProp instruction if trivially constant.
Chris Lattnere3eda252007-01-30 23:16:15 +00009154 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009155 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009156 Inst->replaceAllUsesWith(C);
9157 ++NumConstProp;
9158 Inst->eraseFromParent();
9159 continue;
9160 }
9161
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009162 IC.AddToWorkList(Inst);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009163 }
9164
9165 // Recursively visit successors. If this is a branch or switch on a constant,
9166 // only visit the reachable successor.
9167 TerminatorInst *TI = BB->getTerminator();
9168 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00009169 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009170 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009171 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009172 return;
9173 }
9174 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9175 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9176 // See if this is an explicit destination.
9177 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9178 if (SI->getCaseValue(i) == Cond) {
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009179 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009180 return;
9181 }
9182
9183 // Otherwise it is the default destination.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009184 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009185 return;
9186 }
9187 }
9188
9189 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009190 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009191}
9192
Chris Lattner960a5432007-03-03 02:04:50 +00009193bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner260ab202002-04-18 17:39:14 +00009194 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009195 TD = &getAnalysis<TargetData>();
Chris Lattner960a5432007-03-03 02:04:50 +00009196
9197 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9198 << F.getNameStr() << "\n");
Chris Lattnerca081252001-12-14 16:52:21 +00009199
Chris Lattner4ed40f72005-07-07 20:40:38 +00009200 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009201 // Do a depth-first traversal of the function, populate the worklist with
9202 // the reachable instructions. Ignore blocks that are not reachable. Keep
9203 // track of which blocks we visit.
Chris Lattner7907e5f2007-02-15 19:41:52 +00009204 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009205 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009206
Chris Lattner4ed40f72005-07-07 20:40:38 +00009207 // Do a quick scan over the function. If we find any blocks that are
9208 // unreachable, remove any instructions inside of them. This prevents
9209 // the instcombine code from having to deal with some bad special cases.
9210 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9211 if (!Visited.count(BB)) {
9212 Instruction *Term = BB->getTerminator();
9213 while (Term != BB->begin()) { // Remove instrs bottom-up
9214 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009215
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009216 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009217 ++NumDeadInst;
9218
9219 if (!I->use_empty())
9220 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9221 I->eraseFromParent();
9222 }
9223 }
9224 }
Chris Lattnerca081252001-12-14 16:52:21 +00009225
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009226 while (!Worklist.empty()) {
9227 Instruction *I = RemoveOneFromWorkList();
9228 if (I == 0) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00009229
Chris Lattner1443bc52006-05-11 17:11:52 +00009230 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009231 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009232 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009233 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009234 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009235 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009236
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009237 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009238
9239 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009240 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009241 continue;
9242 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009243
Chris Lattner1443bc52006-05-11 17:11:52 +00009244 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere3eda252007-01-30 23:16:15 +00009245 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009246 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009247
Chris Lattner1443bc52006-05-11 17:11:52 +00009248 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009249 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009250 ReplaceInstUsesWith(*I, C);
9251
Chris Lattner99f48c62002-09-02 04:59:56 +00009252 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009253 I->eraseFromParent();
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009254 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009255 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009256 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009257
Chris Lattner39c98bb2004-12-08 23:43:58 +00009258 // See if we can trivially sink this instruction to a successor basic block.
9259 if (I->hasOneUse()) {
9260 BasicBlock *BB = I->getParent();
9261 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9262 if (UserParent != BB) {
9263 bool UserIsSuccessor = false;
9264 // See if the user is one of our successors.
9265 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9266 if (*SI == UserParent) {
9267 UserIsSuccessor = true;
9268 break;
9269 }
9270
9271 // If the user is one of our immediate successors, and if that successor
9272 // only has us as a predecessors (we'd have to split the critical edge
9273 // otherwise), we can keep going.
9274 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9275 next(pred_begin(UserParent)) == pred_end(UserParent))
9276 // Okay, the CFG is simple enough, try to sink this instruction.
9277 Changed |= TryToSinkInstruction(I, UserParent);
9278 }
9279 }
9280
Chris Lattnerca081252001-12-14 16:52:21 +00009281 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009282 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009283 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009284 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009285 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009286 DOUT << "IC: Old = " << *I
9287 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009288
Chris Lattner396dbfe2004-06-09 05:08:07 +00009289 // Everything uses the new instruction now.
9290 I->replaceAllUsesWith(Result);
9291
9292 // Push the new instruction and any users onto the worklist.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009293 AddToWorkList(Result);
Chris Lattner396dbfe2004-06-09 05:08:07 +00009294 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009295
Chris Lattner6e0123b2007-02-11 01:23:03 +00009296 // Move the name to the new instruction first.
9297 Result->takeName(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009298
9299 // Insert the new instruction into the basic block...
9300 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009301 BasicBlock::iterator InsertPos = I;
9302
9303 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9304 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9305 ++InsertPos;
9306
9307 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009308
Chris Lattner63d75af2004-05-01 23:27:23 +00009309 // Make sure that we reprocess all operands now that we reduced their
9310 // use counts.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009311 AddUsesToWorkList(*I);
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009312
Chris Lattner396dbfe2004-06-09 05:08:07 +00009313 // Instructions can end up on the worklist more than once. Make sure
9314 // we do not process an instruction that has been deleted.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009315 RemoveFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009316
9317 // Erase the old instruction.
9318 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009319 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009320 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009321
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009322 // If the instruction was modified, it's possible that it is now dead.
9323 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009324 if (isInstructionTriviallyDead(I)) {
9325 // Make sure we process all operands now that we are reducing their
9326 // use counts.
Chris Lattner960a5432007-03-03 02:04:50 +00009327 AddUsesToWorkList(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009328
Chris Lattner63d75af2004-05-01 23:27:23 +00009329 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009330 // occurrences of this instruction.
Chris Lattnerb15e2b12007-03-02 21:28:56 +00009331 RemoveFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009332 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009333 } else {
Chris Lattner960a5432007-03-03 02:04:50 +00009334 AddToWorkList(I);
9335 AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009336 }
Chris Lattner053c0932002-05-14 15:24:07 +00009337 }
Chris Lattner260ab202002-04-18 17:39:14 +00009338 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009339 }
9340 }
9341
Chris Lattner960a5432007-03-03 02:04:50 +00009342 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattner260ab202002-04-18 17:39:14 +00009343 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009344}
9345
Chris Lattner960a5432007-03-03 02:04:50 +00009346
9347bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner8258b442007-03-04 04:27:24 +00009348 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9349
Chris Lattner960a5432007-03-03 02:04:50 +00009350 bool EverMadeChange = false;
9351
9352 // Iterate while there is work to do.
9353 unsigned Iteration = 0;
9354 while (DoOneIteration(F, Iteration++))
9355 EverMadeChange = true;
9356 return EverMadeChange;
9357}
9358
Brian Gaeke38b79e82004-07-27 17:43:21 +00009359FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009360 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009361}
Brian Gaeke960707c2003-11-11 22:41:34 +00009362