blob: 592e61d040ac0cd734a1c12a27e832956b2d45a5 [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 Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000109
Chris Lattner99f48c62002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000112 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000114
Chris Lattnerf12cc842002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 }
120
Chris Lattner69193f92004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattner260ab202002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000149
Reid Spencer266e42b2006-12-23 06:05:41 +0000150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000171 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000176 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000177 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000178 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000179 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000180 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000181 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000182 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000185
186 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000187 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000188
Chris Lattner970c33a2003-06-19 17:00:31 +0000189 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000190 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000191 bool transformConstExprCastCall(CallSite CS);
192
Chris Lattner69193f92004-04-05 01:30:19 +0000193 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
196 //
Chris Lattner623826c2004-09-28 21:48:02 +0000197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000203 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000204 }
205
Chris Lattner7e794272004-09-24 15:21:34 +0000206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
208 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000211 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattnere79d2492006-04-06 19:19:17 +0000213 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000214 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000215
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000217 WorkList.push_back(C);
218 return C;
219 }
220
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
225 // modified.
226 //
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000228 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000229 if (&I != V) {
230 I.replaceAllUsesWith(V);
231 return &I;
232 } else {
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000236 return &I;
237 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000238 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000239
Chris Lattner2590e512006-02-07 06:56:34 +0000240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
245 //
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
248 if (Old != New)
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000254 return true;
255 }
256
Chris Lattner51ea1272004-02-28 05:22:00 +0000257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
260 // this function.
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000265 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000266 return 0; // Don't do anything with FI
267 }
268
Chris Lattner3ac7c262003-08-13 20:16:26 +0000269 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
273 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000276 Instruction *InsertBefore);
277
Reid Spencer266e42b2006-12-23 06:05:41 +0000278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000281
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
285
Chris Lattner0157e7f2006-02-11 09:31:47 +0000286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
288 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000289
Chris Lattner2deeaea2006-10-05 06:55:50 +0000290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
292
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
297
Chris Lattner7515cab2004-11-14 19:13:23 +0000298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303
304
Chris Lattnerba1cb382003-09-19 17:17:26 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencer74a528b2006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000331}
Chris Lattner260ab202002-04-18 17:39:14 +0000332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337}
338
Chris Lattnere79e8542004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000342 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000343 case Type::SByteTyID:
344 case Type::ShortTyID: return Type::IntTy;
345 case Type::UByteTyID:
346 case Type::UShortTyID: return Type::UIntTy;
347 case Type::FloatTyID: return Type::DoubleTy;
348 default: return Ty;
349 }
350}
351
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000352/// getBitCastOperand - If the specified operand is a CastInst or a constant
353/// expression bitcast, return the operand value, otherwise return null.
354static Value *getBitCastOperand(Value *V) {
355 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000356 return I->getOperand(0);
357 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000358 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000359 return CE->getOperand(0);
360 return 0;
361}
362
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000363/// This function is a wrapper around CastInst::isEliminableCastPair. It
364/// simply extracts arguments and returns what that function returns.
365/// @Determine if it is valid to eliminate a Convert pair
366static Instruction::CastOps
367isEliminableCastPair(
368 const CastInst *CI, ///< The first cast instruction
369 unsigned opcode, ///< The opcode of the second cast instruction
370 const Type *DstTy, ///< The target type for the second cast instruction
371 TargetData *TD ///< The target data for pointer size
372) {
373
374 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
375 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000376
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000377 // Get the opcodes of the two Cast instructions
378 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
379 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000380
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000381 return Instruction::CastOps(
382 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
383 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000384}
385
386/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
387/// in any code being generated. It does not require codegen if V is simple
388/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000389static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
390 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000391 if (V->getType() == Ty || isa<Constant>(V)) return false;
392
393 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000394 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000395 return false;
396
Chris Lattner99155be2006-05-25 23:24:33 +0000397 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000398 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000399 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000400 return false;
401 return true;
402}
403
404/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
405/// InsertBefore instruction. This is specialized a bit to avoid inserting
406/// casts that are known to not do anything...
407///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000408Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
409 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410 Instruction *InsertBefore) {
411 if (V->getType() == DestTy) return V;
412 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000413 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414
Reid Spencer13bc5d72006-12-12 09:18:51 +0000415 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000416}
417
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000418// SimplifyCommutative - This performs a few simplifications for commutative
419// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000420//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421// 1. Order operands such that they are listed from right (least complex) to
422// left (most complex). This puts constants before unary operators before
423// binary operators.
424//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000425// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
426// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000428bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000429 bool Changed = false;
430 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
431 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000432
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000433 if (!I.isAssociative()) return Changed;
434 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
436 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
437 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000438 Constant *Folded = ConstantExpr::get(I.getOpcode(),
439 cast<Constant>(I.getOperand(1)),
440 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000441 I.setOperand(0, Op->getOperand(0));
442 I.setOperand(1, Folded);
443 return true;
444 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
445 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
446 isOnlyUse(Op) && isOnlyUse(Op1)) {
447 Constant *C1 = cast<Constant>(Op->getOperand(1));
448 Constant *C2 = cast<Constant>(Op1->getOperand(1));
449
450 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000451 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000452 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
453 Op1->getOperand(0),
454 Op1->getName(), &I);
455 WorkList.push_back(New);
456 I.setOperand(0, New);
457 I.setOperand(1, Folded);
458 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000459 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000460 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000461 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000462}
Chris Lattnerca081252001-12-14 16:52:21 +0000463
Reid Spencer266e42b2006-12-23 06:05:41 +0000464/// SimplifyCompare - For a CmpInst this function just orders the operands
465/// so that theyare listed from right (least complex) to left (most complex).
466/// This puts constants before unary operators before binary operators.
467bool InstCombiner::SimplifyCompare(CmpInst &I) {
468 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
469 return false;
470 I.swapOperands();
471 // Compare instructions are not associative so there's nothing else we can do.
472 return true;
473}
474
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
476// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000477//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000478static inline Value *dyn_castNegVal(Value *V) {
479 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000480 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000481
Chris Lattner9ad0d552004-12-14 20:08:06 +0000482 // Constants can be considered to be negated values if they can be folded.
483 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
484 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000486}
487
Chris Lattnerbb74e222003-03-10 23:06:50 +0000488static inline Value *dyn_castNotVal(Value *V) {
489 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000490 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491
492 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000493 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000494 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495 return 0;
496}
497
Chris Lattner7fb29e12003-03-11 00:12:48 +0000498// dyn_castFoldableMul - If this value is a multiply that can be folded into
499// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000500// non-constant operand of the multiply, and set CST to point to the multiplier.
501// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000504 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000506 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000507 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000508 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000509 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000510 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000511 // The multiplier is really 1 << CST.
512 Constant *One = ConstantInt::get(V->getType(), 1);
513 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
514 return I->getOperand(0);
515 }
516 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000517 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000518}
Chris Lattner31ae8632002-08-14 17:51:49 +0000519
Chris Lattner0798af32005-01-13 20:14:25 +0000520/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
521/// expression, return it.
522static User *dyn_castGetElementPtr(Value *V) {
523 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
525 if (CE->getOpcode() == Instruction::GetElementPtr)
526 return cast<User>(V);
527 return false;
528}
529
Chris Lattner623826c2004-09-28 21:48:02 +0000530// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000531static ConstantInt *AddOne(ConstantInt *C) {
532 return cast<ConstantInt>(ConstantExpr::getAdd(C,
533 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000534}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000535static ConstantInt *SubOne(ConstantInt *C) {
536 return cast<ConstantInt>(ConstantExpr::getSub(C,
537 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000538}
539
Chris Lattner0157e7f2006-02-11 09:31:47 +0000540/// GetConstantInType - Return a ConstantInt with the specified type and value.
541///
Chris Lattneree0f2802006-02-12 02:07:56 +0000542static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000543 if (Ty->isUnsigned())
544 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000545 else if (Ty->getTypeID() == Type::BoolTyID)
546 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000547 int64_t SVal = Val;
548 SVal <<= 64-Ty->getPrimitiveSizeInBits();
549 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000550 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000551}
552
553
Chris Lattner4534dd592006-02-09 07:38:58 +0000554/// ComputeMaskedBits - Determine which of the bits specified in Mask are
555/// known to be either zero or one and return them in the KnownZero/KnownOne
556/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
557/// processing.
558static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
559 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000560 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
561 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000562 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000563 // optimized based on the contradictory assumption that it is non-zero.
564 // Because instcombine aggressively folds operations with undef args anyway,
565 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000566 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
567 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000568 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000569 KnownZero = ~KnownOne & Mask;
570 return;
571 }
572
573 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000574 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000575 return; // Limit search depth.
576
577 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000578 Instruction *I = dyn_cast<Instruction>(V);
579 if (!I) return;
580
Chris Lattnerfb296922006-05-04 17:33:35 +0000581 Mask &= V->getType()->getIntegralTypeMask();
582
Chris Lattner0157e7f2006-02-11 09:31:47 +0000583 switch (I->getOpcode()) {
584 case Instruction::And:
585 // If either the LHS or the RHS are Zero, the result is zero.
586 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
587 Mask &= ~KnownZero;
588 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
589 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
590 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
591
592 // Output known-1 bits are only known if set in both the LHS & RHS.
593 KnownOne &= KnownOne2;
594 // Output known-0 are known to be clear if zero in either the LHS | RHS.
595 KnownZero |= KnownZero2;
596 return;
597 case Instruction::Or:
598 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
599 Mask &= ~KnownOne;
600 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
603
604 // Output known-0 bits are only known if clear in both the LHS & RHS.
605 KnownZero &= KnownZero2;
606 // Output known-1 are known to be set if set in either the LHS | RHS.
607 KnownOne |= KnownOne2;
608 return;
609 case Instruction::Xor: {
610 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
611 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
613 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
614
615 // Output known-0 bits are known if clear or set in both the LHS & RHS.
616 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
617 // Output known-1 are known to be set if set in only one of the LHS, RHS.
618 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
619 KnownZero = KnownZeroOut;
620 return;
621 }
622 case Instruction::Select:
623 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
627
628 // Only known if known in both the LHS and RHS.
629 KnownOne &= KnownOne2;
630 KnownZero &= KnownZero2;
631 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000632 case Instruction::FPTrunc:
633 case Instruction::FPExt:
634 case Instruction::FPToUI:
635 case Instruction::FPToSI:
636 case Instruction::SIToFP:
637 case Instruction::PtrToInt:
638 case Instruction::UIToFP:
639 case Instruction::IntToPtr:
640 return; // Can't work with floating point or pointers
641 case Instruction::Trunc:
642 // All these have integer operands
643 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
644 return;
645 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000646 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000648 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000649 return;
650 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000651 break;
652 }
653 case Instruction::ZExt: {
654 // Compute the bits in the result that are not present in the input.
655 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000656 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
657 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000658
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000659 Mask &= SrcTy->getIntegralTypeMask();
660 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 // The top bits are known to be zero.
663 KnownZero |= NewBits;
664 return;
665 }
666 case Instruction::SExt: {
667 // Compute the bits in the result that are not present in the input.
668 const Type *SrcTy = I->getOperand(0)->getType();
669 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
670 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
671
672 Mask &= SrcTy->getIntegralTypeMask();
673 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000675
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000676 // If the sign bit of the input is known set or clear, then we know the
677 // top bits of the result.
678 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
679 if (KnownZero & InSignBit) { // Input sign bit known zero
680 KnownZero |= NewBits;
681 KnownOne &= ~NewBits;
682 } else if (KnownOne & InSignBit) { // Input sign bit known set
683 KnownOne |= NewBits;
684 KnownZero &= ~NewBits;
685 } else { // Input sign bit unknown
686 KnownZero &= ~NewBits;
687 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000693 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
694 uint64_t ShiftAmt = SA->getZExtValue();
695 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000698 KnownZero <<= ShiftAmt;
699 KnownOne <<= ShiftAmt;
700 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000701 return;
702 }
703 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000704 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000706 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000707 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000708 uint64_t ShiftAmt = SA->getZExtValue();
709 uint64_t HighBits = (1ULL << ShiftAmt)-1;
710 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000711
Reid Spencerfdff9382006-11-08 06:47:33 +0000712 // Unsigned shift right.
713 Mask <<= ShiftAmt;
714 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
715 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
716 KnownZero >>= ShiftAmt;
717 KnownOne >>= ShiftAmt;
718 KnownZero |= HighBits; // high bits known zero.
719 return;
720 }
721 break;
722 case Instruction::AShr:
723 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
724 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
725 // Compute the new bits that are at the top now.
726 uint64_t ShiftAmt = SA->getZExtValue();
727 uint64_t HighBits = (1ULL << ShiftAmt)-1;
728 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
729
730 // Signed shift right.
731 Mask <<= ShiftAmt;
732 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
733 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
734 KnownZero >>= ShiftAmt;
735 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736
Reid Spencerfdff9382006-11-08 06:47:33 +0000737 // Handle the sign bits.
738 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
739 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000740
Reid Spencerfdff9382006-11-08 06:47:33 +0000741 if (KnownZero & SignBit) { // New bits are known zero.
742 KnownZero |= HighBits;
743 } else if (KnownOne & SignBit) { // New bits are known one.
744 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000745 }
746 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000747 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000749 }
Chris Lattner92a68652006-02-07 08:05:22 +0000750}
751
752/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
753/// this predicate to simplify operations downstream. Mask is known to be zero
754/// for bits that V cannot have.
755static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000756 uint64_t KnownZero, KnownOne;
757 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000760}
761
Chris Lattner0157e7f2006-02-11 09:31:47 +0000762/// ShrinkDemandedConstant - Check to see if the specified operand of the
763/// specified instruction is a constant integer. If so, check to see if there
764/// are any bits set in the constant that are not demanded. If so, shrink the
765/// constant and return true.
766static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
767 uint64_t Demanded) {
768 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
769 if (!OpC) return false;
770
771 // If there are no bits set that aren't demanded, nothing to do.
772 if ((~Demanded & OpC->getZExtValue()) == 0)
773 return false;
774
775 // This is producing any bits that are not needed, shrink the RHS.
776 uint64_t Val = Demanded & OpC->getZExtValue();
777 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
778 return true;
779}
780
Chris Lattneree0f2802006-02-12 02:07:56 +0000781// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
782// set of known zero and one bits, compute the maximum and minimum values that
783// could have the specified known zero and known one bits, returning them in
784// min/max.
785static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
786 uint64_t KnownZero,
787 uint64_t KnownOne,
788 int64_t &Min, int64_t &Max) {
789 uint64_t TypeBits = Ty->getIntegralTypeMask();
790 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
791
792 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
793
794 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
795 // bit if it is unknown.
796 Min = KnownOne;
797 Max = KnownOne|UnknownBits;
798
799 if (SignBit & UnknownBits) { // Sign bit is unknown
800 Min |= SignBit;
801 Max &= ~SignBit;
802 }
803
804 // Sign extend the min/max values.
805 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
806 Min = (Min << ShAmt) >> ShAmt;
807 Max = (Max << ShAmt) >> ShAmt;
808}
809
810// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
811// a set of known zero and one bits, compute the maximum and minimum values that
812// could have the specified known zero and known one bits, returning them in
813// min/max.
814static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
815 uint64_t KnownZero,
816 uint64_t KnownOne,
817 uint64_t &Min,
818 uint64_t &Max) {
819 uint64_t TypeBits = Ty->getIntegralTypeMask();
820 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
821
822 // The minimum value is when the unknown bits are all zeros.
823 Min = KnownOne;
824 // The maximum value is when the unknown bits are all ones.
825 Max = KnownOne|UnknownBits;
826}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000827
828
829/// SimplifyDemandedBits - Look at V. At this point, we know that only the
830/// DemandedMask bits of the result of V are ever used downstream. If we can
831/// use this information to simplify V, do so and return true. Otherwise,
832/// analyze the expression and return a mask of KnownOne and KnownZero bits for
833/// the expression (used to simplify the caller). The KnownZero/One bits may
834/// only be accurate for those bits in the DemandedMask.
835bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
836 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000837 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000838 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
839 // We know all of the bits for a constant!
840 KnownOne = CI->getZExtValue() & DemandedMask;
841 KnownZero = ~KnownOne & DemandedMask;
842 return false;
843 }
844
845 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000846 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000847 if (Depth != 0) { // Not at the root.
848 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
849 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000850 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000851 }
Chris Lattner2590e512006-02-07 06:56:34 +0000852 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000853 // just set the DemandedMask to all bits.
854 DemandedMask = V->getType()->getIntegralTypeMask();
855 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000856 if (V != UndefValue::get(V->getType()))
857 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
858 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000859 } else if (Depth == 6) { // Limit search depth.
860 return false;
861 }
862
863 Instruction *I = dyn_cast<Instruction>(V);
864 if (!I) return false; // Only analyze instructions.
865
Chris Lattnerfb296922006-05-04 17:33:35 +0000866 DemandedMask &= V->getType()->getIntegralTypeMask();
867
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000868 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000869 switch (I->getOpcode()) {
870 default: break;
871 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000872 // If either the LHS or the RHS are Zero, the result is zero.
873 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
874 KnownZero, KnownOne, Depth+1))
875 return true;
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
877
878 // If something is known zero on the RHS, the bits aren't demanded on the
879 // LHS.
880 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
881 KnownZero2, KnownOne2, Depth+1))
882 return true;
883 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
884
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000885 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 // These bits cannot contribute to the result of the 'and'.
887 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
888 return UpdateValueUsesWith(I, I->getOperand(0));
889 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
890 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000891
892 // If all of the demanded bits in the inputs are known zeros, return zero.
893 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
894 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
895
Chris Lattner0157e7f2006-02-11 09:31:47 +0000896 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000897 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000898 return UpdateValueUsesWith(I, I);
899
900 // Output known-1 bits are only known if set in both the LHS & RHS.
901 KnownOne &= KnownOne2;
902 // Output known-0 are known to be clear if zero in either the LHS | RHS.
903 KnownZero |= KnownZero2;
904 break;
905 case Instruction::Or:
906 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
907 KnownZero, KnownOne, Depth+1))
908 return true;
909 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
910 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
911 KnownZero2, KnownOne2, Depth+1))
912 return true;
913 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
914
915 // If all of the demanded bits are known zero on one side, return the other.
916 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000917 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000919 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000920 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000921
922 // If all of the potentially set bits on one side are known to be set on
923 // the other side, just use the 'other' side.
924 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
925 (DemandedMask & (~KnownZero)))
926 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000927 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
928 (DemandedMask & (~KnownZero2)))
929 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000930
931 // If the RHS is a constant, see if we can simplify it.
932 if (ShrinkDemandedConstant(I, 1, DemandedMask))
933 return UpdateValueUsesWith(I, I);
934
935 // Output known-0 bits are only known if clear in both the LHS & RHS.
936 KnownZero &= KnownZero2;
937 // Output known-1 are known to be set if set in either the LHS | RHS.
938 KnownOne |= KnownOne2;
939 break;
940 case Instruction::Xor: {
941 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
942 KnownZero, KnownOne, Depth+1))
943 return true;
944 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
945 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
946 KnownZero2, KnownOne2, Depth+1))
947 return true;
948 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
949
950 // If all of the demanded bits are known zero on one side, return the other.
951 // These bits cannot contribute to the result of the 'xor'.
952 if ((DemandedMask & KnownZero) == DemandedMask)
953 return UpdateValueUsesWith(I, I->getOperand(0));
954 if ((DemandedMask & KnownZero2) == DemandedMask)
955 return UpdateValueUsesWith(I, I->getOperand(1));
956
957 // Output known-0 bits are known if clear or set in both the LHS & RHS.
958 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
959 // Output known-1 are known to be set if set in only one of the LHS, RHS.
960 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
961
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000962 // If all of the demanded bits are known to be zero on one side or the
963 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000964 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000965 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
966 Instruction *Or =
967 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
968 I->getName());
969 InsertNewInstBefore(Or, *I);
970 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000971 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972
Chris Lattner5b2edb12006-02-12 08:02:11 +0000973 // If all of the demanded bits on one side are known, and all of the set
974 // bits on that side are also known to be set on the other side, turn this
975 // into an AND, as we know the bits will be cleared.
976 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
977 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
978 if ((KnownOne & KnownOne2) == KnownOne) {
979 Constant *AndC = GetConstantInType(I->getType(),
980 ~KnownOne & DemandedMask);
981 Instruction *And =
982 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
983 InsertNewInstBefore(And, *I);
984 return UpdateValueUsesWith(I, And);
985 }
986 }
987
Chris Lattner0157e7f2006-02-11 09:31:47 +0000988 // If the RHS is a constant, see if we can simplify it.
989 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
990 if (ShrinkDemandedConstant(I, 1, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992
993 KnownZero = KnownZeroOut;
994 KnownOne = KnownOneOut;
995 break;
996 }
997 case Instruction::Select:
998 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1000 return true;
1001 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1002 KnownZero2, KnownOne2, Depth+1))
1003 return true;
1004 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1005 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1006
1007 // If the operands are constants, see if we can simplify them.
1008 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1009 return UpdateValueUsesWith(I, I);
1010 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1011 return UpdateValueUsesWith(I, I);
1012
1013 // Only known if known in both the LHS and RHS.
1014 KnownOne &= KnownOne2;
1015 KnownZero &= KnownZero2;
1016 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001017 case Instruction::Trunc:
1018 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1019 KnownZero, KnownOne, Depth+1))
1020 return true;
1021 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1022 break;
1023 case Instruction::BitCast:
1024 if (!I->getOperand(0)->getType()->isIntegral())
1025 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001026
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001027 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1028 KnownZero, KnownOne, Depth+1))
1029 return true;
1030 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1031 break;
1032 case Instruction::ZExt: {
1033 // Compute the bits in the result that are not present in the input.
1034 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001035 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1036 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1037
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001038 DemandedMask &= SrcTy->getIntegralTypeMask();
1039 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1040 KnownZero, KnownOne, Depth+1))
1041 return true;
1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1043 // The top bits are known to be zero.
1044 KnownZero |= NewBits;
1045 break;
1046 }
1047 case Instruction::SExt: {
1048 // Compute the bits in the result that are not present in the input.
1049 const Type *SrcTy = I->getOperand(0)->getType();
1050 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1051 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1052
1053 // Get the sign bit for the source type
1054 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1055 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001056
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001057 // If any of the sign extended bits are demanded, we know that the sign
1058 // bit is demanded.
1059 if (NewBits & DemandedMask)
1060 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001061
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001062 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1063 KnownZero, KnownOne, Depth+1))
1064 return true;
1065 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001067 // If the sign bit of the input is known set or clear, then we know the
1068 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001069
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001070 // If the input sign bit is known zero, or if the NewBits are not demanded
1071 // convert this into a zero extension.
1072 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1073 // Convert to ZExt cast
1074 CastInst *NewCast = CastInst::create(
1075 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1076 return UpdateValueUsesWith(I, NewCast);
1077 } else if (KnownOne & InSignBit) { // Input sign bit known set
1078 KnownOne |= NewBits;
1079 KnownZero &= ~NewBits;
1080 } else { // Input sign bit unknown
1081 KnownZero &= ~NewBits;
1082 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001083 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001084 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001085 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001086 case Instruction::Add:
1087 // If there is a constant on the RHS, there are a variety of xformations
1088 // we can do.
1089 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1090 // If null, this should be simplified elsewhere. Some of the xforms here
1091 // won't work if the RHS is zero.
1092 if (RHS->isNullValue())
1093 break;
1094
1095 // Figure out what the input bits are. If the top bits of the and result
1096 // are not demanded, then the add doesn't demand them from its input
1097 // either.
1098
1099 // Shift the demanded mask up so that it's at the top of the uint64_t.
1100 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1101 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1102
1103 // If the top bit of the output is demanded, demand everything from the
1104 // input. Otherwise, we demand all the input bits except NLZ top bits.
1105 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1106
1107 // Find information about known zero/one bits in the input.
1108 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1109 KnownZero2, KnownOne2, Depth+1))
1110 return true;
1111
1112 // If the RHS of the add has bits set that can't affect the input, reduce
1113 // the constant.
1114 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1115 return UpdateValueUsesWith(I, I);
1116
1117 // Avoid excess work.
1118 if (KnownZero2 == 0 && KnownOne2 == 0)
1119 break;
1120
1121 // Turn it into OR if input bits are zero.
1122 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1123 Instruction *Or =
1124 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1125 I->getName());
1126 InsertNewInstBefore(Or, *I);
1127 return UpdateValueUsesWith(I, Or);
1128 }
1129
1130 // We can say something about the output known-zero and known-one bits,
1131 // depending on potential carries from the input constant and the
1132 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1133 // bits set and the RHS constant is 0x01001, then we know we have a known
1134 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1135
1136 // To compute this, we first compute the potential carry bits. These are
1137 // the bits which may be modified. I'm not aware of a better way to do
1138 // this scan.
1139 uint64_t RHSVal = RHS->getZExtValue();
1140
1141 bool CarryIn = false;
1142 uint64_t CarryBits = 0;
1143 uint64_t CurBit = 1;
1144 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1145 // Record the current carry in.
1146 if (CarryIn) CarryBits |= CurBit;
1147
1148 bool CarryOut;
1149
1150 // This bit has a carry out unless it is "zero + zero" or
1151 // "zero + anything" with no carry in.
1152 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1153 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1154 } else if (!CarryIn &&
1155 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1156 CarryOut = false; // 0 + anything has no carry out if no carry in.
1157 } else {
1158 // Otherwise, we have to assume we have a carry out.
1159 CarryOut = true;
1160 }
1161
1162 // This stage's carry out becomes the next stage's carry-in.
1163 CarryIn = CarryOut;
1164 }
1165
1166 // Now that we know which bits have carries, compute the known-1/0 sets.
1167
1168 // Bits are known one if they are known zero in one operand and one in the
1169 // other, and there is no input carry.
1170 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1171
1172 // Bits are known zero if they are known zero in both operands and there
1173 // is no input carry.
1174 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1175 }
1176 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001177 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 uint64_t ShiftAmt = SA->getZExtValue();
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001181 KnownZero, KnownOne, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001184 KnownZero <<= ShiftAmt;
1185 KnownOne <<= ShiftAmt;
1186 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001187 }
Chris Lattner2590e512006-02-07 06:56:34 +00001188 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001189 case Instruction::LShr:
1190 // For a logical shift right
1191 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1192 unsigned ShiftAmt = SA->getZExtValue();
1193
1194 // Compute the new bits that are at the top now.
1195 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1196 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1197 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1198 // Unsigned shift right.
1199 if (SimplifyDemandedBits(I->getOperand(0),
1200 (DemandedMask << ShiftAmt) & TypeMask,
1201 KnownZero, KnownOne, Depth+1))
1202 return true;
1203 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1204 KnownZero &= TypeMask;
1205 KnownOne &= TypeMask;
1206 KnownZero >>= ShiftAmt;
1207 KnownOne >>= ShiftAmt;
1208 KnownZero |= HighBits; // high bits known zero.
1209 }
1210 break;
1211 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001212 // If this is an arithmetic shift right and only the low-bit is set, we can
1213 // always convert this into a logical shr, even if the shift amount is
1214 // variable. The low bit of the shift cannot be an input sign bit unless
1215 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001216 if (DemandedMask == 1) {
1217 // Perform the logical shift right.
1218 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1219 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001220 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001221 return UpdateValueUsesWith(I, NewVal);
1222 }
1223
Reid Spencere0fc4df2006-10-20 07:07:24 +00001224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001226
1227 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001228 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1229 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001230 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001231 // Signed shift right.
1232 if (SimplifyDemandedBits(I->getOperand(0),
1233 (DemandedMask << ShiftAmt) & TypeMask,
1234 KnownZero, KnownOne, Depth+1))
1235 return true;
1236 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1237 KnownZero &= TypeMask;
1238 KnownOne &= TypeMask;
1239 KnownZero >>= ShiftAmt;
1240 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241
Reid Spencerfdff9382006-11-08 06:47:33 +00001242 // Handle the sign bits.
1243 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1244 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001245
Reid Spencerfdff9382006-11-08 06:47:33 +00001246 // If the input sign bit is known to be zero, or if none of the top bits
1247 // are demanded, turn this into an unsigned shift right.
1248 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1249 // Perform the logical shift right.
1250 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1251 SA, I->getName());
1252 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253 return UpdateValueUsesWith(I, NewVal);
1254 } else if (KnownOne & SignBit) { // New bits are known one.
1255 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001256 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001257 }
Chris Lattner2590e512006-02-07 06:56:34 +00001258 break;
1259 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001260
1261 // If the client is only demanding bits that we know, return the known
1262 // constant.
1263 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1264 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001265 return false;
1266}
1267
Chris Lattner2deeaea2006-10-05 06:55:50 +00001268
1269/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1270/// 64 or fewer elements. DemandedElts contains the set of elements that are
1271/// actually used by the caller. This method analyzes which elements of the
1272/// operand are undef and returns that information in UndefElts.
1273///
1274/// If the information about demanded elements can be used to simplify the
1275/// operation, the operation is simplified, then the resultant value is
1276/// returned. This returns null if no change was made.
1277Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1278 uint64_t &UndefElts,
1279 unsigned Depth) {
1280 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1281 assert(VWidth <= 64 && "Vector too wide to analyze!");
1282 uint64_t EltMask = ~0ULL >> (64-VWidth);
1283 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1284 "Invalid DemandedElts!");
1285
1286 if (isa<UndefValue>(V)) {
1287 // If the entire vector is undefined, just return this info.
1288 UndefElts = EltMask;
1289 return 0;
1290 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1291 UndefElts = EltMask;
1292 return UndefValue::get(V->getType());
1293 }
1294
1295 UndefElts = 0;
1296 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1297 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1298 Constant *Undef = UndefValue::get(EltTy);
1299
1300 std::vector<Constant*> Elts;
1301 for (unsigned i = 0; i != VWidth; ++i)
1302 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1303 Elts.push_back(Undef);
1304 UndefElts |= (1ULL << i);
1305 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1306 Elts.push_back(Undef);
1307 UndefElts |= (1ULL << i);
1308 } else { // Otherwise, defined.
1309 Elts.push_back(CP->getOperand(i));
1310 }
1311
1312 // If we changed the constant, return it.
1313 Constant *NewCP = ConstantPacked::get(Elts);
1314 return NewCP != CP ? NewCP : 0;
1315 } else if (isa<ConstantAggregateZero>(V)) {
1316 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1317 // set to undef.
1318 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1319 Constant *Zero = Constant::getNullValue(EltTy);
1320 Constant *Undef = UndefValue::get(EltTy);
1321 std::vector<Constant*> Elts;
1322 for (unsigned i = 0; i != VWidth; ++i)
1323 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1324 UndefElts = DemandedElts ^ EltMask;
1325 return ConstantPacked::get(Elts);
1326 }
1327
1328 if (!V->hasOneUse()) { // Other users may use these bits.
1329 if (Depth != 0) { // Not at the root.
1330 // TODO: Just compute the UndefElts information recursively.
1331 return false;
1332 }
1333 return false;
1334 } else if (Depth == 10) { // Limit search depth.
1335 return false;
1336 }
1337
1338 Instruction *I = dyn_cast<Instruction>(V);
1339 if (!I) return false; // Only analyze instructions.
1340
1341 bool MadeChange = false;
1342 uint64_t UndefElts2;
1343 Value *TmpV;
1344 switch (I->getOpcode()) {
1345 default: break;
1346
1347 case Instruction::InsertElement: {
1348 // If this is a variable index, we don't know which element it overwrites.
1349 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001350 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001351 if (Idx == 0) {
1352 // Note that we can't propagate undef elt info, because we don't know
1353 // which elt is getting updated.
1354 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1355 UndefElts2, Depth+1);
1356 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1357 break;
1358 }
1359
1360 // If this is inserting an element that isn't demanded, remove this
1361 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001362 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001363 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1364 return AddSoonDeadInstToWorklist(*I, 0);
1365
1366 // Otherwise, the element inserted overwrites whatever was there, so the
1367 // input demanded set is simpler than the output set.
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1369 DemandedElts & ~(1ULL << IdxNo),
1370 UndefElts, Depth+1);
1371 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372
1373 // The inserted element is defined.
1374 UndefElts |= 1ULL << IdxNo;
1375 break;
1376 }
1377
1378 case Instruction::And:
1379 case Instruction::Or:
1380 case Instruction::Xor:
1381 case Instruction::Add:
1382 case Instruction::Sub:
1383 case Instruction::Mul:
1384 // div/rem demand all inputs, because they don't want divide by zero.
1385 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1386 UndefElts, Depth+1);
1387 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1388 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1389 UndefElts2, Depth+1);
1390 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1391
1392 // Output elements are undefined if both are undefined. Consider things
1393 // like undef&0. The result is known zero, not undef.
1394 UndefElts &= UndefElts2;
1395 break;
1396
1397 case Instruction::Call: {
1398 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1399 if (!II) break;
1400 switch (II->getIntrinsicID()) {
1401 default: break;
1402
1403 // Binary vector operations that work column-wise. A dest element is a
1404 // function of the corresponding input elements from the two inputs.
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse_min_ss:
1408 case Intrinsic::x86_sse_max_ss:
1409 case Intrinsic::x86_sse2_sub_sd:
1410 case Intrinsic::x86_sse2_mul_sd:
1411 case Intrinsic::x86_sse2_min_sd:
1412 case Intrinsic::x86_sse2_max_sd:
1413 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1414 UndefElts, Depth+1);
1415 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1416 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1417 UndefElts2, Depth+1);
1418 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1419
1420 // If only the low elt is demanded and this is a scalarizable intrinsic,
1421 // scalarize it now.
1422 if (DemandedElts == 1) {
1423 switch (II->getIntrinsicID()) {
1424 default: break;
1425 case Intrinsic::x86_sse_sub_ss:
1426 case Intrinsic::x86_sse_mul_ss:
1427 case Intrinsic::x86_sse2_sub_sd:
1428 case Intrinsic::x86_sse2_mul_sd:
1429 // TODO: Lower MIN/MAX/ABS/etc
1430 Value *LHS = II->getOperand(1);
1431 Value *RHS = II->getOperand(2);
1432 // Extract the element as scalars.
1433 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1434 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1435
1436 switch (II->getIntrinsicID()) {
1437 default: assert(0 && "Case stmts out of sync!");
1438 case Intrinsic::x86_sse_sub_ss:
1439 case Intrinsic::x86_sse2_sub_sd:
1440 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1441 II->getName()), *II);
1442 break;
1443 case Intrinsic::x86_sse_mul_ss:
1444 case Intrinsic::x86_sse2_mul_sd:
1445 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1446 II->getName()), *II);
1447 break;
1448 }
1449
1450 Instruction *New =
1451 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1452 II->getName());
1453 InsertNewInstBefore(New, *II);
1454 AddSoonDeadInstToWorklist(*II, 0);
1455 return New;
1456 }
1457 }
1458
1459 // Output elements are undefined if both are undefined. Consider things
1460 // like undef&0. The result is known zero, not undef.
1461 UndefElts &= UndefElts2;
1462 break;
1463 }
1464 break;
1465 }
1466 }
1467 return MadeChange ? I : 0;
1468}
1469
Reid Spencer266e42b2006-12-23 06:05:41 +00001470/// @returns true if the specified compare instruction is
1471/// true when both operands are equal...
1472/// @brief Determine if the ICmpInst returns true if both operands are equal
1473static bool isTrueWhenEqual(ICmpInst &ICI) {
1474 ICmpInst::Predicate pred = ICI.getPredicate();
1475 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1476 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1477 pred == ICmpInst::ICMP_SLE;
1478}
1479
1480/// @returns true if the specified compare instruction is
1481/// true when both operands are equal...
1482/// @brief Determine if the FCmpInst returns true if both operands are equal
1483static bool isTrueWhenEqual(FCmpInst &FCI) {
1484 FCmpInst::Predicate pred = FCI.getPredicate();
1485 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1486 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1487 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001488}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001489
1490/// AssociativeOpt - Perform an optimization on an associative operator. This
1491/// function is designed to check a chain of associative operators for a
1492/// potential to apply a certain optimization. Since the optimization may be
1493/// applicable if the expression was reassociated, this checks the chain, then
1494/// reassociates the expression as necessary to expose the optimization
1495/// opportunity. This makes use of a special Functor, which must define
1496/// 'shouldApply' and 'apply' methods.
1497///
1498template<typename Functor>
1499Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1500 unsigned Opcode = Root.getOpcode();
1501 Value *LHS = Root.getOperand(0);
1502
1503 // Quick check, see if the immediate LHS matches...
1504 if (F.shouldApply(LHS))
1505 return F.apply(Root);
1506
1507 // Otherwise, if the LHS is not of the same opcode as the root, return.
1508 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001509 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001510 // Should we apply this transform to the RHS?
1511 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1512
1513 // If not to the RHS, check to see if we should apply to the LHS...
1514 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1515 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1516 ShouldApply = true;
1517 }
1518
1519 // If the functor wants to apply the optimization to the RHS of LHSI,
1520 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1521 if (ShouldApply) {
1522 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001523
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524 // Now all of the instructions are in the current basic block, go ahead
1525 // and perform the reassociation.
1526 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1527
1528 // First move the selected RHS to the LHS of the root...
1529 Root.setOperand(0, LHSI->getOperand(1));
1530
1531 // Make what used to be the LHS of the root be the user of the root...
1532 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001533 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001534 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1535 return 0;
1536 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001537 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001538 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001539 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1540 BasicBlock::iterator ARI = &Root; ++ARI;
1541 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1542 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001543
1544 // Now propagate the ExtraOperand down the chain of instructions until we
1545 // get to LHSI.
1546 while (TmpLHSI != LHSI) {
1547 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001548 // Move the instruction to immediately before the chain we are
1549 // constructing to avoid breaking dominance properties.
1550 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1551 BB->getInstList().insert(ARI, NextLHSI);
1552 ARI = NextLHSI;
1553
Chris Lattnerb8b97502003-08-13 19:01:45 +00001554 Value *NextOp = NextLHSI->getOperand(1);
1555 NextLHSI->setOperand(1, ExtraOperand);
1556 TmpLHSI = NextLHSI;
1557 ExtraOperand = NextOp;
1558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559
Chris Lattnerb8b97502003-08-13 19:01:45 +00001560 // Now that the instructions are reassociated, have the functor perform
1561 // the transformation...
1562 return F.apply(Root);
1563 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001564
Chris Lattnerb8b97502003-08-13 19:01:45 +00001565 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1566 }
1567 return 0;
1568}
1569
1570
1571// AddRHS - Implements: X + X --> X << 1
1572struct AddRHS {
1573 Value *RHS;
1574 AddRHS(Value *rhs) : RHS(rhs) {}
1575 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1576 Instruction *apply(BinaryOperator &Add) const {
1577 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1578 ConstantInt::get(Type::UByteTy, 1));
1579 }
1580};
1581
1582// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1583// iff C1&C2 == 0
1584struct AddMaskingAnd {
1585 Constant *C2;
1586 AddMaskingAnd(Constant *c) : C2(c) {}
1587 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001588 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001589 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001590 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001591 }
1592 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001593 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001594 }
1595};
1596
Chris Lattner86102b82005-01-01 16:22:27 +00001597static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001598 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001599 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001600 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001601 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001602
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001603 return IC->InsertNewInstBefore(CastInst::create(
1604 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001605 }
1606
Chris Lattner183b3362004-04-09 19:05:30 +00001607 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001608 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1609 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001610
Chris Lattner183b3362004-04-09 19:05:30 +00001611 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1612 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001613 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1614 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001615 }
1616
1617 Value *Op0 = SO, *Op1 = ConstOperand;
1618 if (!ConstIsRHS)
1619 std::swap(Op0, Op1);
1620 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001621 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1622 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001623 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1624 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1625 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001626 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1627 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001628 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001629 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001630 abort();
1631 }
Chris Lattner86102b82005-01-01 16:22:27 +00001632 return IC->InsertNewInstBefore(New, I);
1633}
1634
1635// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1636// constant as the other operand, try to fold the binary operator into the
1637// select arguments. This also works for Cast instructions, which obviously do
1638// not have a second operand.
1639static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1640 InstCombiner *IC) {
1641 // Don't modify shared select instructions
1642 if (!SI->hasOneUse()) return 0;
1643 Value *TV = SI->getOperand(1);
1644 Value *FV = SI->getOperand(2);
1645
1646 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001647 // Bool selects with constant operands can be folded to logical ops.
1648 if (SI->getType() == Type::BoolTy) return 0;
1649
Chris Lattner86102b82005-01-01 16:22:27 +00001650 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1651 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1652
1653 return new SelectInst(SI->getCondition(), SelectTrueVal,
1654 SelectFalseVal);
1655 }
1656 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001657}
1658
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001659
1660/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1661/// node as operand #0, see if we can fold the instruction into the PHI (which
1662/// is only possible if all operands to the PHI are constants).
1663Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1664 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001665 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001666 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001667
Chris Lattner04689872006-09-09 22:02:56 +00001668 // Check to see if all of the operands of the PHI are constants. If there is
1669 // one non-constant value, remember the BB it is. If there is more than one
1670 // bail out.
1671 BasicBlock *NonConstBB = 0;
1672 for (unsigned i = 0; i != NumPHIValues; ++i)
1673 if (!isa<Constant>(PN->getIncomingValue(i))) {
1674 if (NonConstBB) return 0; // More than one non-const value.
1675 NonConstBB = PN->getIncomingBlock(i);
1676
1677 // If the incoming non-constant value is in I's block, we have an infinite
1678 // loop.
1679 if (NonConstBB == I.getParent())
1680 return 0;
1681 }
1682
1683 // If there is exactly one non-constant value, we can insert a copy of the
1684 // operation in that block. However, if this is a critical edge, we would be
1685 // inserting the computation one some other paths (e.g. inside a loop). Only
1686 // do this if the pred block is unconditionally branching into the phi block.
1687 if (NonConstBB) {
1688 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1689 if (!BI || !BI->isUnconditional()) return 0;
1690 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001691
1692 // Okay, we can do the transformation: create the new PHI node.
1693 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1694 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001695 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001696 InsertNewInstBefore(NewPN, *PN);
1697
1698 // Next, add all of the operands to the PHI.
1699 if (I.getNumOperands() == 2) {
1700 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001701 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001702 Value *InV;
1703 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001704 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1705 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1706 else
1707 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001708 } else {
1709 assert(PN->getIncomingBlock(i) == NonConstBB);
1710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1711 InV = BinaryOperator::create(BO->getOpcode(),
1712 PN->getIncomingValue(i), C, "phitmp",
1713 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001714 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1715 InV = CmpInst::create(CI->getOpcode(),
1716 CI->getPredicate(),
1717 PN->getIncomingValue(i), C, "phitmp",
1718 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001719 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1720 InV = new ShiftInst(SI->getOpcode(),
1721 PN->getIncomingValue(i), C, "phitmp",
1722 NonConstBB->getTerminator());
1723 else
1724 assert(0 && "Unknown binop!");
1725
1726 WorkList.push_back(cast<Instruction>(InV));
1727 }
1728 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001729 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001730 } else {
1731 CastInst *CI = cast<CastInst>(&I);
1732 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001733 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001734 Value *InV;
1735 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001736 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001737 } else {
1738 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001739 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1740 I.getType(), "phitmp",
1741 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001742 WorkList.push_back(cast<Instruction>(InV));
1743 }
1744 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001745 }
1746 }
1747 return ReplaceInstUsesWith(I, NewPN);
1748}
1749
Chris Lattner113f4f42002-06-25 16:13:24 +00001750Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001751 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001752 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001753
Chris Lattnercf4a9962004-04-10 22:01:55 +00001754 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001755 // X + undef -> undef
1756 if (isa<UndefValue>(RHS))
1757 return ReplaceInstUsesWith(I, RHS);
1758
Chris Lattnercf4a9962004-04-10 22:01:55 +00001759 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001760 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001761 if (RHSC->isNullValue())
1762 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001763 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1764 if (CFP->isExactlyValue(-0.0))
1765 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001767
Chris Lattnercf4a9962004-04-10 22:01:55 +00001768 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001769 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001770 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001771 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001772 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001773
1774 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1775 // (X & 254)+1 -> (X&254)|1
1776 uint64_t KnownZero, KnownOne;
1777 if (!isa<PackedType>(I.getType()) &&
1778 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1779 KnownZero, KnownOne))
1780 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001781 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001782
1783 if (isa<PHINode>(LHS))
1784 if (Instruction *NV = FoldOpIntoPhi(I))
1785 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001786
Chris Lattner330628a2006-01-06 17:59:59 +00001787 ConstantInt *XorRHS = 0;
1788 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001789 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1790 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);
Chris Lattner4534dd592006-02-09 07:38:58 +00001813 Mask &= XorLHS->getType()->getIntegralTypeMask();
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;
1828 case 32: MiddleType = Type::IntTy; break;
1829 case 16: MiddleType = Type::ShortTy; break;
1830 case 8: MiddleType = Type::SByteTy; break;
1831 }
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
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001841 if (I.getType()->isInteger()) {
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 Lattner57c8d992003-02-18 19:57:07 +00001881
Chris Lattnerb8b97502003-08-13 19:01:45 +00001882 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001883 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001884 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001885
Chris Lattnerb9cde762003-10-02 15:11:26 +00001886 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001887 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001888 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1889 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1890 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001891 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001892
Chris Lattnerbff91d92004-10-08 05:07:56 +00001893 // (X & FF00) + xx00 -> (X+xx00) & FF00
1894 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1895 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1896 if (Anded == CRHS) {
1897 // See if all bits from the first bit set in the Add RHS up are included
1898 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001899 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001900
1901 // Form a mask of all bits from the lowest bit added through the top.
1902 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001903 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001904
1905 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001906 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001907
Chris Lattnerbff91d92004-10-08 05:07:56 +00001908 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1909 // Okay, the xform is safe. Insert the new add pronto.
1910 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1911 LHS->getName()), I);
1912 return BinaryOperator::createAnd(NewAdd, C2);
1913 }
1914 }
1915 }
1916
Chris Lattnerd4252a72004-07-30 07:50:03 +00001917 // Try to fold constant add into select arguments.
1918 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001919 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001920 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001921 }
1922
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001923 // add (cast *A to intptrtype) B ->
1924 // cast (GEP (cast *A to sbyte*) B) ->
1925 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001926 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001927 CastInst *CI = dyn_cast<CastInst>(LHS);
1928 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001929 if (!CI) {
1930 CI = dyn_cast<CastInst>(RHS);
1931 Other = LHS;
1932 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001933 if (CI && CI->getType()->isSized() &&
1934 (CI->getType()->getPrimitiveSize() ==
1935 TD->getIntPtrType()->getPrimitiveSize())
1936 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001937 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001938 PointerType::get(Type::SByteTy), I);
1939 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001940 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001941 }
1942 }
1943
Chris Lattner113f4f42002-06-25 16:13:24 +00001944 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001945}
1946
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001947// isSignBit - Return true if the value represented by the constant only has the
1948// highest order bit set.
1949static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001950 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001951 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001952}
1953
Chris Lattner022167f2004-03-13 00:11:49 +00001954/// RemoveNoopCast - Strip off nonconverting casts from the value.
1955///
1956static Value *RemoveNoopCast(Value *V) {
1957 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1958 const Type *CTy = CI->getType();
1959 const Type *OpTy = CI->getOperand(0)->getType();
1960 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001961 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001962 return RemoveNoopCast(CI->getOperand(0));
1963 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1964 return RemoveNoopCast(CI->getOperand(0));
1965 }
1966 return V;
1967}
1968
Chris Lattner113f4f42002-06-25 16:13:24 +00001969Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001971
Chris Lattnere6794492002-08-12 21:17:25 +00001972 if (Op0 == Op1) // sub X, X -> 0
1973 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001974
Chris Lattnere6794492002-08-12 21:17:25 +00001975 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001976 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001977 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001978
Chris Lattner81a7a232004-10-16 18:11:37 +00001979 if (isa<UndefValue>(Op0))
1980 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1981 if (isa<UndefValue>(Op1))
1982 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1983
Chris Lattner8f2f5982003-11-05 01:06:05 +00001984 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1985 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001986 if (C->isAllOnesValue())
1987 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001988
Chris Lattner8f2f5982003-11-05 01:06:05 +00001989 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001990 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001991 if (match(Op1, m_Not(m_Value(X))))
1992 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001993 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001994 // -((uint)X >> 31) -> ((int)X >> 31)
1995 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001996 if (C->isNullValue()) {
1997 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1998 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001999 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002000 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002001 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002002 if (CU->getZExtValue() ==
2003 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002004 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00002005 // FIXME: Once integer types are signless, this cast should be
2006 // removed.
2007 Value *ShiftOp = SI->getOperand(0);
2008 if (ShiftOp->getType() != I.getType())
2009 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
2010 I.getType(), I);
2011 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2012 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002013 }
2014 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002015 }
2016 else if (SI->getOpcode() == Instruction::AShr) {
2017 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2018 // Check to see if we are shifting out everything but the sign bit.
2019 if (CU->getZExtValue() ==
2020 SI->getType()->getPrimitiveSizeInBits()-1) {
2021 // Ok, the transformation is safe. Insert LShr.
2022 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
2023 CU, SI->getName());
2024 }
2025 }
2026 }
Chris Lattner022167f2004-03-13 00:11:49 +00002027 }
Chris Lattner183b3362004-04-09 19:05:30 +00002028
2029 // Try to fold constant sub into select arguments.
2030 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002031 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002032 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002033
2034 if (isa<PHINode>(Op0))
2035 if (Instruction *NV = FoldOpIntoPhi(I))
2036 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002037 }
2038
Chris Lattnera9be4492005-04-07 16:15:25 +00002039 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2040 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002041 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002042 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002043 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002044 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002045 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002046 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2047 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2048 // C1-(X+C2) --> (C1-C2)-X
2049 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2050 Op1I->getOperand(0));
2051 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002052 }
2053
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002054 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002055 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2056 // is not used by anyone else...
2057 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002058 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002059 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002060 // Swap the two operands of the subexpr...
2061 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2062 Op1I->setOperand(0, IIOp1);
2063 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002064
Chris Lattner3082c5a2003-02-18 19:28:33 +00002065 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002066 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002067 }
2068
2069 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2070 //
2071 if (Op1I->getOpcode() == Instruction::And &&
2072 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2073 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2074
Chris Lattner396dbfe2004-06-09 05:08:07 +00002075 Value *NewNot =
2076 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002077 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002078 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002079
Reid Spencer3c514952006-10-16 23:08:08 +00002080 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002081 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002082 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002083 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002084 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002085 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002086 ConstantExpr::getNeg(DivRHS));
2087
Chris Lattner57c8d992003-02-18 19:57:07 +00002088 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002089 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002090 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002091 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002092 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002093 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002094 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002095 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002096 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002097
Chris Lattner7a002fe2006-12-02 00:13:08 +00002098 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002099 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2100 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002101 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2102 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2103 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2104 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002105 } else if (Op0I->getOpcode() == Instruction::Sub) {
2106 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2107 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002108 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002109
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002110 ConstantInt *C1;
2111 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2112 if (X == Op1) { // X*C - X --> X * (C-1)
2113 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2114 return BinaryOperator::createMul(Op1, CP1);
2115 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002116
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002117 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2118 if (X == dyn_castFoldableMul(Op1, C2))
2119 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2120 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002121 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002122}
2123
Reid Spencer266e42b2006-12-23 06:05:41 +00002124/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002125/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002126static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2127 switch (pred) {
2128 case ICmpInst::ICMP_SLT:
2129 // True if LHS s< RHS and RHS == 0
2130 return RHS->isNullValue();
2131 case ICmpInst::ICMP_SLE:
2132 // True if LHS s<= RHS and RHS == -1
2133 return RHS->isAllOnesValue();
2134 case ICmpInst::ICMP_UGE:
2135 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2136 return RHS->getZExtValue() == (1ULL <<
2137 (RHS->getType()->getPrimitiveSizeInBits()-1));
2138 case ICmpInst::ICMP_UGT:
2139 // True if LHS u> RHS and RHS == high-bit-mask - 1
2140 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002141 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002142 default:
2143 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002144 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002145}
2146
Chris Lattner113f4f42002-06-25 16:13:24 +00002147Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002148 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002149 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002150
Chris Lattner81a7a232004-10-16 18:11:37 +00002151 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2153
Chris Lattnere6794492002-08-12 21:17:25 +00002154 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002155 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2156 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002157
2158 // ((X << C1)*C2) == (X * (C2 << C1))
2159 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2160 if (SI->getOpcode() == Instruction::Shl)
2161 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002162 return BinaryOperator::createMul(SI->getOperand(0),
2163 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002164
Chris Lattnercce81be2003-09-11 22:24:54 +00002165 if (CI->isNullValue())
2166 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2167 if (CI->equalsInt(1)) // X * 1 == X
2168 return ReplaceInstUsesWith(I, Op0);
2169 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002170 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002171
Reid Spencere0fc4df2006-10-20 07:07:24 +00002172 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002173 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2174 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002175 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002176 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002177 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002178 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002179 if (Op1F->isNullValue())
2180 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002181
Chris Lattner3082c5a2003-02-18 19:28:33 +00002182 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2183 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2184 if (Op1F->getValue() == 1.0)
2185 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2186 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002187
2188 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2189 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2190 isa<ConstantInt>(Op0I->getOperand(1))) {
2191 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2192 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2193 Op1, "tmp");
2194 InsertNewInstBefore(Add, I);
2195 Value *C1C2 = ConstantExpr::getMul(Op1,
2196 cast<Constant>(Op0I->getOperand(1)));
2197 return BinaryOperator::createAdd(Add, C1C2);
2198
2199 }
Chris Lattner183b3362004-04-09 19:05:30 +00002200
2201 // Try to fold constant mul into select arguments.
2202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002203 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002204 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002205
2206 if (isa<PHINode>(Op0))
2207 if (Instruction *NV = FoldOpIntoPhi(I))
2208 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002209 }
2210
Chris Lattner934a64cf2003-03-10 23:23:04 +00002211 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2212 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002213 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002214
Chris Lattner2635b522004-02-23 05:39:21 +00002215 // If one of the operands of the multiply is a cast from a boolean value, then
2216 // we know the bool is either zero or one, so this is a 'masking' multiply.
2217 // See if we can simplify things based on how the boolean was originally
2218 // formed.
2219 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002220 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2221 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002222 BoolCast = CI;
2223 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002224 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2225 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002226 BoolCast = CI;
2227 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002228 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002229 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2230 const Type *SCOpTy = SCIOp0->getType();
2231
Reid Spencer266e42b2006-12-23 06:05:41 +00002232 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002233 // multiply into a shift/and combination.
2234 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002235 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002236 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002237 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002238 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002239 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002240 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002241 BoolCast->getOperand(0)->getName()+
2242 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002243
2244 // If the multiply type is not the same as the source type, sign extend
2245 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002246 if (I.getType() != V->getType()) {
2247 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2248 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2249 Instruction::CastOps opcode =
2250 (SrcBits == DstBits ? Instruction::BitCast :
2251 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2252 V = InsertCastBefore(opcode, V, I.getType(), I);
2253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002254
Chris Lattner2635b522004-02-23 05:39:21 +00002255 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002256 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002257 }
2258 }
2259 }
2260
Chris Lattner113f4f42002-06-25 16:13:24 +00002261 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002262}
2263
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264/// This function implements the transforms on div instructions that work
2265/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2266/// used by the visitors to those instructions.
2267/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002268Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002270
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 // undef / X -> 0
2272 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002273 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002274
2275 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002276 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002277 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002278
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2281 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002282 // same basic block, then we replace the select with Y, and the condition
2283 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002284 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002285 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002286 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2287 if (ST->isNullValue()) {
2288 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2289 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002290 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002291 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2292 I.setOperand(1, SI->getOperand(2));
2293 else
2294 UpdateValueUsesWith(SI, SI->getOperand(2));
2295 return &I;
2296 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002297
Chris Lattnerd79dc792006-09-09 20:26:32 +00002298 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2299 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2300 if (ST->isNullValue()) {
2301 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2302 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002303 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002304 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2305 I.setOperand(1, SI->getOperand(1));
2306 else
2307 UpdateValueUsesWith(SI, SI->getOperand(1));
2308 return &I;
2309 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002310 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002311
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312 return 0;
2313}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002314
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002315/// This function implements the transforms common to both integer division
2316/// instructions (udiv and sdiv). It is called by the visitors to those integer
2317/// division instructions.
2318/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002319Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2321
2322 if (Instruction *Common = commonDivTransforms(I))
2323 return Common;
2324
2325 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2326 // div X, 1 == X
2327 if (RHS->equalsInt(1))
2328 return ReplaceInstUsesWith(I, Op0);
2329
2330 // (X / C1) / C2 -> X / (C1*C2)
2331 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2332 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2333 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2334 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2335 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002336 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002337
2338 if (!RHS->isNullValue()) { // avoid X udiv 0
2339 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2340 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2341 return R;
2342 if (isa<PHINode>(Op0))
2343 if (Instruction *NV = FoldOpIntoPhi(I))
2344 return NV;
2345 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002346 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002347
Chris Lattner3082c5a2003-02-18 19:28:33 +00002348 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002349 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002350 if (LHS->equalsInt(0))
2351 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2352
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002353 return 0;
2354}
2355
2356Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2357 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2358
2359 // Handle the integer div common cases
2360 if (Instruction *Common = commonIDivTransforms(I))
2361 return Common;
2362
2363 // X udiv C^2 -> X >> C
2364 // Check to see if this is an unsigned division with an exact power of 2,
2365 // if so, convert to a right shift.
2366 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2367 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2368 if (isPowerOf2_64(Val)) {
2369 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002370 return new ShiftInst(Instruction::LShr, Op0,
2371 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 }
2373 }
2374
2375 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2376 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2377 if (RHSI->getOpcode() == Instruction::Shl &&
2378 isa<ConstantInt>(RHSI->getOperand(0))) {
2379 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2380 if (isPowerOf2_64(C1)) {
2381 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002382 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002383 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002384 Constant *C2V = ConstantInt::get(NTy, C2);
2385 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002386 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002387 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002388 }
2389 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002390 }
2391
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002392 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2393 // where C1&C2 are powers of two.
2394 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2395 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2396 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2397 if (!STO->isNullValue() && !STO->isNullValue()) {
2398 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2399 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2400 // Compute the shift amounts
2401 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002402 // Construct the "on true" case of the select
2403 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2404 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002405 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406 TSI = InsertNewInstBefore(TSI, I);
2407
2408 // Construct the "on false" case of the select
2409 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2410 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002411 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002412 FSI = InsertNewInstBefore(FSI, I);
2413
2414 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002415 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416 }
2417 }
2418 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002419 return 0;
2420}
2421
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002422Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2424
2425 // Handle the integer div common cases
2426 if (Instruction *Common = commonIDivTransforms(I))
2427 return Common;
2428
2429 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2430 // sdiv X, -1 == -X
2431 if (RHS->isAllOnesValue())
2432 return BinaryOperator::createNeg(Op0);
2433
2434 // -X/C -> X/-C
2435 if (Value *LHSNeg = dyn_castNegVal(Op0))
2436 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2437 }
2438
2439 // If the sign bits of both operands are zero (i.e. we can prove they are
2440 // unsigned inputs), turn this into a udiv.
2441 if (I.getType()->isInteger()) {
2442 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2443 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2444 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2445 }
2446 }
2447
2448 return 0;
2449}
2450
2451Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2452 return commonDivTransforms(I);
2453}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002454
Chris Lattner85dda9a2006-03-02 06:50:58 +00002455/// GetFactor - If we can prove that the specified value is at least a multiple
2456/// of some factor, return that factor.
2457static Constant *GetFactor(Value *V) {
2458 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2459 return CI;
2460
2461 // Unless we can be tricky, we know this is a multiple of 1.
2462 Constant *Result = ConstantInt::get(V->getType(), 1);
2463
2464 Instruction *I = dyn_cast<Instruction>(V);
2465 if (!I) return Result;
2466
2467 if (I->getOpcode() == Instruction::Mul) {
2468 // Handle multiplies by a constant, etc.
2469 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2470 GetFactor(I->getOperand(1)));
2471 } else if (I->getOpcode() == Instruction::Shl) {
2472 // (X<<C) -> X * (1 << C)
2473 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2474 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2475 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2476 }
2477 } else if (I->getOpcode() == Instruction::And) {
2478 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2479 // X & 0xFFF0 is known to be a multiple of 16.
2480 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2481 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2482 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002483 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002484 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002485 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002486 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002487 if (!CI->isIntegerCast())
2488 return Result;
2489 Value *Op = CI->getOperand(0);
2490 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002491 }
2492 return Result;
2493}
2494
Reid Spencer7eb55b32006-11-02 01:53:59 +00002495/// This function implements the transforms on rem instructions that work
2496/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2497/// is used by the visitors to those instructions.
2498/// @brief Transforms common to all three rem instructions
2499Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002500 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002501
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002502 // 0 % X == 0, we don't need to preserve faults!
2503 if (Constant *LHS = dyn_cast<Constant>(Op0))
2504 if (LHS->isNullValue())
2505 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2506
2507 if (isa<UndefValue>(Op0)) // undef % X -> 0
2508 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2509 if (isa<UndefValue>(Op1))
2510 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002511
2512 // Handle cases involving: rem X, (select Cond, Y, Z)
2513 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2514 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2515 // the same basic block, then we replace the select with Y, and the
2516 // condition of the select with false (if the cond value is in the same
2517 // BB). If the select has uses other than the div, this allows them to be
2518 // simplified also.
2519 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2520 if (ST->isNullValue()) {
2521 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2522 if (CondI && CondI->getParent() == I.getParent())
2523 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2524 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2525 I.setOperand(1, SI->getOperand(2));
2526 else
2527 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002528 return &I;
2529 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002530 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2531 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2532 if (ST->isNullValue()) {
2533 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2534 if (CondI && CondI->getParent() == I.getParent())
2535 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2536 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2537 I.setOperand(1, SI->getOperand(1));
2538 else
2539 UpdateValueUsesWith(SI, SI->getOperand(1));
2540 return &I;
2541 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002542 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002543
Reid Spencer7eb55b32006-11-02 01:53:59 +00002544 return 0;
2545}
2546
2547/// This function implements the transforms common to both integer remainder
2548/// instructions (urem and srem). It is called by the visitors to those integer
2549/// remainder instructions.
2550/// @brief Common integer remainder transforms
2551Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2552 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2553
2554 if (Instruction *common = commonRemTransforms(I))
2555 return common;
2556
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002557 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002558 // X % 0 == undef, we don't need to preserve faults!
2559 if (RHS->equalsInt(0))
2560 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2561
Chris Lattner3082c5a2003-02-18 19:28:33 +00002562 if (RHS->equalsInt(1)) // X % 1 == 0
2563 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2564
Chris Lattnerb70f1412006-02-28 05:49:21 +00002565 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2566 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2567 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2568 return R;
2569 } else if (isa<PHINode>(Op0I)) {
2570 if (Instruction *NV = FoldOpIntoPhi(I))
2571 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002572 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002573 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2574 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002575 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002576 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002577 }
2578
Reid Spencer7eb55b32006-11-02 01:53:59 +00002579 return 0;
2580}
2581
2582Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2583 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2584
2585 if (Instruction *common = commonIRemTransforms(I))
2586 return common;
2587
2588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2589 // X urem C^2 -> X and C
2590 // Check to see if this is an unsigned remainder with an exact power of 2,
2591 // if so, convert to a bitwise and.
2592 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2593 if (isPowerOf2_64(C->getZExtValue()))
2594 return BinaryOperator::createAnd(Op0, SubOne(C));
2595 }
2596
Chris Lattner2e90b732006-02-05 07:54:04 +00002597 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002598 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2599 if (RHSI->getOpcode() == Instruction::Shl &&
2600 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002601 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002602 if (isPowerOf2_64(C1)) {
2603 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2604 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2605 "tmp"), I);
2606 return BinaryOperator::createAnd(Op0, Add);
2607 }
2608 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002609 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002610
Reid Spencer7eb55b32006-11-02 01:53:59 +00002611 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2612 // where C1&C2 are powers of two.
2613 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2614 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2615 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2616 // STO == 0 and SFO == 0 handled above.
2617 if (isPowerOf2_64(STO->getZExtValue()) &&
2618 isPowerOf2_64(SFO->getZExtValue())) {
2619 Value *TrueAnd = InsertNewInstBefore(
2620 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2621 Value *FalseAnd = InsertNewInstBefore(
2622 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2623 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2624 }
2625 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002626 }
2627
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002628 return 0;
2629}
2630
Reid Spencer7eb55b32006-11-02 01:53:59 +00002631Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2632 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2633
2634 if (Instruction *common = commonIRemTransforms(I))
2635 return common;
2636
2637 if (Value *RHSNeg = dyn_castNegVal(Op1))
2638 if (!isa<ConstantInt>(RHSNeg) ||
2639 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2640 // X % -Y -> X % Y
2641 AddUsesToWorkList(I);
2642 I.setOperand(1, RHSNeg);
2643 return &I;
2644 }
2645
2646 // If the top bits of both operands are zero (i.e. we can prove they are
2647 // unsigned inputs), turn this into a urem.
2648 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2649 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2650 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2651 return BinaryOperator::createURem(Op0, Op1, I.getName());
2652 }
2653
2654 return 0;
2655}
2656
2657Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002658 return commonRemTransforms(I);
2659}
2660
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002661// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002662static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2663 if (isSigned) {
2664 // Calculate 0111111111..11111
2665 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2666 int64_t Val = INT64_MAX; // All ones
2667 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2668 return C->getSExtValue() == Val-1;
2669 }
2670 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002671}
2672
2673// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002674static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2675 if (isSigned) {
2676 // Calculate 1111111111000000000000
2677 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2678 int64_t Val = -1; // All ones
2679 Val <<= TypeBits-1; // Shift over to the right spot
2680 return C->getSExtValue() == Val+1;
2681 }
2682 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002683}
2684
Chris Lattner35167c32004-06-09 07:59:58 +00002685// isOneBitSet - Return true if there is exactly one bit set in the specified
2686// constant.
2687static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002688 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002689 return V && (V & (V-1)) == 0;
2690}
2691
Chris Lattner8fc5af42004-09-23 21:46:38 +00002692#if 0 // Currently unused
2693// isLowOnes - Return true if the constant is of the form 0+1+.
2694static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002695 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002696
2697 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002698 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002699
2700 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2701 return U && V && (U & V) == 0;
2702}
2703#endif
2704
2705// isHighOnes - Return true if the constant is of the form 1+0+.
2706// This is the same as lowones(~X).
2707static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002708 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002709 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002710
2711 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002712 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002713
2714 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2715 return U && V && (U & V) == 0;
2716}
2717
Reid Spencer266e42b2006-12-23 06:05:41 +00002718/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002719/// are carefully arranged to allow folding of expressions such as:
2720///
2721/// (A < B) | (A > B) --> (A != B)
2722///
Reid Spencer266e42b2006-12-23 06:05:41 +00002723/// Note that this is only valid if the first and second predicates have the
2724/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002725///
Reid Spencer266e42b2006-12-23 06:05:41 +00002726/// Three bits are used to represent the condition, as follows:
2727/// 0 A > B
2728/// 1 A == B
2729/// 2 A < B
2730///
2731/// <=> Value Definition
2732/// 000 0 Always false
2733/// 001 1 A > B
2734/// 010 2 A == B
2735/// 011 3 A >= B
2736/// 100 4 A < B
2737/// 101 5 A != B
2738/// 110 6 A <= B
2739/// 111 7 Always true
2740///
2741static unsigned getICmpCode(const ICmpInst *ICI) {
2742 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002743 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002744 case ICmpInst::ICMP_UGT: return 1; // 001
2745 case ICmpInst::ICMP_SGT: return 1; // 001
2746 case ICmpInst::ICMP_EQ: return 2; // 010
2747 case ICmpInst::ICMP_UGE: return 3; // 011
2748 case ICmpInst::ICMP_SGE: return 3; // 011
2749 case ICmpInst::ICMP_ULT: return 4; // 100
2750 case ICmpInst::ICMP_SLT: return 4; // 100
2751 case ICmpInst::ICMP_NE: return 5; // 101
2752 case ICmpInst::ICMP_ULE: return 6; // 110
2753 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002754 // True -> 7
2755 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002756 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002757 return 0;
2758 }
2759}
2760
Reid Spencer266e42b2006-12-23 06:05:41 +00002761/// getICmpValue - This is the complement of getICmpCode, which turns an
2762/// opcode and two operands into either a constant true or false, or a brand
2763/// new /// ICmp instruction. The sign is passed in to determine which kind
2764/// of predicate to use in new icmp instructions.
2765static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2766 switch (code) {
2767 default: assert(0 && "Illegal ICmp code!");
2768 case 0: return ConstantBool::getFalse();
2769 case 1:
2770 if (sign)
2771 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2772 else
2773 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2774 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2775 case 3:
2776 if (sign)
2777 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2778 else
2779 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2780 case 4:
2781 if (sign)
2782 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2783 else
2784 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2785 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2786 case 6:
2787 if (sign)
2788 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2789 else
2790 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2791 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002792 }
2793}
2794
Reid Spencer266e42b2006-12-23 06:05:41 +00002795static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2796 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2797 (ICmpInst::isSignedPredicate(p1) &&
2798 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2799 (ICmpInst::isSignedPredicate(p2) &&
2800 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2801}
2802
2803namespace {
2804// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2805struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002806 InstCombiner &IC;
2807 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002808 ICmpInst::Predicate pred;
2809 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2810 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2811 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002812 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002813 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2814 if (PredicatesFoldable(pred, ICI->getPredicate()))
2815 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2816 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002817 return false;
2818 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002819 Instruction *apply(Instruction &Log) const {
2820 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2821 if (ICI->getOperand(0) != LHS) {
2822 assert(ICI->getOperand(1) == LHS);
2823 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002824 }
2825
Reid Spencer266e42b2006-12-23 06:05:41 +00002826 unsigned LHSCode = getICmpCode(ICI);
2827 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002828 unsigned Code;
2829 switch (Log.getOpcode()) {
2830 case Instruction::And: Code = LHSCode & RHSCode; break;
2831 case Instruction::Or: Code = LHSCode | RHSCode; break;
2832 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002833 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002834 }
2835
Reid Spencer266e42b2006-12-23 06:05:41 +00002836 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002837 if (Instruction *I = dyn_cast<Instruction>(RV))
2838 return I;
2839 // Otherwise, it's a constant boolean value...
2840 return IC.ReplaceInstUsesWith(Log, RV);
2841 }
2842};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002843} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002844
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2846// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2847// guaranteed to be either a shift instruction or a binary operator.
2848Instruction *InstCombiner::OptAndOp(Instruction *Op,
2849 ConstantIntegral *OpRHS,
2850 ConstantIntegral *AndRHS,
2851 BinaryOperator &TheAnd) {
2852 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002853 Constant *Together = 0;
2854 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002855 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002856
Chris Lattnerba1cb382003-09-19 17:17:26 +00002857 switch (Op->getOpcode()) {
2858 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002859 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002860 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2861 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002862 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002863 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002864 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002865 }
2866 break;
2867 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002868 if (Together == AndRHS) // (X | C) & C --> C
2869 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002870
Chris Lattner86102b82005-01-01 16:22:27 +00002871 if (Op->hasOneUse() && Together != OpRHS) {
2872 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2873 std::string Op0Name = Op->getName(); Op->setName("");
2874 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2875 InsertNewInstBefore(Or, TheAnd);
2876 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002877 }
2878 break;
2879 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002880 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002881 // Adding a one to a single bit bit-field should be turned into an XOR
2882 // of the bit. First thing to check is to see if this AND is with a
2883 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002884 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002885
2886 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002887 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002888
2889 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002890 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002891 // Ok, at this point, we know that we are masking the result of the
2892 // ADD down to exactly one bit. If the constant we are adding has
2893 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002894 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002895
Chris Lattnerba1cb382003-09-19 17:17:26 +00002896 // Check to see if any bits below the one bit set in AndRHSV are set.
2897 if ((AddRHS & (AndRHSV-1)) == 0) {
2898 // If not, the only thing that can effect the output of the AND is
2899 // the bit specified by AndRHSV. If that bit is set, the effect of
2900 // the XOR is to toggle the bit. If it is clear, then the ADD has
2901 // no effect.
2902 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2903 TheAnd.setOperand(0, X);
2904 return &TheAnd;
2905 } else {
2906 std::string Name = Op->getName(); Op->setName("");
2907 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002908 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002909 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002910 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002911 }
2912 }
2913 }
2914 }
2915 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002916
2917 case Instruction::Shl: {
2918 // We know that the AND will not produce any of the bits shifted in, so if
2919 // the anded constant includes them, clear them now!
2920 //
2921 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002922 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2923 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002924
Chris Lattner7e794272004-09-24 15:21:34 +00002925 if (CI == ShlMask) { // Masking out bits that the shift already masks
2926 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2927 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002928 TheAnd.setOperand(1, CI);
2929 return &TheAnd;
2930 }
2931 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002932 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002933 case Instruction::LShr:
2934 {
Chris Lattner2da29172003-09-19 19:05:02 +00002935 // We know that the AND will not produce any of the bits shifted in, so if
2936 // the anded constant includes them, clear them now! This only applies to
2937 // unsigned shifts, because a signed shr may bring in set bits!
2938 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002939 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2940 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2941 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002942
Reid Spencerfdff9382006-11-08 06:47:33 +00002943 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2944 return ReplaceInstUsesWith(TheAnd, Op);
2945 } else if (CI != AndRHS) {
2946 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2947 return &TheAnd;
2948 }
2949 break;
2950 }
2951 case Instruction::AShr:
2952 // Signed shr.
2953 // See if this is shifting in some sign extension, then masking it out
2954 // with an and.
2955 if (Op->hasOneUse()) {
2956 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2957 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002958 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2959 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002960 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002961 // Make the argument unsigned.
2962 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002963 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2964 OpRHS, Op->getName()), TheAnd);
2965 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002966 }
Chris Lattner2da29172003-09-19 19:05:02 +00002967 }
2968 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002969 }
2970 return 0;
2971}
2972
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002973
Chris Lattner6862fbd2004-09-29 17:40:11 +00002974/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2975/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002976/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2977/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002978/// insert new instructions.
2979Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002980 bool isSigned, bool Inside,
2981 Instruction &IB) {
2982 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2983 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002984 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002985
Chris Lattner6862fbd2004-09-29 17:40:11 +00002986 if (Inside) {
2987 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002988 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002989
Reid Spencer266e42b2006-12-23 06:05:41 +00002990 // V >= Min && V < Hi --> V < Hi
2991 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2992 ICmpInst::Predicate pred = (isSigned ?
2993 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2994 return new ICmpInst(pred, V, Hi);
2995 }
2996
2997 // Emit V-Lo <u Hi-Lo
2998 Constant *NegLo = ConstantExpr::getNeg(Lo);
2999 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003000 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003001 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3002 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003003 }
3004
3005 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003006 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003007
Reid Spencer266e42b2006-12-23 06:05:41 +00003008 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003009 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencer266e42b2006-12-23 06:05:41 +00003010 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3011 ICmpInst::Predicate pred = (isSigned ?
3012 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3013 return new ICmpInst(pred, V, Hi);
3014 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003015
Reid Spencer266e42b2006-12-23 06:05:41 +00003016 // Emit V-Lo > Hi-1-Lo
3017 Constant *NegLo = ConstantExpr::getNeg(Lo);
3018 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003019 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003020 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3021 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003022}
3023
Chris Lattnerb4b25302005-09-18 07:22:02 +00003024// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3025// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3026// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3027// not, since all 1s are not contiguous.
3028static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003029 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003030 if (!isShiftedMask_64(V)) return false;
3031
3032 // look for the first zero bit after the run of ones
3033 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3034 // look for the first non-zero bit
3035 ME = 64-CountLeadingZeros_64(V);
3036 return true;
3037}
3038
3039
3040
3041/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3042/// where isSub determines whether the operator is a sub. If we can fold one of
3043/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003044///
3045/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3046/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3047/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3048///
3049/// return (A +/- B).
3050///
3051Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3052 ConstantIntegral *Mask, bool isSub,
3053 Instruction &I) {
3054 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3055 if (!LHSI || LHSI->getNumOperands() != 2 ||
3056 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3057
3058 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3059
3060 switch (LHSI->getOpcode()) {
3061 default: return 0;
3062 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003063 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3064 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003065 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003066 break;
3067
3068 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3069 // part, we don't need any explicit masks to take them out of A. If that
3070 // is all N is, ignore it.
3071 unsigned MB, ME;
3072 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003073 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3074 Mask >>= 64-MB+1;
3075 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003076 break;
3077 }
3078 }
Chris Lattneraf517572005-09-18 04:24:45 +00003079 return 0;
3080 case Instruction::Or:
3081 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003082 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003083 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003084 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003085 break;
3086 return 0;
3087 }
3088
3089 Instruction *New;
3090 if (isSub)
3091 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3092 else
3093 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3094 return InsertNewInstBefore(New, I);
3095}
3096
Chris Lattner113f4f42002-06-25 16:13:24 +00003097Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003098 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003100
Chris Lattner81a7a232004-10-16 18:11:37 +00003101 if (isa<UndefValue>(Op1)) // X & undef -> 0
3102 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3103
Chris Lattner86102b82005-01-01 16:22:27 +00003104 // and X, X = X
3105 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003106 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003107
Chris Lattner5b2edb12006-02-12 08:02:11 +00003108 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003109 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003110 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003111 if (!isa<PackedType>(I.getType()) &&
3112 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003113 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003114 return &I;
3115
Chris Lattner86102b82005-01-01 16:22:27 +00003116 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003117 uint64_t AndRHSMask = AndRHS->getZExtValue();
3118 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003119 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003120
Chris Lattnerba1cb382003-09-19 17:17:26 +00003121 // Optimize a variety of ((val OP C1) & C2) combinations...
3122 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3123 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003124 Value *Op0LHS = Op0I->getOperand(0);
3125 Value *Op0RHS = Op0I->getOperand(1);
3126 switch (Op0I->getOpcode()) {
3127 case Instruction::Xor:
3128 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003129 // If the mask is only needed on one incoming arm, push it up.
3130 if (Op0I->hasOneUse()) {
3131 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3132 // Not masking anything out for the LHS, move to RHS.
3133 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3134 Op0RHS->getName()+".masked");
3135 InsertNewInstBefore(NewRHS, I);
3136 return BinaryOperator::create(
3137 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003138 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003139 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003140 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3141 // Not masking anything out for the RHS, move to LHS.
3142 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3143 Op0LHS->getName()+".masked");
3144 InsertNewInstBefore(NewLHS, I);
3145 return BinaryOperator::create(
3146 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3147 }
3148 }
3149
Chris Lattner86102b82005-01-01 16:22:27 +00003150 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003151 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003152 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3153 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3154 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3155 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3156 return BinaryOperator::createAnd(V, AndRHS);
3157 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3158 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003159 break;
3160
3161 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003162 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3163 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3164 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3165 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3166 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003167 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003168 }
3169
Chris Lattner16464b32003-07-23 19:25:52 +00003170 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003171 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003172 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003173 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003174 // If this is an integer truncation or change from signed-to-unsigned, and
3175 // if the source is an and/or with immediate, transform it. This
3176 // frequently occurs for bitfield accesses.
3177 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003178 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003179 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003180 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003181 if (CastOp->getOpcode() == Instruction::And) {
3182 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003183 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3184 // This will fold the two constants together, which may allow
3185 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003186 Instruction *NewCast = CastInst::createTruncOrBitCast(
3187 CastOp->getOperand(0), I.getType(),
3188 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003189 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003190 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003191 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003192 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003193 return BinaryOperator::createAnd(NewCast, C3);
3194 } else if (CastOp->getOpcode() == Instruction::Or) {
3195 // Change: and (cast (or X, C1) to T), C2
3196 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003197 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003198 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3199 return ReplaceInstUsesWith(I, AndRHS);
3200 }
3201 }
Chris Lattner33217db2003-07-23 19:36:21 +00003202 }
Chris Lattner183b3362004-04-09 19:05:30 +00003203
3204 // Try to fold constant and into select arguments.
3205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003206 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003207 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003208 if (isa<PHINode>(Op0))
3209 if (Instruction *NV = FoldOpIntoPhi(I))
3210 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003211 }
3212
Chris Lattnerbb74e222003-03-10 23:06:50 +00003213 Value *Op0NotVal = dyn_castNotVal(Op0);
3214 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003215
Chris Lattner023a4832004-06-18 06:07:51 +00003216 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3217 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3218
Misha Brukman9c003d82004-07-30 12:50:08 +00003219 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003220 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003221 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3222 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003223 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003224 return BinaryOperator::createNot(Or);
3225 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003226
3227 {
3228 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003229 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3230 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3231 return ReplaceInstUsesWith(I, Op1);
3232 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3233 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3234 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003235
3236 if (Op0->hasOneUse() &&
3237 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3238 if (A == Op1) { // (A^B)&A -> A&(A^B)
3239 I.swapOperands(); // Simplify below
3240 std::swap(Op0, Op1);
3241 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3242 cast<BinaryOperator>(Op0)->swapOperands();
3243 I.swapOperands(); // Simplify below
3244 std::swap(Op0, Op1);
3245 }
3246 }
3247 if (Op1->hasOneUse() &&
3248 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3249 if (B == Op0) { // B&(A^B) -> B&(B^A)
3250 cast<BinaryOperator>(Op1)->swapOperands();
3251 std::swap(A, B);
3252 }
3253 if (A == Op0) { // A&(A^B) -> A & ~B
3254 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3255 InsertNewInstBefore(NotB, I);
3256 return BinaryOperator::createAnd(A, NotB);
3257 }
3258 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003259 }
3260
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3262 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3263 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003264 return R;
3265
Chris Lattner623826c2004-09-28 21:48:02 +00003266 Value *LHSVal, *RHSVal;
3267 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003268 ICmpInst::Predicate LHSCC, RHSCC;
3269 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3270 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3271 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3272 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3273 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3274 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3275 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3276 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003277 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003278 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3279 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3280 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3281 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner623826c2004-09-28 21:48:02 +00003282 if (cast<ConstantBool>(Cmp)->getValue()) {
3283 std::swap(LHS, RHS);
3284 std::swap(LHSCst, RHSCst);
3285 std::swap(LHSCC, RHSCC);
3286 }
3287
Reid Spencer266e42b2006-12-23 06:05:41 +00003288 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003289 // comparing a value against two constants and and'ing the result
3290 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003291 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3292 // (from the FoldICmpLogical check above), that the two constants
3293 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003294 assert(LHSCst != RHSCst && "Compares not folded above?");
3295
3296 switch (LHSCC) {
3297 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003298 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003299 switch (RHSCC) {
3300 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003301 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3302 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3303 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003304 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003305 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3306 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3307 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003308 return ReplaceInstUsesWith(I, LHS);
3309 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003311 switch (RHSCC) {
3312 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003313 case ICmpInst::ICMP_ULT:
3314 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3315 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3316 break; // (X != 13 & X u< 15) -> no change
3317 case ICmpInst::ICMP_SLT:
3318 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3319 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3320 break; // (X != 13 & X s< 15) -> no change
3321 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3322 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3323 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003324 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003325 case ICmpInst::ICMP_NE:
3326 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003327 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3328 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3329 LHSVal->getName()+".off");
3330 InsertNewInstBefore(Add, I);
3331 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003332 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3333 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003334 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003335 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Reid Spencer266e42b2006-12-23 06:05:41 +00003336 return new ICmpInst(ICmpInst::ICMP_UGT, OffsetVal, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003337 }
3338 break; // (X != 13 & X != 15) -> no change
3339 }
3340 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003341 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003342 switch (RHSCC) {
3343 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003344 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3345 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003346 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3348 break;
3349 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3350 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003351 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003352 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3353 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003354 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 break;
3356 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003357 switch (RHSCC) {
3358 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003359 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3360 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3361 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3362 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3363 break;
3364 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3365 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003366 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003367 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3368 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003369 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003370 break;
3371 case ICmpInst::ICMP_UGT:
3372 switch (RHSCC) {
3373 default: assert(0 && "Unknown integer condition code!");
3374 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3375 return ReplaceInstUsesWith(I, LHS);
3376 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3377 return ReplaceInstUsesWith(I, RHS);
3378 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3379 break;
3380 case ICmpInst::ICMP_NE:
3381 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3382 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3383 break; // (X u> 13 & X != 15) -> no change
3384 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3385 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3386 true, I);
3387 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3388 break;
3389 }
3390 break;
3391 case ICmpInst::ICMP_SGT:
3392 switch (RHSCC) {
3393 default: assert(0 && "Unknown integer condition code!");
3394 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3395 return ReplaceInstUsesWith(I, LHS);
3396 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3397 return ReplaceInstUsesWith(I, RHS);
3398 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3399 break;
3400 case ICmpInst::ICMP_NE:
3401 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3402 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3403 break; // (X s> 13 & X != 15) -> no change
3404 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3405 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3406 true, I);
3407 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3408 break;
3409 }
3410 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003411 }
3412 }
3413 }
3414
Chris Lattner3af10532006-05-05 06:39:07 +00003415 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003416 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3417 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3418 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3419 const Type *SrcTy = Op0C->getOperand(0)->getType();
3420 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3421 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003422 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3423 I.getType(), TD) &&
3424 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3425 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003426 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3427 Op1C->getOperand(0),
3428 I.getName());
3429 InsertNewInstBefore(NewOp, I);
3430 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3431 }
Chris Lattner3af10532006-05-05 06:39:07 +00003432 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003433
3434 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3435 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3436 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3437 if (SI0->getOpcode() == SI1->getOpcode() &&
3438 SI0->getOperand(1) == SI1->getOperand(1) &&
3439 (SI0->hasOneUse() || SI1->hasOneUse())) {
3440 Instruction *NewOp =
3441 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3442 SI1->getOperand(0),
3443 SI0->getName()), I);
3444 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3445 }
Chris Lattner3af10532006-05-05 06:39:07 +00003446 }
3447
Chris Lattner113f4f42002-06-25 16:13:24 +00003448 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003449}
3450
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003451/// CollectBSwapParts - Look to see if the specified value defines a single byte
3452/// in the result. If it does, and if the specified byte hasn't been filled in
3453/// yet, fill it in and return false.
3454static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3455 Instruction *I = dyn_cast<Instruction>(V);
3456 if (I == 0) return true;
3457
3458 // If this is an or instruction, it is an inner node of the bswap.
3459 if (I->getOpcode() == Instruction::Or)
3460 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3461 CollectBSwapParts(I->getOperand(1), ByteValues);
3462
3463 // If this is a shift by a constant int, and it is "24", then its operand
3464 // defines a byte. We only handle unsigned types here.
3465 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3466 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003467 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003468 8*(ByteValues.size()-1))
3469 return true;
3470
3471 unsigned DestNo;
3472 if (I->getOpcode() == Instruction::Shl) {
3473 // X << 24 defines the top byte with the lowest of the input bytes.
3474 DestNo = ByteValues.size()-1;
3475 } else {
3476 // X >>u 24 defines the low byte with the highest of the input bytes.
3477 DestNo = 0;
3478 }
3479
3480 // If the destination byte value is already defined, the values are or'd
3481 // together, which isn't a bswap (unless it's an or of the same bits).
3482 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3483 return true;
3484 ByteValues[DestNo] = I->getOperand(0);
3485 return false;
3486 }
3487
3488 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3489 // don't have this.
3490 Value *Shift = 0, *ShiftLHS = 0;
3491 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3492 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3493 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3494 return true;
3495 Instruction *SI = cast<Instruction>(Shift);
3496
3497 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003498 if (ShiftAmt->getZExtValue() & 7 ||
3499 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003500 return true;
3501
3502 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3503 unsigned DestByte;
3504 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003505 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003506 break;
3507 // Unknown mask for bswap.
3508 if (DestByte == ByteValues.size()) return true;
3509
Reid Spencere0fc4df2006-10-20 07:07:24 +00003510 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003511 unsigned SrcByte;
3512 if (SI->getOpcode() == Instruction::Shl)
3513 SrcByte = DestByte - ShiftBytes;
3514 else
3515 SrcByte = DestByte + ShiftBytes;
3516
3517 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3518 if (SrcByte != ByteValues.size()-DestByte-1)
3519 return true;
3520
3521 // If the destination byte value is already defined, the values are or'd
3522 // together, which isn't a bswap (unless it's an or of the same bits).
3523 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3524 return true;
3525 ByteValues[DestByte] = SI->getOperand(0);
3526 return false;
3527}
3528
3529/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3530/// If so, insert the new bswap intrinsic and return it.
3531Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3532 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3533 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3534 return 0;
3535
3536 /// ByteValues - For each byte of the result, we keep track of which value
3537 /// defines each byte.
3538 std::vector<Value*> ByteValues;
3539 ByteValues.resize(I.getType()->getPrimitiveSize());
3540
3541 // Try to find all the pieces corresponding to the bswap.
3542 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3543 CollectBSwapParts(I.getOperand(1), ByteValues))
3544 return 0;
3545
3546 // Check to see if all of the bytes come from the same value.
3547 Value *V = ByteValues[0];
3548 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3549
3550 // Check to make sure that all of the bytes come from the same value.
3551 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3552 if (ByteValues[i] != V)
3553 return 0;
3554
3555 // If they do then *success* we can turn this into a bswap. Figure out what
3556 // bswap to make it into.
3557 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003558 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003559 if (I.getType() == Type::UShortTy)
3560 FnName = "llvm.bswap.i16";
3561 else if (I.getType() == Type::UIntTy)
3562 FnName = "llvm.bswap.i32";
3563 else if (I.getType() == Type::ULongTy)
3564 FnName = "llvm.bswap.i64";
3565 else
3566 assert(0 && "Unknown integer type!");
3567 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3568
3569 return new CallInst(F, V);
3570}
3571
3572
Chris Lattner113f4f42002-06-25 16:13:24 +00003573Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003574 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003575 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003576
Chris Lattner81a7a232004-10-16 18:11:37 +00003577 if (isa<UndefValue>(Op1))
3578 return ReplaceInstUsesWith(I, // X | undef -> -1
3579 ConstantIntegral::getAllOnesValue(I.getType()));
3580
Chris Lattner5b2edb12006-02-12 08:02:11 +00003581 // or X, X = X
3582 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003583 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003584
Chris Lattner5b2edb12006-02-12 08:02:11 +00003585 // See if we can simplify any instructions used by the instruction whose sole
3586 // purpose is to compute bits we don't care about.
3587 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003588 if (!isa<PackedType>(I.getType()) &&
3589 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003590 KnownZero, KnownOne))
3591 return &I;
3592
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003593 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003594 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003595 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003596 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3597 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003598 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3599 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003600 InsertNewInstBefore(Or, I);
3601 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3602 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003603
Chris Lattnerd4252a72004-07-30 07:50:03 +00003604 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3605 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3606 std::string Op0Name = Op0->getName(); Op0->setName("");
3607 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3608 InsertNewInstBefore(Or, I);
3609 return BinaryOperator::createXor(Or,
3610 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003611 }
Chris Lattner183b3362004-04-09 19:05:30 +00003612
3613 // Try to fold constant and into select arguments.
3614 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003615 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003616 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003617 if (isa<PHINode>(Op0))
3618 if (Instruction *NV = FoldOpIntoPhi(I))
3619 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003620 }
3621
Chris Lattner330628a2006-01-06 17:59:59 +00003622 Value *A = 0, *B = 0;
3623 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003624
3625 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3626 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3627 return ReplaceInstUsesWith(I, Op1);
3628 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3629 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3630 return ReplaceInstUsesWith(I, Op0);
3631
Chris Lattnerb7845d62006-07-10 20:25:24 +00003632 // (A | B) | C and A | (B | C) -> bswap if possible.
3633 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003634 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003635 match(Op1, m_Or(m_Value(), m_Value())) ||
3636 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3637 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003638 if (Instruction *BSwap = MatchBSwap(I))
3639 return BSwap;
3640 }
3641
Chris Lattnerb62f5082005-05-09 04:58:36 +00003642 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3643 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003644 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003645 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3646 Op0->setName("");
3647 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3648 }
3649
3650 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3651 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003652 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003653 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3654 Op0->setName("");
3655 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3656 }
3657
Chris Lattner15212982005-09-18 03:42:07 +00003658 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003659 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003660 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3661
3662 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3663 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3664
3665
Chris Lattner01f56c62005-09-18 06:02:59 +00003666 // If we have: ((V + N) & C1) | (V & C2)
3667 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3668 // replace with V+N.
3669 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003670 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003671 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003672 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3673 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003674 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003675 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003676 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003677 return ReplaceInstUsesWith(I, A);
3678 }
3679 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003680 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003681 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3682 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003683 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003684 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003685 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003686 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003687 }
3688 }
3689 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003690
3691 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3692 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3693 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3694 if (SI0->getOpcode() == SI1->getOpcode() &&
3695 SI0->getOperand(1) == SI1->getOperand(1) &&
3696 (SI0->hasOneUse() || SI1->hasOneUse())) {
3697 Instruction *NewOp =
3698 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3699 SI1->getOperand(0),
3700 SI0->getName()), I);
3701 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3702 }
3703 }
Chris Lattner812aab72003-08-12 19:11:07 +00003704
Chris Lattnerd4252a72004-07-30 07:50:03 +00003705 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3706 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003707 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003708 ConstantIntegral::getAllOnesValue(I.getType()));
3709 } else {
3710 A = 0;
3711 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003712 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003713 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3714 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003715 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003716 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003717
Misha Brukman9c003d82004-07-30 12:50:08 +00003718 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003719 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3720 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3721 I.getName()+".demorgan"), I);
3722 return BinaryOperator::createNot(And);
3723 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003724 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003725
Reid Spencer266e42b2006-12-23 06:05:41 +00003726 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3727 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3728 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003729 return R;
3730
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003731 Value *LHSVal, *RHSVal;
3732 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003733 ICmpInst::Predicate LHSCC, RHSCC;
3734 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3735 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3736 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3737 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3738 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3739 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3740 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3741 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003742 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003743 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3744 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3745 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3746 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003747 if (cast<ConstantBool>(Cmp)->getValue()) {
3748 std::swap(LHS, RHS);
3749 std::swap(LHSCst, RHSCst);
3750 std::swap(LHSCC, RHSCC);
3751 }
3752
Reid Spencer266e42b2006-12-23 06:05:41 +00003753 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003754 // comparing a value against two constants and or'ing the result
3755 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003756 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3757 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003758 // equal.
3759 assert(LHSCst != RHSCst && "Compares not folded above?");
3760
3761 switch (LHSCC) {
3762 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 switch (RHSCC) {
3765 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003766 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003767 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3768 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3769 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3770 LHSVal->getName()+".off");
3771 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003772 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003773 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003774 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003775 break; // (X == 13 | X == 15) -> no change
3776 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3777 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003778 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3780 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3781 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003782 return ReplaceInstUsesWith(I, RHS);
3783 }
3784 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003785 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003786 switch (RHSCC) {
3787 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003788 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3789 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3790 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003791 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003792 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3793 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3794 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003795 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003796 }
3797 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003798 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003799 switch (RHSCC) {
3800 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003801 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003802 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003803 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3804 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3805 false, I);
3806 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3807 break;
3808 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3809 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003810 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003811 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3812 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003813 }
3814 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003815 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003816 switch (RHSCC) {
3817 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003818 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3819 break;
3820 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3821 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3822 false, I);
3823 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3824 break;
3825 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3826 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3827 return ReplaceInstUsesWith(I, RHS);
3828 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3829 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003830 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003831 break;
3832 case ICmpInst::ICMP_UGT:
3833 switch (RHSCC) {
3834 default: assert(0 && "Unknown integer condition code!");
3835 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3836 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3837 return ReplaceInstUsesWith(I, LHS);
3838 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3839 break;
3840 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3841 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3842 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3843 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3844 break;
3845 }
3846 break;
3847 case ICmpInst::ICMP_SGT:
3848 switch (RHSCC) {
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3851 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3852 return ReplaceInstUsesWith(I, LHS);
3853 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3854 break;
3855 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3856 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3857 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3858 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3859 break;
3860 }
3861 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003862 }
3863 }
3864 }
Chris Lattner3af10532006-05-05 06:39:07 +00003865
3866 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003867 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003868 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003869 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3870 const Type *SrcTy = Op0C->getOperand(0)->getType();
3871 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3872 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003873 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3874 I.getType(), TD) &&
3875 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3876 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003877 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3878 Op1C->getOperand(0),
3879 I.getName());
3880 InsertNewInstBefore(NewOp, I);
3881 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3882 }
Chris Lattner3af10532006-05-05 06:39:07 +00003883 }
Chris Lattner3af10532006-05-05 06:39:07 +00003884
Chris Lattner15212982005-09-18 03:42:07 +00003885
Chris Lattner113f4f42002-06-25 16:13:24 +00003886 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003887}
3888
Chris Lattnerc2076352004-02-16 01:20:27 +00003889// XorSelf - Implements: X ^ X --> 0
3890struct XorSelf {
3891 Value *RHS;
3892 XorSelf(Value *rhs) : RHS(rhs) {}
3893 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3894 Instruction *apply(BinaryOperator &Xor) const {
3895 return &Xor;
3896 }
3897};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003898
3899
Chris Lattner113f4f42002-06-25 16:13:24 +00003900Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003901 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003903
Chris Lattner81a7a232004-10-16 18:11:37 +00003904 if (isa<UndefValue>(Op1))
3905 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3906
Chris Lattnerc2076352004-02-16 01:20:27 +00003907 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3908 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3909 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003910 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003911 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003912
3913 // See if we can simplify any instructions used by the instruction whose sole
3914 // purpose is to compute bits we don't care about.
3915 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003916 if (!isa<PackedType>(I.getType()) &&
3917 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003918 KnownZero, KnownOne))
3919 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003920
Chris Lattner97638592003-07-23 21:37:07 +00003921 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003922 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3923 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3924 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3925 return new ICmpInst(ICI->getInversePredicate(),
3926 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003927
Reid Spencer266e42b2006-12-23 06:05:41 +00003928 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003929 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003930 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3931 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003932 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3933 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003934 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003935 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003936 }
Chris Lattner023a4832004-06-18 06:07:51 +00003937
3938 // ~(~X & Y) --> (X | ~Y)
3939 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3940 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3941 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3942 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003943 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003944 Op0I->getOperand(1)->getName()+".not");
3945 InsertNewInstBefore(NotY, I);
3946 return BinaryOperator::createOr(Op0NotVal, NotY);
3947 }
3948 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003949
Chris Lattner97638592003-07-23 21:37:07 +00003950 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003951 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003952 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003953 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003954 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3955 return BinaryOperator::createSub(
3956 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003957 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003958 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003959 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003960 } else if (Op0I->getOpcode() == Instruction::Or) {
3961 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3962 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3963 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3964 // Anything in both C1 and C2 is known to be zero, remove it from
3965 // NewRHS.
3966 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3967 NewRHS = ConstantExpr::getAnd(NewRHS,
3968 ConstantExpr::getNot(CommonBits));
3969 WorkList.push_back(Op0I);
3970 I.setOperand(0, Op0I->getOperand(0));
3971 I.setOperand(1, NewRHS);
3972 return &I;
3973 }
Chris Lattner97638592003-07-23 21:37:07 +00003974 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003975 }
Chris Lattner183b3362004-04-09 19:05:30 +00003976
3977 // Try to fold constant and into select arguments.
3978 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003979 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003980 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003981 if (isa<PHINode>(Op0))
3982 if (Instruction *NV = FoldOpIntoPhi(I))
3983 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003984 }
3985
Chris Lattnerbb74e222003-03-10 23:06:50 +00003986 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003987 if (X == Op1)
3988 return ReplaceInstUsesWith(I,
3989 ConstantIntegral::getAllOnesValue(I.getType()));
3990
Chris Lattnerbb74e222003-03-10 23:06:50 +00003991 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003992 if (X == Op0)
3993 return ReplaceInstUsesWith(I,
3994 ConstantIntegral::getAllOnesValue(I.getType()));
3995
Chris Lattnerdcd07922006-04-01 08:03:55 +00003996 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003997 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003998 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003999 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004000 I.swapOperands();
4001 std::swap(Op0, Op1);
4002 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004003 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004004 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004005 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004006 } else if (Op1I->getOpcode() == Instruction::Xor) {
4007 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4008 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4009 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4010 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004011 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4012 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4013 Op1I->swapOperands();
4014 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4015 I.swapOperands(); // Simplified below.
4016 std::swap(Op0, Op1);
4017 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004018 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004019
Chris Lattnerdcd07922006-04-01 08:03:55 +00004020 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004021 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004022 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004023 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004024 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004025 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4026 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004027 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004028 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004029 } else if (Op0I->getOpcode() == Instruction::Xor) {
4030 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4031 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4032 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4033 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004034 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4035 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4036 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004037 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4038 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004039 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4040 InsertNewInstBefore(N, I);
4041 return BinaryOperator::createAnd(N, Op1);
4042 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004043 }
4044
Reid Spencer266e42b2006-12-23 06:05:41 +00004045 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4046 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4047 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004048 return R;
4049
Chris Lattner3af10532006-05-05 06:39:07 +00004050 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004051 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004052 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004053 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4054 const Type *SrcTy = Op0C->getOperand(0)->getType();
4055 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4056 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004057 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4058 I.getType(), TD) &&
4059 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4060 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004061 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4062 Op1C->getOperand(0),
4063 I.getName());
4064 InsertNewInstBefore(NewOp, I);
4065 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4066 }
Chris Lattner3af10532006-05-05 06:39:07 +00004067 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004068
4069 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4070 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4071 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4072 if (SI0->getOpcode() == SI1->getOpcode() &&
4073 SI0->getOperand(1) == SI1->getOperand(1) &&
4074 (SI0->hasOneUse() || SI1->hasOneUse())) {
4075 Instruction *NewOp =
4076 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4077 SI1->getOperand(0),
4078 SI0->getName()), I);
4079 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4080 }
4081 }
Chris Lattner3af10532006-05-05 06:39:07 +00004082
Chris Lattner113f4f42002-06-25 16:13:24 +00004083 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004084}
4085
Chris Lattner6862fbd2004-09-29 17:40:11 +00004086static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004087 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004088}
4089
4090/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4091/// overflowed for this type.
4092static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4093 ConstantInt *In2) {
4094 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4095
4096 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00004097 return cast<ConstantInt>(Result)->getZExtValue() <
4098 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004099 if (isPositive(In1) != isPositive(In2))
4100 return false;
4101 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00004102 return cast<ConstantInt>(Result)->getSExtValue() <
4103 cast<ConstantInt>(In1)->getSExtValue();
4104 return cast<ConstantInt>(Result)->getSExtValue() >
4105 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004106}
4107
Chris Lattner0798af32005-01-13 20:14:25 +00004108/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4109/// code necessary to compute the offset from the base pointer (without adding
4110/// in the base pointer). Return the result as a signed integer of intptr size.
4111static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4112 TargetData &TD = IC.getTargetData();
4113 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004114 const Type *IntPtrTy = TD.getIntPtrType();
4115 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004116
4117 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004118 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004119
Chris Lattner0798af32005-01-13 20:14:25 +00004120 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4121 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004122 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004123 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004124 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4125 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004126 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004127 Scale = ConstantExpr::getMul(OpC, Scale);
4128 if (Constant *RC = dyn_cast<Constant>(Result))
4129 Result = ConstantExpr::getAdd(RC, Scale);
4130 else {
4131 // Emit an add instruction.
4132 Result = IC.InsertNewInstBefore(
4133 BinaryOperator::createAdd(Result, Scale,
4134 GEP->getName()+".offs"), I);
4135 }
4136 }
4137 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004138 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004139 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004140 Op->getName()+".c"), I);
4141 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004142 // We'll let instcombine(mul) convert this to a shl if possible.
4143 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4144 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004145
4146 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004147 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004148 GEP->getName()+".offs"), I);
4149 }
4150 }
4151 return Result;
4152}
4153
Reid Spencer266e42b2006-12-23 06:05:41 +00004154/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004155/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004156Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4157 ICmpInst::Predicate Cond,
4158 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004159 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004160
4161 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4162 if (isa<PointerType>(CI->getOperand(0)->getType()))
4163 RHS = CI->getOperand(0);
4164
Chris Lattner0798af32005-01-13 20:14:25 +00004165 Value *PtrBase = GEPLHS->getOperand(0);
4166 if (PtrBase == RHS) {
4167 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4169 // each index is zero or not.
4170 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004171 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004172 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4173 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004174 bool EmitIt = true;
4175 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4176 if (isa<UndefValue>(C)) // undef index -> undef.
4177 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4178 if (C->isNullValue())
4179 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004180 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4181 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004182 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004183 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004184 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004185 }
4186
4187 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004188 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004189 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004190 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4191 if (InVal == 0)
4192 InVal = Comp;
4193 else {
4194 InVal = InsertNewInstBefore(InVal, I);
4195 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004196 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004197 InVal = BinaryOperator::createOr(InVal, Comp);
4198 else // True if all are equal
4199 InVal = BinaryOperator::createAnd(InVal, Comp);
4200 }
4201 }
4202 }
4203
4204 if (InVal)
4205 return InVal;
4206 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004207 // No comparison is needed here, all indexes = 0
4208 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004209 }
Chris Lattner0798af32005-01-13 20:14:25 +00004210
Reid Spencer266e42b2006-12-23 06:05:41 +00004211 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004212 // the result to fold to a constant!
4213 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4214 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4215 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004216 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4217 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004218 }
4219 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004220 // If the base pointers are different, but the indices are the same, just
4221 // compare the base pointer.
4222 if (PtrBase != GEPRHS->getOperand(0)) {
4223 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004224 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004225 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004226 if (IndicesTheSame)
4227 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4228 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4229 IndicesTheSame = false;
4230 break;
4231 }
4232
4233 // If all indices are the same, just compare the base pointers.
4234 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004235 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4236 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004237
4238 // Otherwise, the base pointers are different and the indices are
4239 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004240 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004241 }
Chris Lattner0798af32005-01-13 20:14:25 +00004242
Chris Lattner81e84172005-01-13 22:25:21 +00004243 // If one of the GEPs has all zero indices, recurse.
4244 bool AllZeros = true;
4245 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4246 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4247 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4248 AllZeros = false;
4249 break;
4250 }
4251 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004252 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4253 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004254
4255 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004256 AllZeros = true;
4257 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4258 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4259 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4260 AllZeros = false;
4261 break;
4262 }
4263 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004264 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004265
Chris Lattner4fa89822005-01-14 00:20:05 +00004266 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4267 // If the GEPs only differ by one index, compare it.
4268 unsigned NumDifferences = 0; // Keep track of # differences.
4269 unsigned DiffOperand = 0; // The operand that differs.
4270 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4271 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004272 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4273 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004274 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004275 NumDifferences = 2;
4276 break;
4277 } else {
4278 if (NumDifferences++) break;
4279 DiffOperand = i;
4280 }
4281 }
4282
4283 if (NumDifferences == 0) // SAME GEP?
4284 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004285 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004286 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004287 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4288 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004289 if (LHSV->getType() != RHSV->getType())
4290 // Doesn't matter which one we bitconvert here.
4291 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, RHSV->getType(),
4292 I);
4293 // Make sure we do a signed comparison here.
4294 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004295 }
4296 }
4297
Reid Spencer266e42b2006-12-23 06:05:41 +00004298 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004299 // the result to fold to a constant!
4300 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4301 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4302 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4303 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4304 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004305 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004306 }
4307 }
4308 return 0;
4309}
4310
Reid Spencer266e42b2006-12-23 06:05:41 +00004311Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4312 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004314
Reid Spencer266e42b2006-12-23 06:05:41 +00004315 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004316 if (Op0 == Op1)
4317 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004318
Reid Spencer266e42b2006-12-23 06:05:41 +00004319 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00004320 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4321
Reid Spencer266e42b2006-12-23 06:05:41 +00004322 // Handle fcmp with constant RHS
4323 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4324 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4325 switch (LHSI->getOpcode()) {
4326 case Instruction::PHI:
4327 if (Instruction *NV = FoldOpIntoPhi(I))
4328 return NV;
4329 break;
4330 case Instruction::Select:
4331 // If either operand of the select is a constant, we can fold the
4332 // comparison into the select arms, which will cause one to be
4333 // constant folded and the select turned into a bitwise or.
4334 Value *Op1 = 0, *Op2 = 0;
4335 if (LHSI->hasOneUse()) {
4336 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4337 // Fold the known value into the constant operand.
4338 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4339 // Insert a new FCmp of the other select operand.
4340 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4341 LHSI->getOperand(2), RHSC,
4342 I.getName()), I);
4343 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4344 // Fold the known value into the constant operand.
4345 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4346 // Insert a new FCmp of the other select operand.
4347 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4348 LHSI->getOperand(1), RHSC,
4349 I.getName()), I);
4350 }
4351 }
4352
4353 if (Op1)
4354 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4355 break;
4356 }
4357 }
4358
4359 return Changed ? &I : 0;
4360}
4361
4362Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4363 bool Changed = SimplifyCompare(I);
4364 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4365 const Type *Ty = Op0->getType();
4366
4367 // icmp X, X
4368 if (Op0 == Op1)
4369 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4370
4371 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4372 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4373
4374 // icmp of GlobalValues can never equal each other as long as they aren't
4375 // external weak linkage type.
4376 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4377 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4378 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4379 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4380
4381 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004382 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004383 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4384 isa<ConstantPointerNull>(Op0)) &&
4385 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004386 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004387 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4388
Reid Spencer266e42b2006-12-23 06:05:41 +00004389 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004390 if (Ty == Type::BoolTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004391 switch (I.getPredicate()) {
4392 default: assert(0 && "Invalid icmp instruction!");
4393 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004394 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004395 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004396 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004397 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004398 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004399 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004400
Reid Spencer266e42b2006-12-23 06:05:41 +00004401 case ICmpInst::ICMP_UGT:
4402 case ICmpInst::ICMP_SGT:
4403 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004404 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004405 case ICmpInst::ICMP_ULT:
4406 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004407 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4408 InsertNewInstBefore(Not, I);
4409 return BinaryOperator::createAnd(Not, Op1);
4410 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004411 case ICmpInst::ICMP_UGE:
4412 case ICmpInst::ICMP_SGE:
4413 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004414 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004415 case ICmpInst::ICMP_ULE:
4416 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004417 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4418 InsertNewInstBefore(Not, I);
4419 return BinaryOperator::createOr(Not, Op1);
4420 }
4421 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004422 }
4423
Chris Lattner2dd01742004-06-09 04:24:29 +00004424 // See if we are doing a comparison between a constant and an instruction that
4425 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004426 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004427 switch (I.getPredicate()) {
4428 default: break;
4429 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4430 if (CI->isMinValue(false))
Chris Lattner6ab03f62006-09-28 23:35:22 +00004431 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004432 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4433 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4434 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4435 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4436 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004437
Reid Spencer266e42b2006-12-23 06:05:41 +00004438 case ICmpInst::ICMP_SLT:
4439 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004440 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004441 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4442 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4443 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4444 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4445 break;
4446
4447 case ICmpInst::ICMP_UGT:
4448 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4449 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4450 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4451 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4452 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4453 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4454 break;
4455
4456 case ICmpInst::ICMP_SGT:
4457 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4458 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4459 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4460 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4461 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4462 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4463 break;
4464
4465 case ICmpInst::ICMP_ULE:
4466 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004467 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004468 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4469 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4470 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4471 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4472 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004473
Reid Spencer266e42b2006-12-23 06:05:41 +00004474 case ICmpInst::ICMP_SLE:
4475 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4476 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4477 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4478 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4479 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4480 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4481 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004482
Reid Spencer266e42b2006-12-23 06:05:41 +00004483 case ICmpInst::ICMP_UGE:
4484 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4485 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4486 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4487 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4488 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4489 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4490 break;
4491
4492 case ICmpInst::ICMP_SGE:
4493 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4494 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4495 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4496 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4497 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4498 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4499 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004500 }
4501
Reid Spencer266e42b2006-12-23 06:05:41 +00004502 // If we still have a icmp le or icmp ge instruction, turn it into the
4503 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004504 // already been handled above, this requires little checking.
4505 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004506 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4507 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4508 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4509 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4510 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4511 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4512 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4513 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004514
4515 // See if we can fold the comparison based on bits known to be zero or one
4516 // in the input.
4517 uint64_t KnownZero, KnownOne;
4518 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4519 KnownZero, KnownOne, 0))
4520 return &I;
4521
4522 // Given the known and unknown bits, compute a range that the LHS could be
4523 // in.
4524 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 // Compute the Min, Max and RHS values based on the known bits. For the
4526 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004527 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4528 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004529 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4530 SRHSVal = CI->getSExtValue();
4531 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4532 SMax);
4533 } else {
4534 URHSVal = CI->getZExtValue();
4535 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4536 UMax);
4537 }
4538 switch (I.getPredicate()) { // LE/GE have been folded already.
4539 default: assert(0 && "Unknown icmp opcode!");
4540 case ICmpInst::ICMP_EQ:
4541 if (UMax < URHSVal || UMin > URHSVal)
4542 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4543 break;
4544 case ICmpInst::ICMP_NE:
4545 if (UMax < URHSVal || UMin > URHSVal)
4546 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4547 break;
4548 case ICmpInst::ICMP_ULT:
4549 if (UMax < URHSVal)
4550 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4551 if (UMin > URHSVal)
4552 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4553 break;
4554 case ICmpInst::ICMP_UGT:
4555 if (UMin > URHSVal)
4556 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4557 if (UMax < URHSVal)
4558 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4559 break;
4560 case ICmpInst::ICMP_SLT:
4561 if (SMax < SRHSVal)
4562 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4563 if (SMin > SRHSVal)
4564 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4565 break;
4566 case ICmpInst::ICMP_SGT:
4567 if (SMin > SRHSVal)
4568 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4569 if (SMax < SRHSVal)
4570 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4571 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004572 }
4573 }
4574
Reid Spencer266e42b2006-12-23 06:05:41 +00004575 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004576 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004577 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004578 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004579 switch (LHSI->getOpcode()) {
4580 case Instruction::And:
4581 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4582 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004583 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4584
Reid Spencer266e42b2006-12-23 06:05:41 +00004585 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004586 // and/compare to be the input width without changing the value
4587 // produced, eliminating a cast.
4588 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4589 // We can do this transformation if either the AND constant does not
4590 // have its sign bit set or if it is an equality comparison.
4591 // Extending a relational comparison when we're checking the sign
4592 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004593 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004594 (I.isEquality() ||
4595 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4596 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4597 ConstantInt *NewCST;
4598 ConstantInt *NewCI;
4599 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004600 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004601 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004602 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004603 CI->getZExtValue());
4604 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004605 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004606 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004607 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004608 CI->getZExtValue());
4609 }
4610 Instruction *NewAnd =
4611 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4612 LHSI->getName());
4613 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004614 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004615 }
4616 }
4617
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004618 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4619 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4620 // happens a LOT in code produced by the C front-end, for bitfield
4621 // access.
4622 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004623
4624 // Check to see if there is a noop-cast between the shift and the and.
4625 if (!Shift) {
4626 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004627 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004628 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4629 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004630
Reid Spencere0fc4df2006-10-20 07:07:24 +00004631 ConstantInt *ShAmt;
4632 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004633 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4634 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004635
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004636 // We can fold this as long as we can't shift unknown bits
4637 // into the mask. This can only happen with signed shift
4638 // rights, as they sign-extend.
4639 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004640 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004641 if (!CanFold) {
4642 // To test for the bad case of the signed shr, see if any
4643 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004644 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004645 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4646
Reid Spencere0fc4df2006-10-20 07:07:24 +00004647 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004648 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004649 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4650 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004651 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4652 CanFold = true;
4653 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004654
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004655 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004656 Constant *NewCst;
4657 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004658 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004659 else
4660 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004661
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004662 // Check to see if we are shifting out any of the bits being
4663 // compared.
4664 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4665 // If we shifted bits out, the fold is not going to work out.
4666 // As a special case, check to see if this means that the
4667 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004668 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004669 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004670 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004671 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004672 } else {
4673 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004674 Constant *NewAndCST;
4675 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004676 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004677 else
4678 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4679 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004680 if (AndTy == Ty)
4681 LHSI->setOperand(0, Shift->getOperand(0));
4682 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004683 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4684 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004685 *Shift);
4686 LHSI->setOperand(0, NewCast);
4687 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004688 WorkList.push_back(Shift); // Shift is dead.
4689 AddUsesToWorkList(I);
4690 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004691 }
4692 }
Chris Lattner35167c32004-06-09 07:59:58 +00004693 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004694
4695 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4696 // preferable because it allows the C<<Y expression to be hoisted out
4697 // of a loop if Y is invariant and X is not.
4698 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004699 I.isEquality() && !Shift->isArithmeticShift() &&
4700 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004701 // Compute C << Y.
4702 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004703 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004704 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4705 "tmp");
4706 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004707 // Insert a logical shift.
4708 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004709 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004710 }
4711 InsertNewInstBefore(cast<Instruction>(NS), I);
4712
4713 // If C's sign doesn't agree with the and, insert a cast now.
4714 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004715 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4716 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004717
4718 Value *ShiftOp = Shift->getOperand(0);
4719 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004720 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4721 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004722
4723 // Compute X & (C << Y).
4724 Instruction *NewAnd =
4725 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4726 InsertNewInstBefore(NewAnd, I);
4727
4728 I.setOperand(0, NewAnd);
4729 return &I;
4730 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004731 }
4732 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004733
Reid Spencer266e42b2006-12-23 06:05:41 +00004734 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004735 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004736 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004737 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4738
4739 // Check that the shift amount is in range. If not, don't perform
4740 // undefined shifts. When the shift is visited it will be
4741 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004742 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004743 break;
4744
Chris Lattner272d5ca2004-09-28 18:22:15 +00004745 // If we are comparing against bits always shifted out, the
4746 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004747 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004748 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004749 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004750 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4751 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004752 return ReplaceInstUsesWith(I, Cst);
4753 }
4754
4755 if (LHSI->hasOneUse()) {
4756 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004757 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004758 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4759
4760 Constant *Mask;
4761 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004762 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004763 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004764 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004765 } else {
4766 Mask = ConstantInt::getAllOnesValue(CI->getType());
4767 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004768
Chris Lattner272d5ca2004-09-28 18:22:15 +00004769 Instruction *AndI =
4770 BinaryOperator::createAnd(LHSI->getOperand(0),
4771 Mask, LHSI->getName()+".mask");
4772 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004773 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004774 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004775 }
4776 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004777 }
4778 break;
4779
Reid Spencer266e42b2006-12-23 06:05:41 +00004780 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004781 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004782 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004783 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004784 // Check that the shift amount is in range. If not, don't perform
4785 // undefined shifts. When the shift is visited it will be
4786 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004787 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004788 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004789 break;
4790
Chris Lattner1023b872004-09-27 16:18:50 +00004791 // If we are comparing against bits always shifted out, the
4792 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004793 Constant *Comp;
4794 if (CI->getType()->isUnsigned())
4795 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4796 ShAmt);
4797 else
4798 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4799 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004800
Chris Lattner1023b872004-09-27 16:18:50 +00004801 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004802 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4803 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004804 return ReplaceInstUsesWith(I, Cst);
4805 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004806
Chris Lattner1023b872004-09-27 16:18:50 +00004807 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004808 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004809
Chris Lattner1023b872004-09-27 16:18:50 +00004810 // Otherwise strength reduce the shift into an and.
4811 uint64_t Val = ~0ULL; // All ones.
4812 Val <<= ShAmtVal; // Shift over to the right spot.
4813
4814 Constant *Mask;
4815 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004816 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004817 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004818 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004819 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004820 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004821
Chris Lattner1023b872004-09-27 16:18:50 +00004822 Instruction *AndI =
4823 BinaryOperator::createAnd(LHSI->getOperand(0),
4824 Mask, LHSI->getName()+".mask");
4825 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004826 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004827 ConstantExpr::getShl(CI, ShAmt));
4828 }
Chris Lattner1023b872004-09-27 16:18:50 +00004829 }
4830 }
4831 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004832
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004833 case Instruction::SDiv:
4834 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004835 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004836 // Fold this div into the comparison, producing a range check.
4837 // Determine, based on the divide type, what the range is being
4838 // checked. If there is an overflow on the low or high side, remember
4839 // it, otherwise compute the range [low, hi) bounding the new value.
4840 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004841 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004842 // FIXME: If the operand types don't match the type of the divide
4843 // then don't attempt this transform. The code below doesn't have the
4844 // logic to deal with a signed divide and an unsigned compare (and
4845 // vice versa). This is because (x /s C1) <s C2 produces different
4846 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4847 // (x /u C1) <u C2. Simply casting the operands and result won't
4848 // work. :( The if statement below tests that condition and bails
4849 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004850 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4851 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004852 break;
4853
4854 // Initialize the variables that will indicate the nature of the
4855 // range check.
4856 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004857 ConstantInt *LoBound = 0, *HiBound = 0;
4858
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004859 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4860 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4861 // C2 (CI). By solving for X we can turn this into a range check
4862 // instead of computing a divide.
4863 ConstantInt *Prod =
4864 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004865
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004866 // Determine if the product overflows by seeing if the product is
4867 // not equal to the divide. Make sure we do the same kind of divide
4868 // as in the LHS instruction that we're folding.
4869 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004871 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4872
Reid Spencer266e42b2006-12-23 06:05:41 +00004873 // Get the ICmp opcode
4874 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004875
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004876 if (DivRHS->isNullValue()) {
4877 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004878 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004879 LoBound = Prod;
4880 LoOverflow = ProdOV;
4881 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004882 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004883 if (CI->isNullValue()) { // (X / pos) op 0
4884 // Can't overflow.
4885 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4886 HiBound = DivRHS;
4887 } else if (isPositive(CI)) { // (X / pos) op pos
4888 LoBound = Prod;
4889 LoOverflow = ProdOV;
4890 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4891 } else { // (X / pos) op neg
4892 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4893 LoOverflow = AddWithOverflow(LoBound, Prod,
4894 cast<ConstantInt>(DivRHSH));
4895 HiBound = Prod;
4896 HiOverflow = ProdOV;
4897 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004898 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004899 if (CI->isNullValue()) { // (X / neg) op 0
4900 LoBound = AddOne(DivRHS);
4901 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004902 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004903 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004904 } else if (isPositive(CI)) { // (X / neg) op pos
4905 HiOverflow = LoOverflow = ProdOV;
4906 if (!LoOverflow)
4907 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4908 HiBound = AddOne(Prod);
4909 } else { // (X / neg) op neg
4910 LoBound = Prod;
4911 LoOverflow = HiOverflow = ProdOV;
4912 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4913 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004914
Chris Lattnera92af962004-10-11 19:40:04 +00004915 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004916 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004917 }
4918
4919 if (LoBound) {
4920 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004921 switch (predicate) {
4922 default: assert(0 && "Unhandled icmp opcode!");
4923 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004924 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004925 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004926 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4928 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004929 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004930 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4931 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004932 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004933 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4934 true, I);
4935 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004936 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004937 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004938 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004939 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4940 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004941 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4943 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004944 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004945 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4946 false, I);
4947 case ICmpInst::ICMP_ULT:
4948 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004949 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004950 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004951 return new ICmpInst(predicate, X, LoBound);
4952 case ICmpInst::ICMP_UGT:
4953 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004954 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004955 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004956 if (predicate == ICmpInst::ICMP_UGT)
4957 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4958 else
4959 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004960 }
4961 }
4962 }
4963 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004964 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004965
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004967 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004968 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004969
Reid Spencere0fc4df2006-10-20 07:07:24 +00004970 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4971 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4973 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004974 case Instruction::SRem:
4975 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4976 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4977 BO->hasOneUse()) {
4978 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4979 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004980 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4981 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004982 return new ICmpInst(I.getPredicate(), NewRem,
4983 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004984 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004985 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004986 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004987 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004988 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4989 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004990 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004991 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4992 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004993 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004994 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4995 // efficiently invertible, or if the add has just this one use.
4996 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004997
Chris Lattnerc992add2003-08-13 05:33:12 +00004998 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004999 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00005000 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005001 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005002 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00005003 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
5004 BO->setName("");
5005 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00005006 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00005007 }
5008 }
5009 break;
5010 case Instruction::Xor:
5011 // For the xor case, we can xor two constants together, eliminating
5012 // the explicit xor.
5013 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00005014 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5015 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00005016
5017 // FALLTHROUGH
5018 case Instruction::Sub:
5019 // Replace (([sub|xor] A, B) != 0) with (A != B)
5020 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005021 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5022 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00005023 break;
5024
5025 case Instruction::Or:
5026 // If bits are being or'd in that are not present in the constant we
5027 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005028 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005029 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005030 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005031 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00005032 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005033 break;
5034
5035 case Instruction::And:
5036 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005037 // If bits are being compared against that are and'd out, then the
5038 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00005039 if (!ConstantExpr::getAnd(CI,
5040 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005042
Chris Lattner35167c32004-06-09 07:59:58 +00005043 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005044 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005045 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5046 ICmpInst::ICMP_NE, Op0,
5047 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005048
Reid Spencer266e42b2006-12-23 06:05:41 +00005049 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005050 if (isSignBit(BOC)) {
5051 Value *X = BO->getOperand(0);
5052 // If 'X' is not signed, insert a cast now...
5053 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00005054 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00005055 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00005056 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 Constant *Zero = Constant::getNullValue(X->getType());
5058 ICmpInst::Predicate pred = isICMP_NE ?
5059 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5060 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005061 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005062
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005063 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005064 if (CI->isNullValue() && isHighOnes(BOC)) {
5065 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005066 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005067 ICmpInst::Predicate pred = isICMP_NE ?
5068 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5069 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005070 }
5071
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005072 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005073 default: break;
5074 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005075 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5076 // Handle set{eq|ne} <intrinsic>, intcst.
5077 switch (II->getIntrinsicID()) {
5078 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005079 case Intrinsic::bswap_i16:
5080 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005081 WorkList.push_back(II); // Dead?
5082 I.setOperand(0, II->getOperand(1));
5083 I.setOperand(1, ConstantInt::get(Type::UShortTy,
5084 ByteSwap_16(CI->getZExtValue())));
5085 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005086 case Intrinsic::bswap_i32:
5087 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005088 WorkList.push_back(II); // Dead?
5089 I.setOperand(0, II->getOperand(1));
5090 I.setOperand(1, ConstantInt::get(Type::UIntTy,
5091 ByteSwap_32(CI->getZExtValue())));
5092 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005093 case Intrinsic::bswap_i64:
5094 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005095 WorkList.push_back(II); // Dead?
5096 I.setOperand(0, II->getOperand(1));
5097 I.setOperand(1, ConstantInt::get(Type::ULongTy,
5098 ByteSwap_64(CI->getZExtValue())));
5099 return &I;
5100 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005101 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005102 } else { // Not a ICMP_EQ/ICMP_NE
5103 // If the LHS is a cast from an integral value of the same size, then
5104 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005105 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5106 Value *CastOp = Cast->getOperand(0);
5107 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005108 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005109 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005110 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005111 // If this is an unsigned comparison, try to make the comparison use
5112 // smaller constant values.
5113 switch (I.getPredicate()) {
5114 default: break;
5115 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5116 ConstantInt *CUI = cast<ConstantInt>(CI);
5117 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5118 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5119 ConstantInt::get(SrcTy, -1));
5120 break;
5121 }
5122 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5123 ConstantInt *CUI = cast<ConstantInt>(CI);
5124 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5125 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5126 Constant::getNullValue(SrcTy));
5127 break;
5128 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005129 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005130
Chris Lattner2b55ea32004-02-23 07:16:20 +00005131 }
5132 }
Chris Lattnere967b342003-06-04 05:10:11 +00005133 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005134 }
5135
Reid Spencer266e42b2006-12-23 06:05:41 +00005136 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005137 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5138 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5139 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005140 case Instruction::GetElementPtr:
5141 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005142 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005143 bool isAllZeros = true;
5144 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5145 if (!isa<Constant>(LHSI->getOperand(i)) ||
5146 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5147 isAllZeros = false;
5148 break;
5149 }
5150 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005151 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005152 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5153 }
5154 break;
5155
Chris Lattner77c32c32005-04-23 15:31:55 +00005156 case Instruction::PHI:
5157 if (Instruction *NV = FoldOpIntoPhi(I))
5158 return NV;
5159 break;
5160 case Instruction::Select:
5161 // If either operand of the select is a constant, we can fold the
5162 // comparison into the select arms, which will cause one to be
5163 // constant folded and the select turned into a bitwise or.
5164 Value *Op1 = 0, *Op2 = 0;
5165 if (LHSI->hasOneUse()) {
5166 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5167 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005168 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5169 // Insert a new ICmp of the other select operand.
5170 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5171 LHSI->getOperand(2), RHSC,
5172 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005173 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5174 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005175 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5176 // Insert a new ICmp of the other select operand.
5177 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5178 LHSI->getOperand(1), RHSC,
5179 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005180 }
5181 }
Jeff Cohen82639852005-04-23 21:38:35 +00005182
Chris Lattner77c32c32005-04-23 15:31:55 +00005183 if (Op1)
5184 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5185 break;
5186 }
5187 }
5188
Reid Spencer266e42b2006-12-23 06:05:41 +00005189 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005190 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005191 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005192 return NI;
5193 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005194 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5195 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005196 return NI;
5197
Reid Spencer266e42b2006-12-23 06:05:41 +00005198 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner16930792003-11-03 04:25:02 +00005199 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00005200 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5201 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005202 if (CI->isLosslessCast() && I.isEquality() &&
5203 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005204 // We keep moving the cast from the left operand over to the right
5205 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00005206 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005207
Chris Lattner16930792003-11-03 04:25:02 +00005208 // If operand #1 is a cast instruction, see if we can eliminate it as
5209 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005210 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
5211 Value *CI2Op0 = CI2->getOperand(0);
5212 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5213 Op1 = CI2Op0;
5214 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005215
Chris Lattner16930792003-11-03 04:25:02 +00005216 // If Op1 is a constant, we can fold the cast into the constant.
5217 if (Op1->getType() != Op0->getType())
5218 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005219 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005220 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005221 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005222 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005223 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005224 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005225 }
5226
Reid Spencer266e42b2006-12-23 06:05:41 +00005227 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005228 // This comes up when you have code like
5229 // int X = A < B;
5230 // if (X) ...
5231 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005232 // with a constant or another cast from the same type.
5233 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005234 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005235 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005236 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005237
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005238 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005239 Value *A, *B;
5240 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5241 (A == Op1 || B == Op1)) {
5242 // (A^B) == A -> B == 0
5243 Value *OtherVal = A == Op1 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005244 return new ICmpInst(I.getPredicate(), OtherVal,
5245 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005246 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5247 (A == Op0 || B == Op0)) {
5248 // A == (A^B) -> B == 0
5249 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 return new ICmpInst(I.getPredicate(), OtherVal,
5251 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005252 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5253 // (A-B) == A -> 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 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5257 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005258 return new ICmpInst(I.getPredicate(), B,
5259 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005260 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005261
5262 Value *C, *D;
5263 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5264 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5265 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5266 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5267 Value *X = 0, *Y = 0, *Z = 0;
5268
5269 if (A == C) {
5270 X = B; Y = D; Z = A;
5271 } else if (A == D) {
5272 X = B; Y = C; Z = A;
5273 } else if (B == C) {
5274 X = A; Y = D; Z = B;
5275 } else if (B == D) {
5276 X = A; Y = C; Z = B;
5277 }
5278
5279 if (X) { // Build (X^Y) & Z
5280 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5281 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5282 I.setOperand(0, Op1);
5283 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5284 return &I;
5285 }
5286 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005287 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005288 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005289}
5290
Reid Spencer266e42b2006-12-23 06:05:41 +00005291// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005292// We only handle extending casts so far.
5293//
Reid Spencer266e42b2006-12-23 06:05:41 +00005294Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5295 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005296 Value *LHSCIOp = LHSCI->getOperand(0);
5297 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005298 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005299 Value *RHSCIOp;
5300
Reid Spencer266e42b2006-12-23 06:05:41 +00005301 // We only handle extension cast instructions, so far. Enforce this.
5302 if (LHSCI->getOpcode() != Instruction::ZExt &&
5303 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005304 return 0;
5305
Reid Spencer266e42b2006-12-23 06:05:41 +00005306 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5307 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005308
Reid Spencer266e42b2006-12-23 06:05:41 +00005309 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005310 // Not an extension from the same type?
5311 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005312 if (RHSCIOp->getType() != LHSCIOp->getType())
5313 return 0;
5314 else
5315 // Okay, just insert a compare of the reduced operands now!
5316 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005317 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005318
Reid Spencer266e42b2006-12-23 06:05:41 +00005319 // If we aren't dealing with a constant on the RHS, exit early
5320 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5321 if (!CI)
5322 return 0;
5323
5324 // Compute the constant that would happen if we truncated to SrcTy then
5325 // reextended to DestTy.
5326 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5327 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5328
5329 // If the re-extended constant didn't change...
5330 if (Res2 == CI) {
5331 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5332 // For example, we might have:
5333 // %A = sext short %X to uint
5334 // %B = icmp ugt uint %A, 1330
5335 // It is incorrect to transform this into
5336 // %B = icmp ugt short %X, 1330
5337 // because %A may have negative value.
5338 //
5339 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5340 // OR operation is EQ/NE.
5341 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5342 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5343 else
5344 return 0;
5345 }
5346
5347 // The re-extended constant changed so the constant cannot be represented
5348 // in the shorter type. Consequently, we cannot emit a simple comparison.
5349
5350 // First, handle some easy cases. We know the result cannot be equal at this
5351 // point so handle the ICI.isEquality() cases
5352 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5353 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5354 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5355 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5356
5357 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5358 // should have been folded away previously and not enter in here.
5359 Value *Result;
5360 if (isSignedCmp) {
5361 // We're performing a signed comparison.
5362 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5363 Result = ConstantBool::getFalse(); // X < (small) --> false
5364 else
5365 Result = ConstantBool::getTrue(); // X < (large) --> true
5366 } else {
5367 // We're performing an unsigned comparison.
5368 if (isSignedExt) {
5369 // We're performing an unsigned comp with a sign extended value.
5370 // This is true if the input is >= 0. [aka >s -1]
5371 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5372 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5373 NegOne, ICI.getName()), ICI);
5374 } else {
5375 // Unsigned extend & unsigned compare -> always true.
5376 Result = ConstantBool::getTrue();
5377 }
5378 }
5379
5380 // Finally, return the value computed.
5381 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5382 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5383 return ReplaceInstUsesWith(ICI, Result);
5384 } else {
5385 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5386 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5387 "ICmp should be folded!");
5388 if (Constant *CI = dyn_cast<Constant>(Result))
5389 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5390 else
5391 return BinaryOperator::createNot(Result);
5392 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005393}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005394
Chris Lattnere8d6c602003-03-10 19:16:08 +00005395Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005396 assert(I.getOperand(1)->getType() == Type::UByteTy);
5397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005398
5399 // shl X, 0 == X and shr X, 0 == X
5400 // shl 0, X == 0 and shr 0, X == 0
5401 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005402 Op0 == Constant::getNullValue(Op0->getType()))
5403 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005404
Reid Spencer266e42b2006-12-23 06:05:41 +00005405 if (isa<UndefValue>(Op0)) {
5406 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005407 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005408 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5410 }
5411 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005412 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5413 return ReplaceInstUsesWith(I, Op0);
5414 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005416 }
5417
Chris Lattnerd4dee402006-11-10 23:38:52 +00005418 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5419 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005420 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005421 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005422 return ReplaceInstUsesWith(I, CSI);
5423
Chris Lattner183b3362004-04-09 19:05:30 +00005424 // Try to fold constant and into select arguments.
5425 if (isa<Constant>(Op0))
5426 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005427 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005428 return R;
5429
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005430 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005431 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005432 if (MaskedValueIsZero(Op0,
5433 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005434 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005435 }
5436 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005437
Reid Spencere0fc4df2006-10-20 07:07:24 +00005438 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5439 if (CUI->getType()->isUnsigned())
5440 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5441 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005442 return 0;
5443}
5444
Reid Spencere0fc4df2006-10-20 07:07:24 +00005445Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005446 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005447 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5448 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005449 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005450
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005451 // See if we can simplify any instructions used by the instruction whose sole
5452 // purpose is to compute bits we don't care about.
5453 uint64_t KnownZero, KnownOne;
5454 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5455 KnownZero, KnownOne))
5456 return &I;
5457
Chris Lattner14553932006-01-06 07:12:35 +00005458 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5459 // of a signed value.
5460 //
5461 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005462 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005463 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005464 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5465 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005466 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005467 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005468 }
Chris Lattner14553932006-01-06 07:12:35 +00005469 }
5470
5471 // ((X*C1) << C2) == (X * (C1 << C2))
5472 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5473 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5474 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5475 return BinaryOperator::createMul(BO->getOperand(0),
5476 ConstantExpr::getShl(BOOp, Op1));
5477
5478 // Try to fold constant and into select arguments.
5479 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5481 return R;
5482 if (isa<PHINode>(Op0))
5483 if (Instruction *NV = FoldOpIntoPhi(I))
5484 return NV;
5485
5486 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005487 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5488 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5489 Value *V1, *V2;
5490 ConstantInt *CC;
5491 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005492 default: break;
5493 case Instruction::Add:
5494 case Instruction::And:
5495 case Instruction::Or:
5496 case Instruction::Xor:
5497 // These operators commute.
5498 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005499 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5500 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005501 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005502 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005503 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005504 Op0BO->getName());
5505 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005506 Instruction *X =
5507 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5508 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005509 InsertNewInstBefore(X, I); // (X + (Y << C))
5510 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005511 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005512 return BinaryOperator::createAnd(X, C2);
5513 }
Chris Lattner14553932006-01-06 07:12:35 +00005514
Chris Lattner797dee72005-09-18 06:30:59 +00005515 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5516 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5517 match(Op0BO->getOperand(1),
5518 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005519 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005520 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005521 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005522 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005523 Op0BO->getName());
5524 InsertNewInstBefore(YS, I); // (Y << C)
5525 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005526 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005527 V1->getName()+".mask");
5528 InsertNewInstBefore(XM, I); // X & (CC << C)
5529
5530 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5531 }
Chris Lattner14553932006-01-06 07:12:35 +00005532
Chris Lattner797dee72005-09-18 06:30:59 +00005533 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005534 case Instruction::Sub:
5535 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005536 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5537 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005538 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005539 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005540 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005541 Op0BO->getName());
5542 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005543 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005544 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005545 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005546 InsertNewInstBefore(X, I); // (X + (Y << C))
5547 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005548 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005549 return BinaryOperator::createAnd(X, C2);
5550 }
Chris Lattner14553932006-01-06 07:12:35 +00005551
Chris Lattner1df0e982006-05-31 21:14:00 +00005552 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005553 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5554 match(Op0BO->getOperand(0),
5555 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005556 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005557 cast<BinaryOperator>(Op0BO->getOperand(0))
5558 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005559 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005560 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005561 Op0BO->getName());
5562 InsertNewInstBefore(YS, I); // (Y << C)
5563 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005564 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005565 V1->getName()+".mask");
5566 InsertNewInstBefore(XM, I); // X & (CC << C)
5567
Chris Lattner1df0e982006-05-31 21:14:00 +00005568 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005569 }
Chris Lattner14553932006-01-06 07:12:35 +00005570
Chris Lattner27cb9db2005-09-18 05:12:10 +00005571 break;
Chris Lattner14553932006-01-06 07:12:35 +00005572 }
5573
5574
5575 // If the operand is an bitwise operator with a constant RHS, and the
5576 // shift is the only use, we can pull it out of the shift.
5577 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5578 bool isValid = true; // Valid only for And, Or, Xor
5579 bool highBitSet = false; // Transform if high bit of constant set?
5580
5581 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005582 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005583 case Instruction::Add:
5584 isValid = isLeftShift;
5585 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005586 case Instruction::Or:
5587 case Instruction::Xor:
5588 highBitSet = false;
5589 break;
5590 case Instruction::And:
5591 highBitSet = true;
5592 break;
Chris Lattner14553932006-01-06 07:12:35 +00005593 }
5594
5595 // If this is a signed shift right, and the high bit is modified
5596 // by the logical operation, do not perform the transformation.
5597 // The highBitSet boolean indicates the value of the high bit of
5598 // the constant which would cause it to be modified for this
5599 // operation.
5600 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005601 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005602 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005603 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5604 }
5605
5606 if (isValid) {
5607 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5608
5609 Instruction *NewShift =
5610 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5611 Op0BO->getName());
5612 Op0BO->setName("");
5613 InsertNewInstBefore(NewShift, I);
5614
5615 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5616 NewRHS);
5617 }
5618 }
5619 }
5620 }
5621
Chris Lattnereb372a02006-01-06 07:52:12 +00005622 // Find out if this is a shift of a shift by a constant.
5623 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005624 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005625 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005626 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5627 // If this is a noop-integer cast of a shift instruction, use the shift.
5628 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005629 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5630 }
5631 }
5632
Reid Spencere0fc4df2006-10-20 07:07:24 +00005633 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005634 // Find the operands and properties of the input shift. Note that the
5635 // signedness of the input shift may differ from the current shift if there
5636 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005637 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5638 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005639 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005640
Reid Spencere0fc4df2006-10-20 07:07:24 +00005641 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005642
Reid Spencere0fc4df2006-10-20 07:07:24 +00005643 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5644 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005645
5646 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5647 if (isLeftShift == isShiftOfLeftShift) {
5648 // Do not fold these shifts if the first one is signed and the second one
5649 // is unsigned and this is a right shift. Further, don't do any folding
5650 // on them.
5651 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5652 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005653
Chris Lattnereb372a02006-01-06 07:52:12 +00005654 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5655 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5656 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005657
Chris Lattnereb372a02006-01-06 07:52:12 +00005658 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005659 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencer74a528b2006-12-13 18:21:21 +00005660 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005661 if (I.getType() == ShiftResult->getType())
5662 return ShiftResult;
5663 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005664 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005665 }
5666
5667 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5668 // signed types, we can only support the (A >> c1) << c2 configuration,
5669 // because it can not turn an arbitrary bit of A into a sign bit.
5670 if (isUnsignedShift || isLeftShift) {
5671 // Calculate bitmask for what gets shifted off the edge.
5672 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5673 if (isLeftShift)
5674 C = ConstantExpr::getShl(C, ShiftAmt1C);
5675 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005676 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005677
5678 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005679 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005680 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005681
5682 Instruction *Mask =
5683 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5684 InsertNewInstBefore(Mask, I);
5685
5686 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005687 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005688 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005689 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005690 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005691 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005692 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5693 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005694 return new ShiftInst(Instruction::LShr, Mask,
5695 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005696 } else {
5697 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005698 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005699 }
5700 } else {
5701 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005702 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005703 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005704 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005705 InsertNewInstBefore(Shift, I);
5706
5707 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5708 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005709 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005710 }
5711 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005712 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005713 // this case, C1 == C2 and C1 is 8, 16, or 32.
5714 if (ShiftAmt1 == ShiftAmt2) {
5715 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005716 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005717 case 8 : SExtType = Type::SByteTy; break;
5718 case 16: SExtType = Type::ShortTy; break;
5719 case 32: SExtType = Type::IntTy; break;
5720 }
5721
5722 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005723 Instruction *NewTrunc =
5724 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005725 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005726 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005727 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005728 }
Chris Lattner86102b82005-01-01 16:22:27 +00005729 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005730 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005731 return 0;
5732}
5733
Chris Lattner48a44f72002-05-02 17:06:02 +00005734
Chris Lattner8f663e82005-10-29 04:36:15 +00005735/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5736/// expression. If so, decompose it, returning some value X, such that Val is
5737/// X*Scale+Offset.
5738///
5739static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5740 unsigned &Offset) {
5741 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005742 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5743 if (CI->getType()->isUnsigned()) {
5744 Offset = CI->getZExtValue();
5745 Scale = 1;
5746 return ConstantInt::get(Type::UIntTy, 0);
5747 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005748 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5749 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005750 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5751 if (CUI->getType()->isUnsigned()) {
5752 if (I->getOpcode() == Instruction::Shl) {
5753 // This is a value scaled by '1 << the shift amt'.
5754 Scale = 1U << CUI->getZExtValue();
5755 Offset = 0;
5756 return I->getOperand(0);
5757 } else if (I->getOpcode() == Instruction::Mul) {
5758 // This value is scaled by 'CUI'.
5759 Scale = CUI->getZExtValue();
5760 Offset = 0;
5761 return I->getOperand(0);
5762 } else if (I->getOpcode() == Instruction::Add) {
5763 // We have X+C. Check to see if we really have (X*C2)+C1,
5764 // where C1 is divisible by C2.
5765 unsigned SubScale;
5766 Value *SubVal =
5767 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5768 Offset += CUI->getZExtValue();
5769 if (SubScale > 1 && (Offset % SubScale == 0)) {
5770 Scale = SubScale;
5771 return SubVal;
5772 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005773 }
5774 }
5775 }
5776 }
5777 }
5778
5779 // Otherwise, we can't look past this.
5780 Scale = 1;
5781 Offset = 0;
5782 return Val;
5783}
5784
5785
Chris Lattner216be912005-10-24 06:03:58 +00005786/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5787/// try to eliminate the cast by moving the type information into the alloc.
5788Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5789 AllocationInst &AI) {
5790 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005791 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005792
Chris Lattnerac87beb2005-10-24 06:22:12 +00005793 // Remove any uses of AI that are dead.
5794 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5795 std::vector<Instruction*> DeadUsers;
5796 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5797 Instruction *User = cast<Instruction>(*UI++);
5798 if (isInstructionTriviallyDead(User)) {
5799 while (UI != E && *UI == User)
5800 ++UI; // If this instruction uses AI more than once, don't break UI.
5801
5802 // Add operands to the worklist.
5803 AddUsesToWorkList(*User);
5804 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005805 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005806
5807 User->eraseFromParent();
5808 removeFromWorkList(User);
5809 }
5810 }
5811
Chris Lattner216be912005-10-24 06:03:58 +00005812 // Get the type really allocated and the type casted to.
5813 const Type *AllocElTy = AI.getAllocatedType();
5814 const Type *CastElTy = PTy->getElementType();
5815 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005816
Chris Lattner7d190672006-10-01 19:40:58 +00005817 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5818 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005819 if (CastElTyAlign < AllocElTyAlign) return 0;
5820
Chris Lattner46705b22005-10-24 06:35:18 +00005821 // If the allocation has multiple uses, only promote it if we are strictly
5822 // increasing the alignment of the resultant allocation. If we keep it the
5823 // same, we open the door to infinite loops of various kinds.
5824 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5825
Chris Lattner216be912005-10-24 06:03:58 +00005826 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5827 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005828 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005829
Chris Lattner8270c332005-10-29 03:19:53 +00005830 // See if we can satisfy the modulus by pulling a scale out of the array
5831 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005832 unsigned ArraySizeScale, ArrayOffset;
5833 Value *NumElements = // See if the array size is a decomposable linear expr.
5834 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5835
Chris Lattner8270c332005-10-29 03:19:53 +00005836 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5837 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005838 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5839 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005840
Chris Lattner8270c332005-10-29 03:19:53 +00005841 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5842 Value *Amt = 0;
5843 if (Scale == 1) {
5844 Amt = NumElements;
5845 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005846 // If the allocation size is constant, form a constant mul expression
5847 Amt = ConstantInt::get(Type::UIntTy, Scale);
5848 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5849 Amt = ConstantExpr::getMul(
5850 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5851 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005852 else if (Scale != 1) {
5853 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5854 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005855 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005856 }
5857
Chris Lattner8f663e82005-10-29 04:36:15 +00005858 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005859 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005860 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5861 Amt = InsertNewInstBefore(Tmp, AI);
5862 }
5863
Chris Lattner216be912005-10-24 06:03:58 +00005864 std::string Name = AI.getName(); AI.setName("");
5865 AllocationInst *New;
5866 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005867 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005868 else
Nate Begeman848622f2005-11-05 09:21:28 +00005869 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005870 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005871
5872 // If the allocation has multiple uses, insert a cast and change all things
5873 // that used it to use the new cast. This will also hack on CI, but it will
5874 // die soon.
5875 if (!AI.hasOneUse()) {
5876 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005877 // New is the allocation instruction, pointer typed. AI is the original
5878 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5879 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005880 InsertNewInstBefore(NewCast, AI);
5881 AI.replaceAllUsesWith(NewCast);
5882 }
Chris Lattner216be912005-10-24 06:03:58 +00005883 return ReplaceInstUsesWith(CI, New);
5884}
5885
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005886/// CanEvaluateInDifferentType - Return true if we can take the specified value
5887/// and return it without inserting any new casts. This is used by code that
5888/// tries to decide whether promoting or shrinking integer operations to wider
5889/// or smaller types will allow us to eliminate a truncate or extend.
5890static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5891 int &NumCastsRemoved) {
5892 if (isa<Constant>(V)) return true;
5893
5894 Instruction *I = dyn_cast<Instruction>(V);
5895 if (!I || !I->hasOneUse()) return false;
5896
5897 switch (I->getOpcode()) {
5898 case Instruction::And:
5899 case Instruction::Or:
5900 case Instruction::Xor:
5901 // These operators can all arbitrarily be extended or truncated.
5902 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5903 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005904 case Instruction::AShr:
5905 case Instruction::LShr:
5906 case Instruction::Shl:
5907 // If this is just a bitcast changing the sign of the operation, we can
5908 // convert if the operand can be converted.
5909 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5910 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5911 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005912 case Instruction::Trunc:
5913 case Instruction::ZExt:
5914 case Instruction::SExt:
5915 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005916 // If this is a cast from the destination type, we can trivially eliminate
5917 // it, and this will remove a cast overall.
5918 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005919 // If the first operand is itself a cast, and is eliminable, do not count
5920 // this as an eliminable cast. We would prefer to eliminate those two
5921 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005922 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005923 return true;
5924
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005925 ++NumCastsRemoved;
5926 return true;
5927 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005928 break;
5929 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005930 // TODO: Can handle more cases here.
5931 break;
5932 }
5933
5934 return false;
5935}
5936
5937/// EvaluateInDifferentType - Given an expression that
5938/// CanEvaluateInDifferentType returns true for, actually insert the code to
5939/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005940Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5941 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005942 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005943 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005944
5945 // Otherwise, it must be an instruction.
5946 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005947 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005948 switch (I->getOpcode()) {
5949 case Instruction::And:
5950 case Instruction::Or:
5951 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005952 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5953 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005954 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5955 LHS, RHS, I->getName());
5956 break;
5957 }
Chris Lattner960acb02006-11-29 07:18:39 +00005958 case Instruction::AShr:
5959 case Instruction::LShr:
5960 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005961 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005962 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5963 I->getOperand(1), I->getName());
5964 break;
5965 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005966 case Instruction::Trunc:
5967 case Instruction::ZExt:
5968 case Instruction::SExt:
5969 case Instruction::BitCast:
5970 // If the source type of the cast is the type we're trying for then we can
5971 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005972 if (I->getOperand(0)->getType() == Ty)
5973 return I->getOperand(0);
5974
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005975 // Some other kind of cast, which shouldn't happen, so just ..
5976 // FALL THROUGH
5977 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005978 // TODO: Can handle more cases here.
5979 assert(0 && "Unreachable!");
5980 break;
5981 }
5982
5983 return InsertNewInstBefore(Res, *I);
5984}
5985
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005986/// @brief Implement the transforms common to all CastInst visitors.
5987Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005988 Value *Src = CI.getOperand(0);
5989
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005990 // Casting undef to anything results in undef so might as just replace it and
5991 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005992 if (isa<UndefValue>(Src)) // cast undef -> undef
5993 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5994
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005995 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5996 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005997 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005998 if (Instruction::CastOps opc =
5999 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6000 // The first cast (CSrc) is eliminable so we need to fix up or replace
6001 // the second cast (CI). CSrc will then have a good chance of being dead.
6002 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00006003 }
6004 }
Chris Lattner03841652004-05-25 04:29:21 +00006005
Chris Lattnerd0d51602003-06-21 23:12:02 +00006006 // If casting the result of a getelementptr instruction with no offset, turn
6007 // this into a cast of the original pointer!
6008 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00006009 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00006010 bool AllZeroOperands = true;
6011 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6012 if (!isa<Constant>(GEP->getOperand(i)) ||
6013 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6014 AllZeroOperands = false;
6015 break;
6016 }
6017 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006018 // Changing the cast operand is usually not a good idea but it is safe
6019 // here because the pointer operand is being replaced with another
6020 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00006021 CI.setOperand(0, GEP->getOperand(0));
6022 return &CI;
6023 }
6024 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00006025
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006026 // If we are casting a malloc or alloca to a pointer to a type of the same
6027 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006028 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00006029 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6030 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006031
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006032 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00006033 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6034 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6035 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006036
6037 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006038 if (isa<PHINode>(Src))
6039 if (Instruction *NV = FoldOpIntoPhi(CI))
6040 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006041
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006042 return 0;
6043}
6044
6045/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6046/// integers. This function implements the common transforms for all those
6047/// cases.
6048/// @brief Implement the transforms common to CastInst with integer operands
6049Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6050 if (Instruction *Result = commonCastTransforms(CI))
6051 return Result;
6052
6053 Value *Src = CI.getOperand(0);
6054 const Type *SrcTy = Src->getType();
6055 const Type *DestTy = CI.getType();
6056 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6057 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6058
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006059 // See if we can simplify any instructions used by the LHS whose sole
6060 // purpose is to compute bits we don't care about.
6061 uint64_t KnownZero = 0, KnownOne = 0;
6062 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6063 KnownZero, KnownOne))
6064 return &CI;
6065
6066 // If the source isn't an instruction or has more than one use then we
6067 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006068 Instruction *SrcI = dyn_cast<Instruction>(Src);
6069 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006070 return 0;
6071
6072 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006073 int NumCastsRemoved = 0;
6074 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6075 // If this cast is a truncate, evaluting in a different type always
6076 // eliminates the cast, so it is always a win. If this is a noop-cast
6077 // this just removes a noop cast which isn't pointful, but simplifies
6078 // the code. If this is a zero-extension, we need to do an AND to
6079 // maintain the clear top-part of the computation, so we require that
6080 // the input have eliminated at least one cast. If this is a sign
6081 // extension, we insert two new casts (to do the extension) so we
6082 // require that two casts have been eliminated.
6083 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6084 if (!DoXForm) {
6085 switch (CI.getOpcode()) {
6086 case Instruction::Trunc:
6087 DoXForm = true;
6088 break;
6089 case Instruction::ZExt:
6090 DoXForm = NumCastsRemoved >= 1;
6091 break;
6092 case Instruction::SExt:
6093 DoXForm = NumCastsRemoved >= 2;
6094 break;
6095 case Instruction::BitCast:
6096 DoXForm = false;
6097 break;
6098 default:
6099 // All the others use floating point so we shouldn't actually
6100 // get here because of the check above.
6101 assert(!"Unknown cast type .. unreachable");
6102 break;
6103 }
6104 }
6105
6106 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006107 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6108 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006109 assert(Res->getType() == DestTy);
6110 switch (CI.getOpcode()) {
6111 default: assert(0 && "Unknown cast type!");
6112 case Instruction::Trunc:
6113 case Instruction::BitCast:
6114 // Just replace this cast with the result.
6115 return ReplaceInstUsesWith(CI, Res);
6116 case Instruction::ZExt: {
6117 // We need to emit an AND to clear the high bits.
6118 assert(SrcBitSize < DestBitSize && "Not a zext?");
6119 Constant *C =
6120 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
6121 if (DestBitSize < 64)
6122 C = ConstantExpr::getTrunc(C, DestTy);
6123 else {
6124 assert(DestBitSize == 64);
6125 C = ConstantExpr::getBitCast(C, DestTy);
6126 }
6127 return BinaryOperator::createAnd(Res, C);
6128 }
6129 case Instruction::SExt:
6130 // We need to emit a cast to truncate, then a cast to sext.
6131 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006132 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6133 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006134 }
6135 }
6136 }
6137
6138 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6139 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6140
6141 switch (SrcI->getOpcode()) {
6142 case Instruction::Add:
6143 case Instruction::Mul:
6144 case Instruction::And:
6145 case Instruction::Or:
6146 case Instruction::Xor:
6147 // If we are discarding information, or just changing the sign,
6148 // rewrite.
6149 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6150 // Don't insert two casts if they cannot be eliminated. We allow
6151 // two casts to be inserted if the sizes are the same. This could
6152 // only be converting signedness, which is a noop.
6153 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006154 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6155 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006156 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006157 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6158 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6159 return BinaryOperator::create(
6160 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006161 }
6162 }
6163
6164 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6165 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6166 SrcI->getOpcode() == Instruction::Xor &&
6167 Op1 == ConstantBool::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006168 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006169 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006170 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6171 }
6172 break;
6173 case Instruction::SDiv:
6174 case Instruction::UDiv:
6175 case Instruction::SRem:
6176 case Instruction::URem:
6177 // If we are just changing the sign, rewrite.
6178 if (DestBitSize == SrcBitSize) {
6179 // Don't insert two casts if they cannot be eliminated. We allow
6180 // two casts to be inserted if the sizes are the same. This could
6181 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006182 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6183 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006184 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6185 Op0, DestTy, SrcI);
6186 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6187 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006188 return BinaryOperator::create(
6189 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6190 }
6191 }
6192 break;
6193
6194 case Instruction::Shl:
6195 // Allow changing the sign of the source operand. Do not allow
6196 // changing the size of the shift, UNLESS the shift amount is a
6197 // constant. We must not change variable sized shifts to a smaller
6198 // size, because it is undefined to shift more bits out than exist
6199 // in the value.
6200 if (DestBitSize == SrcBitSize ||
6201 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006202 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6203 Instruction::BitCast : Instruction::Trunc);
6204 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006205 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6206 }
6207 break;
6208 case Instruction::AShr:
6209 // If this is a signed shr, and if all bits shifted in are about to be
6210 // truncated off, turn it into an unsigned shr to allow greater
6211 // simplifications.
6212 if (DestBitSize < SrcBitSize &&
6213 isa<ConstantInt>(Op1)) {
6214 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6215 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6216 // Insert the new logical shift right.
6217 return new ShiftInst(Instruction::LShr, Op0, Op1);
6218 }
6219 }
6220 break;
6221
Reid Spencer266e42b2006-12-23 06:05:41 +00006222 case Instruction::ICmp:
6223 // If we are just checking for a icmp eq of a single bit and casting it
6224 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006225 // cast to integer to avoid the comparison.
6226 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6227 uint64_t Op1CV = Op1C->getZExtValue();
6228 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6229 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6230 // cast (X == 1) to int --> X iff X has only the low bit set.
6231 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6232 // cast (X != 0) to int --> X iff X has only the low bit set.
6233 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6234 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6235 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6236 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6237 // If Op1C some other power of two, convert:
6238 uint64_t KnownZero, KnownOne;
6239 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6240 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006241
6242 // This only works for EQ and NE
6243 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6244 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6245 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006246
6247 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006248 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006249 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6250 // (X&4) == 2 --> false
6251 // (X&4) != 2 --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006252 Constant *Res = ConstantBool::get(isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006253 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006254 return ReplaceInstUsesWith(CI, Res);
6255 }
6256
6257 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6258 Value *In = Op0;
6259 if (ShiftAmt) {
6260 // Perform a logical shr by shiftamt.
6261 // Insert the shift to put the result in the low bit.
6262 In = InsertNewInstBefore(
6263 new ShiftInst(Instruction::LShr, In,
6264 ConstantInt::get(Type::UByteTy, ShiftAmt),
6265 In->getName()+".lobit"), CI);
6266 }
6267
Reid Spencer266e42b2006-12-23 06:05:41 +00006268 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006269 Constant *One = ConstantInt::get(In->getType(), 1);
6270 In = BinaryOperator::createXor(In, One, "tmp");
6271 InsertNewInstBefore(cast<Instruction>(In), CI);
6272 }
6273
6274 if (CI.getType() == In->getType())
6275 return ReplaceInstUsesWith(CI, In);
6276 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006277 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006278 }
6279 }
6280 }
6281 break;
6282 }
6283 return 0;
6284}
6285
6286Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006287 if (Instruction *Result = commonIntCastTransforms(CI))
6288 return Result;
6289
6290 Value *Src = CI.getOperand(0);
6291 const Type *Ty = CI.getType();
6292 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6293
6294 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6295 switch (SrcI->getOpcode()) {
6296 default: break;
6297 case Instruction::LShr:
6298 // We can shrink lshr to something smaller if we know the bits shifted in
6299 // are already zeros.
6300 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6301 unsigned ShAmt = ShAmtV->getZExtValue();
6302
6303 // Get a mask for the bits shifting in.
6304 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006305 Value* SrcIOp0 = SrcI->getOperand(0);
6306 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006307 if (ShAmt >= DestBitWidth) // All zeros.
6308 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6309
6310 // Okay, we can shrink this. Truncate the input, then return a new
6311 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006312 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006313 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6314 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006315 } else { // This is a variable shr.
6316
6317 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6318 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6319 // loop-invariant and CSE'd.
6320 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6321 Value *One = ConstantInt::get(SrcI->getType(), 1);
6322
6323 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6324 SrcI->getOperand(1),
6325 "tmp"), CI);
6326 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6327 SrcI->getOperand(0),
6328 "tmp"), CI);
6329 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006330 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006331 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006332 }
6333 break;
6334 }
6335 }
6336
6337 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006338}
6339
6340Instruction *InstCombiner::visitZExt(CastInst &CI) {
6341 // If one of the common conversion will work ..
6342 if (Instruction *Result = commonIntCastTransforms(CI))
6343 return Result;
6344
6345 Value *Src = CI.getOperand(0);
6346
6347 // If this is a cast of a cast
6348 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006349 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6350 // types and if the sizes are just right we can convert this into a logical
6351 // 'and' which will be much cheaper than the pair of casts.
6352 if (isa<TruncInst>(CSrc)) {
6353 // Get the sizes of the types involved
6354 Value *A = CSrc->getOperand(0);
6355 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6356 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6357 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6358 // If we're actually extending zero bits and the trunc is a no-op
6359 if (MidSize < DstSize && SrcSize == DstSize) {
6360 // Replace both of the casts with an And of the type mask.
6361 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6362 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6363 Instruction *And =
6364 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6365 // Unfortunately, if the type changed, we need to cast it back.
6366 if (And->getType() != CI.getType()) {
6367 And->setName(CSrc->getName()+".mask");
6368 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006369 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006370 }
6371 return And;
6372 }
6373 }
6374 }
6375
6376 return 0;
6377}
6378
6379Instruction *InstCombiner::visitSExt(CastInst &CI) {
6380 return commonIntCastTransforms(CI);
6381}
6382
6383Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6384 return commonCastTransforms(CI);
6385}
6386
6387Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6388 return commonCastTransforms(CI);
6389}
6390
6391Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006392 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006393}
6394
6395Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006396 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006397}
6398
6399Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6400 return commonCastTransforms(CI);
6401}
6402
6403Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6404 return commonCastTransforms(CI);
6405}
6406
6407Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006408 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006409}
6410
6411Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6412 return commonCastTransforms(CI);
6413}
6414
6415Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6416
6417 // If the operands are integer typed then apply the integer transforms,
6418 // otherwise just apply the common ones.
6419 Value *Src = CI.getOperand(0);
6420 const Type *SrcTy = Src->getType();
6421 const Type *DestTy = CI.getType();
6422
6423 if (SrcTy->isInteger() && DestTy->isInteger()) {
6424 if (Instruction *Result = commonIntCastTransforms(CI))
6425 return Result;
6426 } else {
6427 if (Instruction *Result = commonCastTransforms(CI))
6428 return Result;
6429 }
6430
6431
6432 // Get rid of casts from one type to the same type. These are useless and can
6433 // be replaced by the operand.
6434 if (DestTy == Src->getType())
6435 return ReplaceInstUsesWith(CI, Src);
6436
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006437 // If the source and destination are pointers, and this cast is equivalent to
6438 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6439 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006440 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6441 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6442 const Type *DstElTy = DstPTy->getElementType();
6443 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006444
6445 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6446 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006447 while (SrcElTy != DstElTy &&
6448 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6449 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6450 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006451 ++NumZeros;
6452 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006453
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006454 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006455 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006456 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6457 return new GetElementPtrInst(Src, Idxs);
6458 }
6459 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006460 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006461
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006462 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6463 if (SVI->hasOneUse()) {
6464 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6465 // a bitconvert to a vector with the same # elts.
6466 if (isa<PackedType>(DestTy) &&
6467 cast<PackedType>(DestTy)->getNumElements() ==
6468 SVI->getType()->getNumElements()) {
6469 CastInst *Tmp;
6470 // If either of the operands is a cast from CI.getType(), then
6471 // evaluating the shuffle in the casted destination's type will allow
6472 // us to eliminate at least one cast.
6473 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6474 Tmp->getOperand(0)->getType() == DestTy) ||
6475 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6476 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006477 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6478 SVI->getOperand(0), DestTy, &CI);
6479 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6480 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006481 // Return a new shuffle vector. Use the same element ID's, as we
6482 // know the vector types match #elts.
6483 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006484 }
6485 }
6486 }
6487 }
Chris Lattner260ab202002-04-18 17:39:14 +00006488 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006489}
6490
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006491/// GetSelectFoldableOperands - We want to turn code that looks like this:
6492/// %C = or %A, %B
6493/// %D = select %cond, %C, %A
6494/// into:
6495/// %C = select %cond, %B, 0
6496/// %D = or %A, %C
6497///
6498/// Assuming that the specified instruction is an operand to the select, return
6499/// a bitmask indicating which operands of this instruction are foldable if they
6500/// equal the other incoming value of the select.
6501///
6502static unsigned GetSelectFoldableOperands(Instruction *I) {
6503 switch (I->getOpcode()) {
6504 case Instruction::Add:
6505 case Instruction::Mul:
6506 case Instruction::And:
6507 case Instruction::Or:
6508 case Instruction::Xor:
6509 return 3; // Can fold through either operand.
6510 case Instruction::Sub: // Can only fold on the amount subtracted.
6511 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006512 case Instruction::LShr:
6513 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006514 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006515 default:
6516 return 0; // Cannot fold
6517 }
6518}
6519
6520/// GetSelectFoldableConstant - For the same transformation as the previous
6521/// function, return the identity constant that goes into the select.
6522static Constant *GetSelectFoldableConstant(Instruction *I) {
6523 switch (I->getOpcode()) {
6524 default: assert(0 && "This cannot happen!"); abort();
6525 case Instruction::Add:
6526 case Instruction::Sub:
6527 case Instruction::Or:
6528 case Instruction::Xor:
6529 return Constant::getNullValue(I->getType());
6530 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006531 case Instruction::LShr:
6532 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006533 return Constant::getNullValue(Type::UByteTy);
6534 case Instruction::And:
6535 return ConstantInt::getAllOnesValue(I->getType());
6536 case Instruction::Mul:
6537 return ConstantInt::get(I->getType(), 1);
6538 }
6539}
6540
Chris Lattner411336f2005-01-19 21:50:18 +00006541/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6542/// have the same opcode and only one use each. Try to simplify this.
6543Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6544 Instruction *FI) {
6545 if (TI->getNumOperands() == 1) {
6546 // If this is a non-volatile load or a cast from the same type,
6547 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006548 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006549 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6550 return 0;
6551 } else {
6552 return 0; // unknown unary op.
6553 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006554
Chris Lattner411336f2005-01-19 21:50:18 +00006555 // Fold this by inserting a select from the input values.
6556 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6557 FI->getOperand(0), SI.getName()+".v");
6558 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006559 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6560 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006561 }
6562
Reid Spencer266e42b2006-12-23 06:05:41 +00006563 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006564 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006565 return 0;
6566
6567 // Figure out if the operations have any operands in common.
6568 Value *MatchOp, *OtherOpT, *OtherOpF;
6569 bool MatchIsOpZero;
6570 if (TI->getOperand(0) == FI->getOperand(0)) {
6571 MatchOp = TI->getOperand(0);
6572 OtherOpT = TI->getOperand(1);
6573 OtherOpF = FI->getOperand(1);
6574 MatchIsOpZero = true;
6575 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6576 MatchOp = TI->getOperand(1);
6577 OtherOpT = TI->getOperand(0);
6578 OtherOpF = FI->getOperand(0);
6579 MatchIsOpZero = false;
6580 } else if (!TI->isCommutative()) {
6581 return 0;
6582 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6583 MatchOp = TI->getOperand(0);
6584 OtherOpT = TI->getOperand(1);
6585 OtherOpF = FI->getOperand(0);
6586 MatchIsOpZero = true;
6587 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6588 MatchOp = TI->getOperand(1);
6589 OtherOpT = TI->getOperand(0);
6590 OtherOpF = FI->getOperand(1);
6591 MatchIsOpZero = true;
6592 } else {
6593 return 0;
6594 }
6595
6596 // If we reach here, they do have operations in common.
6597 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6598 OtherOpF, SI.getName()+".v");
6599 InsertNewInstBefore(NewSI, SI);
6600
6601 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6602 if (MatchIsOpZero)
6603 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6604 else
6605 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006606 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006607
6608 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6609 if (MatchIsOpZero)
6610 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6611 else
6612 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006613}
6614
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006615Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006616 Value *CondVal = SI.getCondition();
6617 Value *TrueVal = SI.getTrueValue();
6618 Value *FalseVal = SI.getFalseValue();
6619
6620 // select true, X, Y -> X
6621 // select false, X, Y -> Y
6622 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006623 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006624
6625 // select C, X, X -> X
6626 if (TrueVal == FalseVal)
6627 return ReplaceInstUsesWith(SI, TrueVal);
6628
Chris Lattner81a7a232004-10-16 18:11:37 +00006629 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6630 return ReplaceInstUsesWith(SI, FalseVal);
6631 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6632 return ReplaceInstUsesWith(SI, TrueVal);
6633 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6634 if (isa<Constant>(TrueVal))
6635 return ReplaceInstUsesWith(SI, TrueVal);
6636 else
6637 return ReplaceInstUsesWith(SI, FalseVal);
6638 }
6639
Chris Lattner1c631e82004-04-08 04:43:23 +00006640 if (SI.getType() == Type::BoolTy)
6641 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006642 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006643 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006644 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006645 } else {
6646 // Change: A = select B, false, C --> A = and !B, C
6647 Value *NotCond =
6648 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6649 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006650 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006651 }
6652 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006653 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006654 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006655 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006656 } else {
6657 // Change: A = select B, C, true --> A = or !B, C
6658 Value *NotCond =
6659 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6660 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006661 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006662 }
6663 }
6664
Chris Lattner183b3362004-04-09 19:05:30 +00006665 // Selecting between two integer constants?
6666 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6667 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6668 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006669 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006670 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006671 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006672 // select C, 0, 1 -> cast !C to int
6673 Value *NotCond =
6674 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006675 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006676 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006677 }
Chris Lattner35167c32004-06-09 07:59:58 +00006678
Reid Spencer266e42b2006-12-23 06:05:41 +00006679 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006680
Reid Spencer266e42b2006-12-23 06:05:41 +00006681 // (x <s 0) ? -1 : 0 -> ashr x, 31
6682 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006683 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6684 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6685 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006686 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006687 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006688 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006689 else {
6690 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006691 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006692 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006693 }
6694
6695 if (CanXForm) {
6696 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006697 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006698 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006699 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006700 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006701 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006702 ShAmt, "ones");
6703 InsertNewInstBefore(SRA, SI);
6704
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006705 // Finally, convert to the type of the select RHS. We figure out
6706 // if this requires a SExt, Trunc or BitCast based on the sizes.
6707 Instruction::CastOps opc = Instruction::BitCast;
6708 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6709 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6710 if (SRASize < SISize)
6711 opc = Instruction::SExt;
6712 else if (SRASize > SISize)
6713 opc = Instruction::Trunc;
6714 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006715 }
6716 }
6717
6718
6719 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006720 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006721 // non-constant value, eliminate this whole mess. This corresponds to
6722 // cases like this: ((X & 27) ? 27 : 0)
6723 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006724 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006725 cast<Constant>(IC->getOperand(1))->isNullValue())
6726 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6727 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006728 isa<ConstantInt>(ICA->getOperand(1)) &&
6729 (ICA->getOperand(1) == TrueValC ||
6730 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006731 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6732 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006733 // know whether we have a icmp_ne or icmp_eq and whether the
6734 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006735 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006736 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006737 Value *V = ICA;
6738 if (ShouldNotVal)
6739 V = InsertNewInstBefore(BinaryOperator::create(
6740 Instruction::Xor, V, ICA->getOperand(1)), SI);
6741 return ReplaceInstUsesWith(SI, V);
6742 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006743 }
Chris Lattner533bc492004-03-30 19:37:13 +00006744 }
Chris Lattner623fba12004-04-10 22:21:27 +00006745
6746 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006747 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6748 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006749 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006750 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006751 return ReplaceInstUsesWith(SI, FalseVal);
6752 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006753 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006754 return ReplaceInstUsesWith(SI, TrueVal);
6755 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6756
Reid Spencer266e42b2006-12-23 06:05:41 +00006757 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006758 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006759 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006760 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006761 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006762 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6763 return ReplaceInstUsesWith(SI, TrueVal);
6764 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6765 }
6766 }
6767
6768 // See if we are selecting two values based on a comparison of the two values.
6769 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6770 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6771 // Transform (X == Y) ? X : Y -> Y
6772 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6773 return ReplaceInstUsesWith(SI, FalseVal);
6774 // Transform (X != Y) ? X : Y -> X
6775 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6776 return ReplaceInstUsesWith(SI, TrueVal);
6777 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6778
6779 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6780 // Transform (X == Y) ? Y : X -> X
6781 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6782 return ReplaceInstUsesWith(SI, FalseVal);
6783 // Transform (X != Y) ? Y : X -> Y
6784 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006785 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006786 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6787 }
6788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006789
Chris Lattnera04c9042005-01-13 22:52:24 +00006790 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6791 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6792 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006793 Instruction *AddOp = 0, *SubOp = 0;
6794
Chris Lattner411336f2005-01-19 21:50:18 +00006795 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6796 if (TI->getOpcode() == FI->getOpcode())
6797 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6798 return IV;
6799
6800 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6801 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006802 if (TI->getOpcode() == Instruction::Sub &&
6803 FI->getOpcode() == Instruction::Add) {
6804 AddOp = FI; SubOp = TI;
6805 } else if (FI->getOpcode() == Instruction::Sub &&
6806 TI->getOpcode() == Instruction::Add) {
6807 AddOp = TI; SubOp = FI;
6808 }
6809
6810 if (AddOp) {
6811 Value *OtherAddOp = 0;
6812 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6813 OtherAddOp = AddOp->getOperand(1);
6814 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6815 OtherAddOp = AddOp->getOperand(0);
6816 }
6817
6818 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006819 // So at this point we know we have (Y -> OtherAddOp):
6820 // select C, (add X, Y), (sub X, Z)
6821 Value *NegVal; // Compute -Z
6822 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6823 NegVal = ConstantExpr::getNeg(C);
6824 } else {
6825 NegVal = InsertNewInstBefore(
6826 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006827 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006828
6829 Value *NewTrueOp = OtherAddOp;
6830 Value *NewFalseOp = NegVal;
6831 if (AddOp != TI)
6832 std::swap(NewTrueOp, NewFalseOp);
6833 Instruction *NewSel =
6834 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6835
6836 NewSel = InsertNewInstBefore(NewSel, SI);
6837 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006838 }
6839 }
6840 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006841
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006842 // See if we can fold the select into one of our operands.
6843 if (SI.getType()->isInteger()) {
6844 // See the comment above GetSelectFoldableOperands for a description of the
6845 // transformation we are doing here.
6846 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6847 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6848 !isa<Constant>(FalseVal))
6849 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6850 unsigned OpToFold = 0;
6851 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6852 OpToFold = 1;
6853 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6854 OpToFold = 2;
6855 }
6856
6857 if (OpToFold) {
6858 Constant *C = GetSelectFoldableConstant(TVI);
6859 std::string Name = TVI->getName(); TVI->setName("");
6860 Instruction *NewSel =
6861 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6862 Name);
6863 InsertNewInstBefore(NewSel, SI);
6864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6865 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6866 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6867 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6868 else {
6869 assert(0 && "Unknown instruction!!");
6870 }
6871 }
6872 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006873
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006874 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6875 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6876 !isa<Constant>(TrueVal))
6877 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6878 unsigned OpToFold = 0;
6879 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6880 OpToFold = 1;
6881 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6882 OpToFold = 2;
6883 }
6884
6885 if (OpToFold) {
6886 Constant *C = GetSelectFoldableConstant(FVI);
6887 std::string Name = FVI->getName(); FVI->setName("");
6888 Instruction *NewSel =
6889 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6890 Name);
6891 InsertNewInstBefore(NewSel, SI);
6892 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6893 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6894 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6895 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6896 else {
6897 assert(0 && "Unknown instruction!!");
6898 }
6899 }
6900 }
6901 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006902
6903 if (BinaryOperator::isNot(CondVal)) {
6904 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6905 SI.setOperand(1, FalseVal);
6906 SI.setOperand(2, TrueVal);
6907 return &SI;
6908 }
6909
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006910 return 0;
6911}
6912
Chris Lattner82f2ef22006-03-06 20:18:44 +00006913/// GetKnownAlignment - If the specified pointer has an alignment that we can
6914/// determine, return it, otherwise return 0.
6915static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6916 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6917 unsigned Align = GV->getAlignment();
6918 if (Align == 0 && TD)
6919 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6920 return Align;
6921 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6922 unsigned Align = AI->getAlignment();
6923 if (Align == 0 && TD) {
6924 if (isa<AllocaInst>(AI))
6925 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6926 else if (isa<MallocInst>(AI)) {
6927 // Malloc returns maximally aligned memory.
6928 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6929 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6930 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6931 }
6932 }
6933 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006934 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006935 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006936 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006937 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006938 if (isa<PointerType>(CI->getOperand(0)->getType()))
6939 return GetKnownAlignment(CI->getOperand(0), TD);
6940 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006941 } else if (isa<GetElementPtrInst>(V) ||
6942 (isa<ConstantExpr>(V) &&
6943 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6944 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006945 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6946 if (BaseAlignment == 0) return 0;
6947
6948 // If all indexes are zero, it is just the alignment of the base pointer.
6949 bool AllZeroOperands = true;
6950 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6951 if (!isa<Constant>(GEPI->getOperand(i)) ||
6952 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6953 AllZeroOperands = false;
6954 break;
6955 }
6956 if (AllZeroOperands)
6957 return BaseAlignment;
6958
6959 // Otherwise, if the base alignment is >= the alignment we expect for the
6960 // base pointer type, then we know that the resultant pointer is aligned at
6961 // least as much as its type requires.
6962 if (!TD) return 0;
6963
6964 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6965 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006966 <= BaseAlignment) {
6967 const Type *GEPTy = GEPI->getType();
6968 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6969 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006970 return 0;
6971 }
6972 return 0;
6973}
6974
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006975
Chris Lattnerc66b2232006-01-13 20:11:04 +00006976/// visitCallInst - CallInst simplification. This mostly only handles folding
6977/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6978/// the heavy lifting.
6979///
Chris Lattner970c33a2003-06-19 17:00:31 +00006980Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006981 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6982 if (!II) return visitCallSite(&CI);
6983
Chris Lattner51ea1272004-02-28 05:22:00 +00006984 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6985 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006986 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006987 bool Changed = false;
6988
6989 // memmove/cpy/set of zero bytes is a noop.
6990 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6991 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6992
Chris Lattner00648e12004-10-12 04:52:52 +00006993 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006994 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006995 // Replace the instruction with just byte operations. We would
6996 // transform other cases to loads/stores, but we don't know if
6997 // alignment is sufficient.
6998 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006999 }
7000
Chris Lattner00648e12004-10-12 04:52:52 +00007001 // If we have a memmove and the source operation is a constant global,
7002 // then the source and dest pointers can't alias, so we can change this
7003 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00007004 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00007005 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7006 if (GVSrc->isConstant()) {
7007 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00007008 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00007009 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00007010 Type::UIntTy)
7011 Name = "llvm.memcpy.i32";
7012 else
7013 Name = "llvm.memcpy.i64";
7014 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00007015 CI.getCalledFunction()->getFunctionType());
7016 CI.setOperand(0, MemCpy);
7017 Changed = true;
7018 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00007019 }
Chris Lattner00648e12004-10-12 04:52:52 +00007020
Chris Lattner82f2ef22006-03-06 20:18:44 +00007021 // If we can determine a pointer alignment that is bigger than currently
7022 // set, update the alignment.
7023 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7024 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7025 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7026 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007027 if (MI->getAlignment()->getZExtValue() < Align) {
7028 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007029 Changed = true;
7030 }
7031 } else if (isa<MemSetInst>(MI)) {
7032 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00007033 if (MI->getAlignment()->getZExtValue() < Alignment) {
7034 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00007035 Changed = true;
7036 }
7037 }
7038
Chris Lattnerc66b2232006-01-13 20:11:04 +00007039 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00007040 } else {
7041 switch (II->getIntrinsicID()) {
7042 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007043 case Intrinsic::ppc_altivec_lvx:
7044 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00007045 case Intrinsic::x86_sse_loadu_ps:
7046 case Intrinsic::x86_sse2_loadu_pd:
7047 case Intrinsic::x86_sse2_loadu_dq:
7048 // Turn PPC lvx -> load if the pointer is known aligned.
7049 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007050 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007051 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007052 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007053 return new LoadInst(Ptr);
7054 }
7055 break;
7056 case Intrinsic::ppc_altivec_stvx:
7057 case Intrinsic::ppc_altivec_stvxl:
7058 // Turn stvx -> store if the pointer is known aligned.
7059 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007060 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007061 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7062 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007063 return new StoreInst(II->getOperand(1), Ptr);
7064 }
7065 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007066 case Intrinsic::x86_sse_storeu_ps:
7067 case Intrinsic::x86_sse2_storeu_pd:
7068 case Intrinsic::x86_sse2_storeu_dq:
7069 case Intrinsic::x86_sse2_storel_dq:
7070 // Turn X86 storeu -> store if the pointer is known aligned.
7071 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7072 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007073 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7074 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007075 return new StoreInst(II->getOperand(2), Ptr);
7076 }
7077 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007078
7079 case Intrinsic::x86_sse_cvttss2si: {
7080 // These intrinsics only demands the 0th element of its input vector. If
7081 // we can simplify the input based on that, do so now.
7082 uint64_t UndefElts;
7083 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7084 UndefElts)) {
7085 II->setOperand(1, V);
7086 return II;
7087 }
7088 break;
7089 }
7090
Chris Lattnere79d2492006-04-06 19:19:17 +00007091 case Intrinsic::ppc_altivec_vperm:
7092 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7093 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7094 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7095
7096 // Check that all of the elements are integer constants or undefs.
7097 bool AllEltsOk = true;
7098 for (unsigned i = 0; i != 16; ++i) {
7099 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7100 !isa<UndefValue>(Mask->getOperand(i))) {
7101 AllEltsOk = false;
7102 break;
7103 }
7104 }
7105
7106 if (AllEltsOk) {
7107 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007108 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7109 II->getOperand(1), Mask->getType(), CI);
7110 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7111 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007112 Value *Result = UndefValue::get(Op0->getType());
7113
7114 // Only extract each element once.
7115 Value *ExtractedElts[32];
7116 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7117
7118 for (unsigned i = 0; i != 16; ++i) {
7119 if (isa<UndefValue>(Mask->getOperand(i)))
7120 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007121 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007122 Idx &= 31; // Match the hardware behavior.
7123
7124 if (ExtractedElts[Idx] == 0) {
7125 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007126 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007127 InsertNewInstBefore(Elt, CI);
7128 ExtractedElts[Idx] = Elt;
7129 }
7130
7131 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007132 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007133 InsertNewInstBefore(cast<Instruction>(Result), CI);
7134 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007135 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007136 }
7137 }
7138 break;
7139
Chris Lattner503221f2006-01-13 21:28:09 +00007140 case Intrinsic::stackrestore: {
7141 // If the save is right next to the restore, remove the restore. This can
7142 // happen when variable allocas are DCE'd.
7143 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7144 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7145 BasicBlock::iterator BI = SS;
7146 if (&*++BI == II)
7147 return EraseInstFromFunction(CI);
7148 }
7149 }
7150
7151 // If the stack restore is in a return/unwind block and if there are no
7152 // allocas or calls between the restore and the return, nuke the restore.
7153 TerminatorInst *TI = II->getParent()->getTerminator();
7154 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7155 BasicBlock::iterator BI = II;
7156 bool CannotRemove = false;
7157 for (++BI; &*BI != TI; ++BI) {
7158 if (isa<AllocaInst>(BI) ||
7159 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7160 CannotRemove = true;
7161 break;
7162 }
7163 }
7164 if (!CannotRemove)
7165 return EraseInstFromFunction(CI);
7166 }
7167 break;
7168 }
7169 }
Chris Lattner00648e12004-10-12 04:52:52 +00007170 }
7171
Chris Lattnerc66b2232006-01-13 20:11:04 +00007172 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007173}
7174
7175// InvokeInst simplification
7176//
7177Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007178 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007179}
7180
Chris Lattneraec3d942003-10-07 22:32:43 +00007181// visitCallSite - Improvements for call and invoke instructions.
7182//
7183Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007184 bool Changed = false;
7185
7186 // If the callee is a constexpr cast of a function, attempt to move the cast
7187 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007188 if (transformConstExprCastCall(CS)) return 0;
7189
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007190 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007191
Chris Lattner61d9d812005-05-13 07:09:09 +00007192 if (Function *CalleeF = dyn_cast<Function>(Callee))
7193 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7194 Instruction *OldCall = CS.getInstruction();
7195 // If the call and callee calling conventions don't match, this call must
7196 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007197 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00007198 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7199 if (!OldCall->use_empty())
7200 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7201 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7202 return EraseInstFromFunction(*OldCall);
7203 return 0;
7204 }
7205
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007206 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7207 // This instruction is not reachable, just remove it. We insert a store to
7208 // undef so that we know that this code is not reachable, despite the fact
7209 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007210 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007211 UndefValue::get(PointerType::get(Type::BoolTy)),
7212 CS.getInstruction());
7213
7214 if (!CS.getInstruction()->use_empty())
7215 CS.getInstruction()->
7216 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7217
7218 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7219 // Don't break the CFG, insert a dummy cond branch.
7220 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00007221 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007222 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007223 return EraseInstFromFunction(*CS.getInstruction());
7224 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007225
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007226 const PointerType *PTy = cast<PointerType>(Callee->getType());
7227 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7228 if (FTy->isVarArg()) {
7229 // See if we can optimize any arguments passed through the varargs area of
7230 // the call.
7231 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7232 E = CS.arg_end(); I != E; ++I)
7233 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7234 // If this cast does not effect the value passed through the varargs
7235 // area, we can eliminate the use of the cast.
7236 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007237 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007238 *I = Op;
7239 Changed = true;
7240 }
7241 }
7242 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007243
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007244 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007245}
7246
Chris Lattner970c33a2003-06-19 17:00:31 +00007247// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7248// attempt to move the cast to the arguments of the call/invoke.
7249//
7250bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7251 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7252 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007253 if (CE->getOpcode() != Instruction::BitCast ||
7254 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007255 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007256 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007257 Instruction *Caller = CS.getInstruction();
7258
7259 // Okay, this is a cast from a function to a different type. Unless doing so
7260 // would cause a type conversion of one of our arguments, change this call to
7261 // be a direct call with arguments casted to the appropriate types.
7262 //
7263 const FunctionType *FT = Callee->getFunctionType();
7264 const Type *OldRetTy = Caller->getType();
7265
Chris Lattner1f7942f2004-01-14 06:06:08 +00007266 // Check to see if we are changing the return type...
7267 if (OldRetTy != FT->getReturnType()) {
7268 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007269 !Caller->use_empty() &&
7270 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00007271 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007272 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7273 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00007274 return false; // Cannot transform this return value...
7275
7276 // If the callsite is an invoke instruction, and the return value is used by
7277 // a PHI node in a successor, we cannot change the return type of the call
7278 // because there is no place to put the cast instruction (without breaking
7279 // the critical edge). Bail out in this case.
7280 if (!Caller->use_empty())
7281 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7282 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7283 UI != E; ++UI)
7284 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7285 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007286 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007287 return false;
7288 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007289
7290 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7291 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007292
Chris Lattner970c33a2003-06-19 17:00:31 +00007293 CallSite::arg_iterator AI = CS.arg_begin();
7294 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7295 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007296 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007297 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007298 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007299 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007300 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7301 ParamTy->isSigned() == ActTy->isSigned() &&
7302 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7303 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007304 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007305 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007306 }
7307
7308 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7309 Callee->isExternal())
7310 return false; // Do not delete arguments unless we have a function body...
7311
7312 // Okay, we decided that this is a safe thing to do: go ahead and start
7313 // inserting cast instructions as necessary...
7314 std::vector<Value*> Args;
7315 Args.reserve(NumActualArgs);
7316
7317 AI = CS.arg_begin();
7318 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7319 const Type *ParamTy = FT->getParamType(i);
7320 if ((*AI)->getType() == ParamTy) {
7321 Args.push_back(*AI);
7322 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007323 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7324 (*AI)->getType()->isSigned(), ParamTy, ParamTy->isSigned());
7325 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007326 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007327 }
7328 }
7329
7330 // If the function takes more arguments than the call was taking, add them
7331 // now...
7332 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7333 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7334
7335 // If we are removing arguments to the function, emit an obnoxious warning...
7336 if (FT->getNumParams() < NumActualArgs)
7337 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007338 cerr << "WARNING: While resolving call to function '"
7339 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007340 } else {
7341 // Add all of the arguments in their promoted form to the arg list...
7342 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7343 const Type *PTy = getPromotedType((*AI)->getType());
7344 if (PTy != (*AI)->getType()) {
7345 // Must promote to pass through va_arg area!
Reid Spencer668d90f2006-12-18 08:47:13 +00007346 Instruction::CastOps opcode = CastInst::getCastOpcode(
7347 *AI, (*AI)->getType()->isSigned(), PTy, PTy->isSigned());
7348 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007349 InsertNewInstBefore(Cast, *Caller);
7350 Args.push_back(Cast);
7351 } else {
7352 Args.push_back(*AI);
7353 }
7354 }
7355 }
7356
7357 if (FT->getReturnType() == Type::VoidTy)
7358 Caller->setName(""); // Void type should not have a name...
7359
7360 Instruction *NC;
7361 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007362 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007363 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007364 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007365 } else {
7366 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007367 if (cast<CallInst>(Caller)->isTailCall())
7368 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007369 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007370 }
7371
7372 // Insert a cast of the return type as necessary...
7373 Value *NV = NC;
7374 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7375 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007376 const Type *CallerTy = Caller->getType();
7377 Instruction::CastOps opcode = CastInst::getCastOpcode(
7378 NC, NC->getType()->isSigned(), CallerTy, CallerTy->isSigned());
7379 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007380
7381 // If this is an invoke instruction, we should insert it after the first
7382 // non-phi, instruction in the normal successor block.
7383 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7384 BasicBlock::iterator I = II->getNormalDest()->begin();
7385 while (isa<PHINode>(I)) ++I;
7386 InsertNewInstBefore(NC, *I);
7387 } else {
7388 // Otherwise, it's a call, just insert cast right after the call instr
7389 InsertNewInstBefore(NC, *Caller);
7390 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007391 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007392 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007393 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007394 }
7395 }
7396
7397 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7398 Caller->replaceAllUsesWith(NV);
7399 Caller->getParent()->getInstList().erase(Caller);
7400 removeFromWorkList(Caller);
7401 return true;
7402}
7403
Chris Lattnercadac0c2006-11-01 04:51:18 +00007404/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7405/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7406/// and a single binop.
7407Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7408 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007409 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007410 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007411 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007412 Value *LHSVal = FirstInst->getOperand(0);
7413 Value *RHSVal = FirstInst->getOperand(1);
7414
7415 const Type *LHSType = LHSVal->getType();
7416 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007417
7418 // Scan to see if all operands are the same opcode, all have one use, and all
7419 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007420 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007421 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007422 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007423 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007424 // types or GEP's with different index types.
7425 I->getOperand(0)->getType() != LHSType ||
7426 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007427 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007428
7429 // If they are CmpInst instructions, check their predicates
7430 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7431 if (cast<CmpInst>(I)->getPredicate() !=
7432 cast<CmpInst>(FirstInst)->getPredicate())
7433 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007434
7435 // Keep track of which operand needs a phi node.
7436 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7437 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007438 }
7439
Chris Lattner4f218d52006-11-08 19:42:28 +00007440 // Otherwise, this is safe to transform, determine if it is profitable.
7441
7442 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7443 // Indexes are often folded into load/store instructions, so we don't want to
7444 // hide them behind a phi.
7445 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7446 return 0;
7447
Chris Lattnercadac0c2006-11-01 04:51:18 +00007448 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007449 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007450 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007451 if (LHSVal == 0) {
7452 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7453 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7454 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007455 InsertNewInstBefore(NewLHS, PN);
7456 LHSVal = NewLHS;
7457 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007458
7459 if (RHSVal == 0) {
7460 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7461 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7462 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007463 InsertNewInstBefore(NewRHS, PN);
7464 RHSVal = NewRHS;
7465 }
7466
Chris Lattnercd62f112006-11-08 19:29:23 +00007467 // Add all operands to the new PHIs.
7468 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7469 if (NewLHS) {
7470 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7471 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7472 }
7473 if (NewRHS) {
7474 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7475 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7476 }
7477 }
7478
Chris Lattnercadac0c2006-11-01 04:51:18 +00007479 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007480 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007481 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7482 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7483 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007484 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7485 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7486 else {
7487 assert(isa<GetElementPtrInst>(FirstInst));
7488 return new GetElementPtrInst(LHSVal, RHSVal);
7489 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007490}
7491
Chris Lattner14f82c72006-11-01 07:13:54 +00007492/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7493/// of the block that defines it. This means that it must be obvious the value
7494/// of the load is not changed from the point of the load to the end of the
7495/// block it is in.
7496static bool isSafeToSinkLoad(LoadInst *L) {
7497 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7498
7499 for (++BBI; BBI != E; ++BBI)
7500 if (BBI->mayWriteToMemory())
7501 return false;
7502 return true;
7503}
7504
Chris Lattner970c33a2003-06-19 17:00:31 +00007505
Chris Lattner7515cab2004-11-14 19:13:23 +00007506// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7507// operator and they all are only used by the PHI, PHI together their
7508// inputs, and do the operation once, to the result of the PHI.
7509Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7510 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7511
7512 // Scan the instruction, looking for input operations that can be folded away.
7513 // If all input operands to the phi are the same instruction (e.g. a cast from
7514 // the same type or "+42") we can pull the operation through the PHI, reducing
7515 // code size and simplifying code.
7516 Constant *ConstantOp = 0;
7517 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007518 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007519 if (isa<CastInst>(FirstInst)) {
7520 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007521 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7522 isa<CmpInst>(FirstInst)) {
7523 // Can fold binop, compare or shift here if the RHS is a constant,
7524 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007525 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007526 if (ConstantOp == 0)
7527 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007528 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7529 isVolatile = LI->isVolatile();
7530 // We can't sink the load if the loaded value could be modified between the
7531 // load and the PHI.
7532 if (LI->getParent() != PN.getIncomingBlock(0) ||
7533 !isSafeToSinkLoad(LI))
7534 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007535 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007536 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007537 return FoldPHIArgBinOpIntoPHI(PN);
7538 // Can't handle general GEPs yet.
7539 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007540 } else {
7541 return 0; // Cannot fold this operation.
7542 }
7543
7544 // Check to see if all arguments are the same operation.
7545 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7546 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7547 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007548 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007549 return 0;
7550 if (CastSrcTy) {
7551 if (I->getOperand(0)->getType() != CastSrcTy)
7552 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007553 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007554 // We can't sink the load if the loaded value could be modified between
7555 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007556 if (LI->isVolatile() != isVolatile ||
7557 LI->getParent() != PN.getIncomingBlock(i) ||
7558 !isSafeToSinkLoad(LI))
7559 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007560 } else if (I->getOperand(1) != ConstantOp) {
7561 return 0;
7562 }
7563 }
7564
7565 // Okay, they are all the same operation. Create a new PHI node of the
7566 // correct type, and PHI together all of the LHS's of the instructions.
7567 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7568 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007569 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007570
7571 Value *InVal = FirstInst->getOperand(0);
7572 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007573
7574 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007575 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7576 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7577 if (NewInVal != InVal)
7578 InVal = 0;
7579 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7580 }
7581
7582 Value *PhiVal;
7583 if (InVal) {
7584 // The new PHI unions all of the same values together. This is really
7585 // common, so we handle it intelligently here for compile-time speed.
7586 PhiVal = InVal;
7587 delete NewPN;
7588 } else {
7589 InsertNewInstBefore(NewPN, PN);
7590 PhiVal = NewPN;
7591 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007592
Chris Lattner7515cab2004-11-14 19:13:23 +00007593 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007594 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7595 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007596 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007597 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007598 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007599 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007600 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7601 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7602 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007603 else
7604 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007605 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007606}
Chris Lattner48a44f72002-05-02 17:06:02 +00007607
Chris Lattner71536432005-01-17 05:10:15 +00007608/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7609/// that is dead.
7610static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7611 if (PN->use_empty()) return true;
7612 if (!PN->hasOneUse()) return false;
7613
7614 // Remember this node, and if we find the cycle, return.
7615 if (!PotentiallyDeadPHIs.insert(PN).second)
7616 return true;
7617
7618 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7619 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007620
Chris Lattner71536432005-01-17 05:10:15 +00007621 return false;
7622}
7623
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007624// PHINode simplification
7625//
Chris Lattner113f4f42002-06-25 16:13:24 +00007626Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007627 // If LCSSA is around, don't mess with Phi nodes
7628 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007629
Owen Andersonae8aa642006-07-10 22:03:18 +00007630 if (Value *V = PN.hasConstantValue())
7631 return ReplaceInstUsesWith(PN, V);
7632
Owen Andersonae8aa642006-07-10 22:03:18 +00007633 // If all PHI operands are the same operation, pull them through the PHI,
7634 // reducing code size.
7635 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7636 PN.getIncomingValue(0)->hasOneUse())
7637 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7638 return Result;
7639
7640 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7641 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7642 // PHI)... break the cycle.
7643 if (PN.hasOneUse())
7644 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7645 std::set<PHINode*> PotentiallyDeadPHIs;
7646 PotentiallyDeadPHIs.insert(&PN);
7647 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7648 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7649 }
7650
Chris Lattner91daeb52003-12-19 05:58:40 +00007651 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007652}
7653
Reid Spencer13bc5d72006-12-12 09:18:51 +00007654static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7655 Instruction *InsertPoint,
7656 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007657 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007658 unsigned VTySize = V->getType()->getPrimitiveSize();
7659 // We must cast correctly to the pointer type. Ensure that we
7660 // sign extend the integer value if it is smaller as this is
7661 // used for address computation.
7662 Instruction::CastOps opcode =
7663 (VTySize < PtrSize ? Instruction::SExt :
7664 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7665 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007666}
7667
Chris Lattner48a44f72002-05-02 17:06:02 +00007668
Chris Lattner113f4f42002-06-25 16:13:24 +00007669Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007670 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007671 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007672 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007673 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007674 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007675
Chris Lattner81a7a232004-10-16 18:11:37 +00007676 if (isa<UndefValue>(GEP.getOperand(0)))
7677 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7678
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007679 bool HasZeroPointerIndex = false;
7680 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7681 HasZeroPointerIndex = C->isNullValue();
7682
7683 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007684 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007685
Chris Lattner69193f92004-04-05 01:30:19 +00007686 // Eliminate unneeded casts for indices.
7687 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007688 gep_type_iterator GTI = gep_type_begin(GEP);
7689 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7690 if (isa<SequentialType>(*GTI)) {
7691 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7692 Value *Src = CI->getOperand(0);
7693 const Type *SrcTy = Src->getType();
7694 const Type *DestTy = CI->getType();
7695 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007696 if (SrcTy->getPrimitiveSizeInBits() ==
7697 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007698 // We can always eliminate a cast from ulong or long to the other.
7699 // We can always eliminate a cast from uint to int or the other on
7700 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007701 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007702 MadeChange = true;
7703 GEP.setOperand(i, Src);
7704 }
7705 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7706 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007707 // We can eliminate a cast from [u]int to [u]long iff the target
7708 // is a 32-bit pointer target.
7709 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007710 MadeChange = true;
7711 GEP.setOperand(i, Src);
7712 }
Chris Lattner69193f92004-04-05 01:30:19 +00007713 }
7714 }
7715 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007716 // If we are using a wider index than needed for this platform, shrink it
7717 // to what we need. If the incoming value needs a cast instruction,
7718 // insert it. This explicit cast can make subsequent optimizations more
7719 // obvious.
7720 Value *Op = GEP.getOperand(i);
7721 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007722 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007723 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007724 MadeChange = true;
7725 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007726 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7727 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007728 GEP.setOperand(i, Op);
7729 MadeChange = true;
7730 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007731 // If this is a constant idx, make sure to canonicalize it to be a signed
7732 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007733 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7734 if (CUI->getType()->isUnsigned()) {
7735 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007736 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007737 MadeChange = true;
7738 }
Chris Lattner69193f92004-04-05 01:30:19 +00007739 }
7740 if (MadeChange) return &GEP;
7741
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007742 // Combine Indices - If the source pointer to this getelementptr instruction
7743 // is a getelementptr instruction, combine the indices of the two
7744 // getelementptr instructions into a single instruction.
7745 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007746 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007747 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007748 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007749
7750 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007751 // Note that if our source is a gep chain itself that we wait for that
7752 // chain to be resolved before we perform this transformation. This
7753 // avoids us creating a TON of code in some cases.
7754 //
7755 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7756 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7757 return 0; // Wait until our source is folded to completion.
7758
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007759 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007760
7761 // Find out whether the last index in the source GEP is a sequential idx.
7762 bool EndsWithSequential = false;
7763 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7764 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007765 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007766
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007767 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007768 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007769 // Replace: gep (gep %P, long B), long A, ...
7770 // With: T = long A+B; gep %P, T, ...
7771 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007772 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007773 if (SO1 == Constant::getNullValue(SO1->getType())) {
7774 Sum = GO1;
7775 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7776 Sum = SO1;
7777 } else {
7778 // If they aren't the same type, convert both to an integer of the
7779 // target's pointer size.
7780 if (SO1->getType() != GO1->getType()) {
7781 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007782 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007783 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007784 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007785 } else {
7786 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007787 if (SO1->getType()->getPrimitiveSize() == PS) {
7788 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007789 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007790
7791 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7792 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007793 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007794 } else {
7795 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007796 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7797 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007798 }
7799 }
7800 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007801 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7802 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7803 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007804 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7805 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007806 }
Chris Lattner69193f92004-04-05 01:30:19 +00007807 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007808
7809 // Recycle the GEP we already have if possible.
7810 if (SrcGEPOperands.size() == 2) {
7811 GEP.setOperand(0, SrcGEPOperands[0]);
7812 GEP.setOperand(1, Sum);
7813 return &GEP;
7814 } else {
7815 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7816 SrcGEPOperands.end()-1);
7817 Indices.push_back(Sum);
7818 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7819 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007820 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007821 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007822 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007823 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007824 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7825 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007826 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7827 }
7828
7829 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007830 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007831
Chris Lattner5f667a62004-05-07 22:09:22 +00007832 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007833 // GEP of global variable. If all of the indices for this GEP are
7834 // constants, we can promote this to a constexpr instead of an instruction.
7835
7836 // Scan for nonconstants...
7837 std::vector<Constant*> Indices;
7838 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7839 for (; I != E && isa<Constant>(*I); ++I)
7840 Indices.push_back(cast<Constant>(*I));
7841
7842 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007843 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007844
7845 // Replace all uses of the GEP with the new constexpr...
7846 return ReplaceInstUsesWith(GEP, CE);
7847 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007848 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007849 if (!isa<PointerType>(X->getType())) {
7850 // Not interesting. Source pointer must be a cast from pointer.
7851 } else if (HasZeroPointerIndex) {
7852 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7853 // into : GEP [10 x ubyte]* X, long 0, ...
7854 //
7855 // This occurs when the program declares an array extern like "int X[];"
7856 //
7857 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7858 const PointerType *XTy = cast<PointerType>(X->getType());
7859 if (const ArrayType *XATy =
7860 dyn_cast<ArrayType>(XTy->getElementType()))
7861 if (const ArrayType *CATy =
7862 dyn_cast<ArrayType>(CPTy->getElementType()))
7863 if (CATy->getElementType() == XATy->getElementType()) {
7864 // At this point, we know that the cast source type is a pointer
7865 // to an array of the same type as the destination pointer
7866 // array. Because the array type is never stepped over (there
7867 // is a leading zero) we can fold the cast into this GEP.
7868 GEP.setOperand(0, X);
7869 return &GEP;
7870 }
7871 } else if (GEP.getNumOperands() == 2) {
7872 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007873 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7874 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007875 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7876 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7877 if (isa<ArrayType>(SrcElTy) &&
7878 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7879 TD->getTypeSize(ResElTy)) {
7880 Value *V = InsertNewInstBefore(
7881 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7882 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007883 // V and GEP are both pointer types --> BitCast
7884 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007885 }
Chris Lattner2a893292005-09-13 18:36:04 +00007886
7887 // Transform things like:
7888 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7889 // (where tmp = 8*tmp2) into:
7890 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7891
7892 if (isa<ArrayType>(SrcElTy) &&
7893 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7894 uint64_t ArrayEltSize =
7895 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7896
7897 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7898 // allow either a mul, shift, or constant here.
7899 Value *NewIdx = 0;
7900 ConstantInt *Scale = 0;
7901 if (ArrayEltSize == 1) {
7902 NewIdx = GEP.getOperand(1);
7903 Scale = ConstantInt::get(NewIdx->getType(), 1);
7904 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007905 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007906 Scale = CI;
7907 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7908 if (Inst->getOpcode() == Instruction::Shl &&
7909 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007910 unsigned ShAmt =
7911 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007912 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007913 NewIdx = Inst->getOperand(0);
7914 } else if (Inst->getOpcode() == Instruction::Mul &&
7915 isa<ConstantInt>(Inst->getOperand(1))) {
7916 Scale = cast<ConstantInt>(Inst->getOperand(1));
7917 NewIdx = Inst->getOperand(0);
7918 }
7919 }
7920
7921 // If the index will be to exactly the right offset with the scale taken
7922 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007923 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007924 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007925 Scale = ConstantInt::get(Scale->getType(),
7926 Scale->getZExtValue() / ArrayEltSize);
7927 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007928 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7929 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007930 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7931 NewIdx = InsertNewInstBefore(Sc, GEP);
7932 }
7933
7934 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007935 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007936 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7937 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007938 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7939 // The NewGEP must be pointer typed, so must the old one -> BitCast
7940 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007941 }
7942 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007943 }
Chris Lattnerca081252001-12-14 16:52:21 +00007944 }
7945
Chris Lattnerca081252001-12-14 16:52:21 +00007946 return 0;
7947}
7948
Chris Lattner1085bdf2002-11-04 16:18:53 +00007949Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7950 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7951 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007952 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7953 const Type *NewTy =
7954 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007955 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007956
7957 // Create and insert the replacement instruction...
7958 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007959 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007960 else {
7961 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007962 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007963 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007964
7965 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007966
Chris Lattner1085bdf2002-11-04 16:18:53 +00007967 // Scan to the end of the allocation instructions, to skip over a block of
7968 // allocas if possible...
7969 //
7970 BasicBlock::iterator It = New;
7971 while (isa<AllocationInst>(*It)) ++It;
7972
7973 // Now that I is pointing to the first non-allocation-inst in the block,
7974 // insert our getelementptr instruction...
7975 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007976 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7977 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7978 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007979
7980 // Now make everything use the getelementptr instead of the original
7981 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007982 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007983 } else if (isa<UndefValue>(AI.getArraySize())) {
7984 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007985 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007986
7987 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7988 // Note that we only do this for alloca's, because malloc should allocate and
7989 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007990 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007991 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007992 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7993
Chris Lattner1085bdf2002-11-04 16:18:53 +00007994 return 0;
7995}
7996
Chris Lattner8427bff2003-12-07 01:24:23 +00007997Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7998 Value *Op = FI.getOperand(0);
7999
8000 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8001 if (CastInst *CI = dyn_cast<CastInst>(Op))
8002 if (isa<PointerType>(CI->getOperand(0)->getType())) {
8003 FI.setOperand(0, CI->getOperand(0));
8004 return &FI;
8005 }
8006
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008007 // free undef -> unreachable.
8008 if (isa<UndefValue>(Op)) {
8009 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00008010 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008011 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
8012 return EraseInstFromFunction(FI);
8013 }
8014
Chris Lattnerf3a36602004-02-28 04:57:37 +00008015 // If we have 'free null' delete the instruction. This can happen in stl code
8016 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008017 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00008018 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00008019
Chris Lattner8427bff2003-12-07 01:24:23 +00008020 return 0;
8021}
8022
8023
Chris Lattner72684fe2005-01-31 05:51:45 +00008024/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00008025static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8026 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008027 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00008028
8029 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008030 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00008031 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008032
Chris Lattnerebca4762006-04-02 05:37:12 +00008033 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8034 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008035 // If the source is an array, the code below will not succeed. Check to
8036 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8037 // constants.
8038 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8039 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8040 if (ASrcTy->getNumElements() != 0) {
8041 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8042 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8043 SrcTy = cast<PointerType>(CastOp->getType());
8044 SrcPTy = SrcTy->getElementType();
8045 }
8046
Chris Lattnerebca4762006-04-02 05:37:12 +00008047 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8048 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00008049 // Do not allow turning this into a load of an integer, which is then
8050 // casted to a pointer, this pessimizes pointer analysis a lot.
8051 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008052 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008053 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00008054
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008055 // Okay, we are casting from one integer or pointer type to another of
8056 // the same size. Instead of casting the pointer before the load, cast
8057 // the result of the loaded value.
8058 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8059 CI->getName(),
8060 LI.isVolatile()),LI);
8061 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008062 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008063 }
Chris Lattner35e24772004-07-13 01:49:43 +00008064 }
8065 }
8066 return 0;
8067}
8068
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008069/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008070/// from this value cannot trap. If it is not obviously safe to load from the
8071/// specified pointer, we do a quick local scan of the basic block containing
8072/// ScanFrom, to determine if the address is already accessed.
8073static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8074 // If it is an alloca or global variable, it is always safe to load from.
8075 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8076
8077 // Otherwise, be a little bit agressive by scanning the local block where we
8078 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008079 // from/to. If so, the previous load or store would have already trapped,
8080 // so there is no harm doing an extra load (also, CSE will later eliminate
8081 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008082 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8083
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008084 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008085 --BBI;
8086
8087 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8088 if (LI->getOperand(0) == V) return true;
8089 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8090 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008091
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008092 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008093 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008094}
8095
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008096Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8097 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008098
Chris Lattnera9d84e32005-05-01 04:24:53 +00008099 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008100 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008101 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8102 return Res;
8103
8104 // None of the following transforms are legal for volatile loads.
8105 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008106
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008107 if (&LI.getParent()->front() != &LI) {
8108 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008109 // If the instruction immediately before this is a store to the same
8110 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008111 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8112 if (SI->getOperand(1) == LI.getOperand(0))
8113 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008114 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8115 if (LIB->getOperand(0) == LI.getOperand(0))
8116 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008117 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008118
8119 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8120 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8121 isa<UndefValue>(GEPI->getOperand(0))) {
8122 // Insert a new store to null instruction before the load to indicate
8123 // that this code is not reachable. We do this instead of inserting
8124 // an unreachable instruction directly because we cannot modify the
8125 // CFG.
8126 new StoreInst(UndefValue::get(LI.getType()),
8127 Constant::getNullValue(Op->getType()), &LI);
8128 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8129 }
8130
Chris Lattner81a7a232004-10-16 18:11:37 +00008131 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008132 // load null/undef -> undef
8133 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008134 // Insert a new store to null instruction before the load to indicate that
8135 // this code is not reachable. We do this instead of inserting an
8136 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008137 new StoreInst(UndefValue::get(LI.getType()),
8138 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008139 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008140 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008141
Chris Lattner81a7a232004-10-16 18:11:37 +00008142 // Instcombine load (constant global) into the value loaded.
8143 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8144 if (GV->isConstant() && !GV->isExternal())
8145 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008146
Chris Lattner81a7a232004-10-16 18:11:37 +00008147 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8148 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8149 if (CE->getOpcode() == Instruction::GetElementPtr) {
8150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8151 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008152 if (Constant *V =
8153 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008154 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008155 if (CE->getOperand(0)->isNullValue()) {
8156 // Insert a new store to null instruction before the load to indicate
8157 // that this code is not reachable. We do this instead of inserting
8158 // an unreachable instruction directly because we cannot modify the
8159 // CFG.
8160 new StoreInst(UndefValue::get(LI.getType()),
8161 Constant::getNullValue(Op->getType()), &LI);
8162 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8163 }
8164
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008165 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008166 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8167 return Res;
8168 }
8169 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008170
Chris Lattnera9d84e32005-05-01 04:24:53 +00008171 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008172 // Change select and PHI nodes to select values instead of addresses: this
8173 // helps alias analysis out a lot, allows many others simplifications, and
8174 // exposes redundancy in the code.
8175 //
8176 // Note that we cannot do the transformation unless we know that the
8177 // introduced loads cannot trap! Something like this is valid as long as
8178 // the condition is always false: load (select bool %C, int* null, int* %G),
8179 // but it would not be valid if we transformed it to load from null
8180 // unconditionally.
8181 //
8182 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8183 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008184 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8185 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008186 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008187 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008188 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008189 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008190 return new SelectInst(SI->getCondition(), V1, V2);
8191 }
8192
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008193 // load (select (cond, null, P)) -> load P
8194 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8195 if (C->isNullValue()) {
8196 LI.setOperand(0, SI->getOperand(2));
8197 return &LI;
8198 }
8199
8200 // load (select (cond, P, null)) -> load P
8201 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8202 if (C->isNullValue()) {
8203 LI.setOperand(0, SI->getOperand(1));
8204 return &LI;
8205 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008206 }
8207 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008208 return 0;
8209}
8210
Chris Lattner72684fe2005-01-31 05:51:45 +00008211/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8212/// when possible.
8213static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8214 User *CI = cast<User>(SI.getOperand(1));
8215 Value *CastOp = CI->getOperand(0);
8216
8217 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8218 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8219 const Type *SrcPTy = SrcTy->getElementType();
8220
8221 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8222 // If the source is an array, the code below will not succeed. Check to
8223 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8224 // constants.
8225 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8226 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8227 if (ASrcTy->getNumElements() != 0) {
8228 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
8229 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8230 SrcTy = cast<PointerType>(CastOp->getType());
8231 SrcPTy = SrcTy->getElementType();
8232 }
8233
8234 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008235 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008236 IC.getTargetData().getTypeSize(DestPTy)) {
8237
8238 // Okay, we are casting from one integer or pointer type to another of
8239 // the same size. Instead of casting the pointer before the store, cast
8240 // the value to be stored.
8241 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008242 Instruction::CastOps opcode = Instruction::BitCast;
8243 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008244 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008245 if (SIOp0->getType()->isIntegral())
8246 opcode = Instruction::IntToPtr;
8247 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008248 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008249 opcode = Instruction::PtrToInt;
8250 }
8251 if (Constant *C = dyn_cast<Constant>(SIOp0))
8252 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008253 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008254 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008255 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008256 return new StoreInst(NewCast, CastOp);
8257 }
8258 }
8259 }
8260 return 0;
8261}
8262
Chris Lattner31f486c2005-01-31 05:36:43 +00008263Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8264 Value *Val = SI.getOperand(0);
8265 Value *Ptr = SI.getOperand(1);
8266
8267 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008268 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008269 ++NumCombined;
8270 return 0;
8271 }
8272
Chris Lattner5997cf92006-02-08 03:25:32 +00008273 // Do really simple DSE, to catch cases where there are several consequtive
8274 // stores to the same location, separated by a few arithmetic operations. This
8275 // situation often occurs with bitfield accesses.
8276 BasicBlock::iterator BBI = &SI;
8277 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8278 --ScanInsts) {
8279 --BBI;
8280
8281 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8282 // Prev store isn't volatile, and stores to the same location?
8283 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8284 ++NumDeadStore;
8285 ++BBI;
8286 EraseInstFromFunction(*PrevSI);
8287 continue;
8288 }
8289 break;
8290 }
8291
Chris Lattnerdab43b22006-05-26 19:19:20 +00008292 // If this is a load, we have to stop. However, if the loaded value is from
8293 // the pointer we're loading and is producing the pointer we're storing,
8294 // then *this* store is dead (X = load P; store X -> P).
8295 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8296 if (LI == Val && LI->getOperand(0) == Ptr) {
8297 EraseInstFromFunction(SI);
8298 ++NumCombined;
8299 return 0;
8300 }
8301 // Otherwise, this is a load from some other location. Stores before it
8302 // may not be dead.
8303 break;
8304 }
8305
Chris Lattner5997cf92006-02-08 03:25:32 +00008306 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008307 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008308 break;
8309 }
8310
8311
8312 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008313
8314 // store X, null -> turns into 'unreachable' in SimplifyCFG
8315 if (isa<ConstantPointerNull>(Ptr)) {
8316 if (!isa<UndefValue>(Val)) {
8317 SI.setOperand(0, UndefValue::get(Val->getType()));
8318 if (Instruction *U = dyn_cast<Instruction>(Val))
8319 WorkList.push_back(U); // Dropped a use.
8320 ++NumCombined;
8321 }
8322 return 0; // Do not modify these!
8323 }
8324
8325 // store undef, Ptr -> noop
8326 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008327 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008328 ++NumCombined;
8329 return 0;
8330 }
8331
Chris Lattner72684fe2005-01-31 05:51:45 +00008332 // If the pointer destination is a cast, see if we can fold the cast into the
8333 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008334 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008335 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8336 return Res;
8337 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008338 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008339 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8340 return Res;
8341
Chris Lattner219175c2005-09-12 23:23:25 +00008342
8343 // If this store is the last instruction in the basic block, and if the block
8344 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008345 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008346 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8347 if (BI->isUnconditional()) {
8348 // Check to see if the successor block has exactly two incoming edges. If
8349 // so, see if the other predecessor contains a store to the same location.
8350 // if so, insert a PHI node (if needed) and move the stores down.
8351 BasicBlock *Dest = BI->getSuccessor(0);
8352
8353 pred_iterator PI = pred_begin(Dest);
8354 BasicBlock *Other = 0;
8355 if (*PI != BI->getParent())
8356 Other = *PI;
8357 ++PI;
8358 if (PI != pred_end(Dest)) {
8359 if (*PI != BI->getParent())
8360 if (Other)
8361 Other = 0;
8362 else
8363 Other = *PI;
8364 if (++PI != pred_end(Dest))
8365 Other = 0;
8366 }
8367 if (Other) { // If only one other pred...
8368 BBI = Other->getTerminator();
8369 // Make sure this other block ends in an unconditional branch and that
8370 // there is an instruction before the branch.
8371 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8372 BBI != Other->begin()) {
8373 --BBI;
8374 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8375
8376 // If this instruction is a store to the same location.
8377 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8378 // Okay, we know we can perform this transformation. Insert a PHI
8379 // node now if we need it.
8380 Value *MergedVal = OtherStore->getOperand(0);
8381 if (MergedVal != SI.getOperand(0)) {
8382 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8383 PN->reserveOperandSpace(2);
8384 PN->addIncoming(SI.getOperand(0), SI.getParent());
8385 PN->addIncoming(OtherStore->getOperand(0), Other);
8386 MergedVal = InsertNewInstBefore(PN, Dest->front());
8387 }
8388
8389 // Advance to a place where it is safe to insert the new store and
8390 // insert it.
8391 BBI = Dest->begin();
8392 while (isa<PHINode>(BBI)) ++BBI;
8393 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8394 OtherStore->isVolatile()), *BBI);
8395
8396 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008397 EraseInstFromFunction(SI);
8398 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008399 ++NumCombined;
8400 return 0;
8401 }
8402 }
8403 }
8404 }
8405
Chris Lattner31f486c2005-01-31 05:36:43 +00008406 return 0;
8407}
8408
8409
Chris Lattner9eef8a72003-06-04 04:46:00 +00008410Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8411 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008412 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008413 BasicBlock *TrueDest;
8414 BasicBlock *FalseDest;
8415 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8416 !isa<Constant>(X)) {
8417 // Swap Destinations and condition...
8418 BI.setCondition(X);
8419 BI.setSuccessor(0, FalseDest);
8420 BI.setSuccessor(1, TrueDest);
8421 return &BI;
8422 }
8423
Reid Spencer266e42b2006-12-23 06:05:41 +00008424 // Cannonicalize fcmp_one -> fcmp_oeq
8425 FCmpInst::Predicate FPred; Value *Y;
8426 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8427 TrueDest, FalseDest)))
8428 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8429 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8430 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008431 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008432 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8433 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8434 // Swap Destinations and condition...
8435 BI.setCondition(NewSCC);
8436 BI.setSuccessor(0, FalseDest);
8437 BI.setSuccessor(1, TrueDest);
8438 removeFromWorkList(I);
8439 I->getParent()->getInstList().erase(I);
8440 WorkList.push_back(cast<Instruction>(NewSCC));
8441 return &BI;
8442 }
8443
8444 // Cannonicalize icmp_ne -> icmp_eq
8445 ICmpInst::Predicate IPred;
8446 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8447 TrueDest, FalseDest)))
8448 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8449 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8450 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8451 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8452 std::string Name = I->getName(); I->setName("");
8453 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8454 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008455 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008456 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008457 BI.setSuccessor(0, FalseDest);
8458 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008459 removeFromWorkList(I);
8460 I->getParent()->getInstList().erase(I);
8461 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008462 return &BI;
8463 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008464
Chris Lattner9eef8a72003-06-04 04:46:00 +00008465 return 0;
8466}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008467
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008468Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8469 Value *Cond = SI.getCondition();
8470 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8471 if (I->getOpcode() == Instruction::Add)
8472 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8473 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8474 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008475 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008476 AddRHS));
8477 SI.setOperand(0, I->getOperand(0));
8478 WorkList.push_back(I);
8479 return &SI;
8480 }
8481 }
8482 return 0;
8483}
8484
Chris Lattner6bc98652006-03-05 00:22:33 +00008485/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8486/// is to leave as a vector operation.
8487static bool CheapToScalarize(Value *V, bool isConstant) {
8488 if (isa<ConstantAggregateZero>(V))
8489 return true;
8490 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8491 if (isConstant) return true;
8492 // If all elts are the same, we can extract.
8493 Constant *Op0 = C->getOperand(0);
8494 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8495 if (C->getOperand(i) != Op0)
8496 return false;
8497 return true;
8498 }
8499 Instruction *I = dyn_cast<Instruction>(V);
8500 if (!I) return false;
8501
8502 // Insert element gets simplified to the inserted element or is deleted if
8503 // this is constant idx extract element and its a constant idx insertelt.
8504 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8505 isa<ConstantInt>(I->getOperand(2)))
8506 return true;
8507 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8508 return true;
8509 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8510 if (BO->hasOneUse() &&
8511 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8512 CheapToScalarize(BO->getOperand(1), isConstant)))
8513 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008514 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8515 if (CI->hasOneUse() &&
8516 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8517 CheapToScalarize(CI->getOperand(1), isConstant)))
8518 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008519
8520 return false;
8521}
8522
Chris Lattner12249be2006-05-25 23:48:38 +00008523/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8524/// elements into values that are larger than the #elts in the input.
8525static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8526 unsigned NElts = SVI->getType()->getNumElements();
8527 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8528 return std::vector<unsigned>(NElts, 0);
8529 if (isa<UndefValue>(SVI->getOperand(2)))
8530 return std::vector<unsigned>(NElts, 2*NElts);
8531
8532 std::vector<unsigned> Result;
8533 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8534 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8535 if (isa<UndefValue>(CP->getOperand(i)))
8536 Result.push_back(NElts*2); // undef -> 8
8537 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008538 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008539 return Result;
8540}
8541
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008542/// FindScalarElement - Given a vector and an element number, see if the scalar
8543/// value is already around as a register, for example if it were inserted then
8544/// extracted from the vector.
8545static Value *FindScalarElement(Value *V, unsigned EltNo) {
8546 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8547 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008548 unsigned Width = PTy->getNumElements();
8549 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008550 return UndefValue::get(PTy->getElementType());
8551
8552 if (isa<UndefValue>(V))
8553 return UndefValue::get(PTy->getElementType());
8554 else if (isa<ConstantAggregateZero>(V))
8555 return Constant::getNullValue(PTy->getElementType());
8556 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8557 return CP->getOperand(EltNo);
8558 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8559 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008560 if (!isa<ConstantInt>(III->getOperand(2)))
8561 return 0;
8562 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008563
8564 // If this is an insert to the element we are looking for, return the
8565 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008566 if (EltNo == IIElt)
8567 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008568
8569 // Otherwise, the insertelement doesn't modify the value, recurse on its
8570 // vector input.
8571 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008572 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008573 unsigned InEl = getShuffleMask(SVI)[EltNo];
8574 if (InEl < Width)
8575 return FindScalarElement(SVI->getOperand(0), InEl);
8576 else if (InEl < Width*2)
8577 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8578 else
8579 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008580 }
8581
8582 // Otherwise, we don't know.
8583 return 0;
8584}
8585
Robert Bocchinoa8352962006-01-13 22:48:06 +00008586Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008587
Chris Lattner92346c32006-03-31 18:25:14 +00008588 // If packed val is undef, replace extract with scalar undef.
8589 if (isa<UndefValue>(EI.getOperand(0)))
8590 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8591
8592 // If packed val is constant 0, replace extract with scalar 0.
8593 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8594 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8595
Robert Bocchinoa8352962006-01-13 22:48:06 +00008596 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8597 // If packed val is constant with uniform operands, replace EI
8598 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008599 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008600 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008601 if (C->getOperand(i) != op0) {
8602 op0 = 0;
8603 break;
8604 }
8605 if (op0)
8606 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008607 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008608
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008609 // If extracting a specified index from the vector, see if we can recursively
8610 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008611 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008612 // This instruction only demands the single element from the input vector.
8613 // If the input vector has a single use, simplify it based on this use
8614 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008615 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008616 if (EI.getOperand(0)->hasOneUse()) {
8617 uint64_t UndefElts;
8618 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008619 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008620 UndefElts)) {
8621 EI.setOperand(0, V);
8622 return &EI;
8623 }
8624 }
8625
Reid Spencere0fc4df2006-10-20 07:07:24 +00008626 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008627 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008628 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008629
Chris Lattner83f65782006-05-25 22:53:38 +00008630 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008631 if (I->hasOneUse()) {
8632 // Push extractelement into predecessor operation if legal and
8633 // profitable to do so
8634 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008635 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8636 if (CheapToScalarize(BO, isConstantElt)) {
8637 ExtractElementInst *newEI0 =
8638 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8639 EI.getName()+".lhs");
8640 ExtractElementInst *newEI1 =
8641 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8642 EI.getName()+".rhs");
8643 InsertNewInstBefore(newEI0, EI);
8644 InsertNewInstBefore(newEI1, EI);
8645 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8646 }
Reid Spencerde46e482006-11-02 20:25:50 +00008647 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008648 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008649 PointerType::get(EI.getType()), EI);
8650 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008651 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008652 InsertNewInstBefore(GEP, EI);
8653 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008654 }
8655 }
8656 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8657 // Extracting the inserted element?
8658 if (IE->getOperand(2) == EI.getOperand(1))
8659 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8660 // If the inserted and extracted elements are constants, they must not
8661 // be the same value, extract from the pre-inserted value instead.
8662 if (isa<Constant>(IE->getOperand(2)) &&
8663 isa<Constant>(EI.getOperand(1))) {
8664 AddUsesToWorkList(EI);
8665 EI.setOperand(0, IE->getOperand(0));
8666 return &EI;
8667 }
8668 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8669 // If this is extracting an element from a shufflevector, figure out where
8670 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008671 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8672 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008673 Value *Src;
8674 if (SrcIdx < SVI->getType()->getNumElements())
8675 Src = SVI->getOperand(0);
8676 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8677 SrcIdx -= SVI->getType()->getNumElements();
8678 Src = SVI->getOperand(1);
8679 } else {
8680 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008681 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008682 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008683 }
8684 }
Chris Lattner83f65782006-05-25 22:53:38 +00008685 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008686 return 0;
8687}
8688
Chris Lattner90951862006-04-16 00:51:47 +00008689/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8690/// elements from either LHS or RHS, return the shuffle mask and true.
8691/// Otherwise, return false.
8692static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8693 std::vector<Constant*> &Mask) {
8694 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8695 "Invalid CollectSingleShuffleElements");
8696 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8697
8698 if (isa<UndefValue>(V)) {
8699 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8700 return true;
8701 } else if (V == LHS) {
8702 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008703 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008704 return true;
8705 } else if (V == RHS) {
8706 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008707 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008708 return true;
8709 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8710 // If this is an insert of an extract from some other vector, include it.
8711 Value *VecOp = IEI->getOperand(0);
8712 Value *ScalarOp = IEI->getOperand(1);
8713 Value *IdxOp = IEI->getOperand(2);
8714
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008715 if (!isa<ConstantInt>(IdxOp))
8716 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008717 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008718
8719 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8720 // Okay, we can handle this if the vector we are insertinting into is
8721 // transitively ok.
8722 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8723 // If so, update the mask to reflect the inserted undef.
8724 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8725 return true;
8726 }
8727 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8728 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008729 EI->getOperand(0)->getType() == V->getType()) {
8730 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008731 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008732
8733 // This must be extracting from either LHS or RHS.
8734 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8735 // Okay, we can handle this if the vector we are insertinting into is
8736 // transitively ok.
8737 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8738 // If so, update the mask to reflect the inserted value.
8739 if (EI->getOperand(0) == LHS) {
8740 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008741 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008742 } else {
8743 assert(EI->getOperand(0) == RHS);
8744 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008745 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008746
8747 }
8748 return true;
8749 }
8750 }
8751 }
8752 }
8753 }
8754 // TODO: Handle shufflevector here!
8755
8756 return false;
8757}
8758
8759/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8760/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8761/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008762static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008763 Value *&RHS) {
8764 assert(isa<PackedType>(V->getType()) &&
8765 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008766 "Invalid shuffle!");
8767 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8768
8769 if (isa<UndefValue>(V)) {
8770 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8771 return V;
8772 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008773 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008774 return V;
8775 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8776 // If this is an insert of an extract from some other vector, include it.
8777 Value *VecOp = IEI->getOperand(0);
8778 Value *ScalarOp = IEI->getOperand(1);
8779 Value *IdxOp = IEI->getOperand(2);
8780
8781 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8782 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8783 EI->getOperand(0)->getType() == V->getType()) {
8784 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008785 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8786 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008787
8788 // Either the extracted from or inserted into vector must be RHSVec,
8789 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008790 if (EI->getOperand(0) == RHS || RHS == 0) {
8791 RHS = EI->getOperand(0);
8792 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008793 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008794 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008795 return V;
8796 }
8797
Chris Lattner90951862006-04-16 00:51:47 +00008798 if (VecOp == RHS) {
8799 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008800 // Everything but the extracted element is replaced with the RHS.
8801 for (unsigned i = 0; i != NumElts; ++i) {
8802 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008803 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008804 }
8805 return V;
8806 }
Chris Lattner90951862006-04-16 00:51:47 +00008807
8808 // If this insertelement is a chain that comes from exactly these two
8809 // vectors, return the vector and the effective shuffle.
8810 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8811 return EI->getOperand(0);
8812
Chris Lattner39fac442006-04-15 01:39:45 +00008813 }
8814 }
8815 }
Chris Lattner90951862006-04-16 00:51:47 +00008816 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008817
8818 // Otherwise, can't do anything fancy. Return an identity vector.
8819 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008820 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008821 return V;
8822}
8823
8824Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8825 Value *VecOp = IE.getOperand(0);
8826 Value *ScalarOp = IE.getOperand(1);
8827 Value *IdxOp = IE.getOperand(2);
8828
8829 // If the inserted element was extracted from some other vector, and if the
8830 // indexes are constant, try to turn this into a shufflevector operation.
8831 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8832 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8833 EI->getOperand(0)->getType() == IE.getType()) {
8834 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008835 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8836 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008837
8838 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8839 return ReplaceInstUsesWith(IE, VecOp);
8840
8841 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8842 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8843
8844 // If we are extracting a value from a vector, then inserting it right
8845 // back into the same place, just use the input vector.
8846 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8847 return ReplaceInstUsesWith(IE, VecOp);
8848
8849 // We could theoretically do this for ANY input. However, doing so could
8850 // turn chains of insertelement instructions into a chain of shufflevector
8851 // instructions, and right now we do not merge shufflevectors. As such,
8852 // only do this in a situation where it is clear that there is benefit.
8853 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8854 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8855 // the values of VecOp, except then one read from EIOp0.
8856 // Build a new shuffle mask.
8857 std::vector<Constant*> Mask;
8858 if (isa<UndefValue>(VecOp))
8859 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8860 else {
8861 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008862 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008863 NumVectorElts));
8864 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008865 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008866 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8867 ConstantPacked::get(Mask));
8868 }
8869
8870 // If this insertelement isn't used by some other insertelement, turn it
8871 // (and any insertelements it points to), into one big shuffle.
8872 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8873 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008874 Value *RHS = 0;
8875 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8876 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8877 // We now have a shuffle of LHS, RHS, Mask.
8878 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008879 }
8880 }
8881 }
8882
8883 return 0;
8884}
8885
8886
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008887Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8888 Value *LHS = SVI.getOperand(0);
8889 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008890 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008891
8892 bool MadeChange = false;
8893
Chris Lattner2deeaea2006-10-05 06:55:50 +00008894 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008895 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008896 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8897
Chris Lattner39fac442006-04-15 01:39:45 +00008898 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8899 // the undef, change them to undefs.
8900
Chris Lattner12249be2006-05-25 23:48:38 +00008901 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8902 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8903 if (LHS == RHS || isa<UndefValue>(LHS)) {
8904 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008905 // shuffle(undef,undef,mask) -> undef.
8906 return ReplaceInstUsesWith(SVI, LHS);
8907 }
8908
Chris Lattner12249be2006-05-25 23:48:38 +00008909 // Remap any references to RHS to use LHS.
8910 std::vector<Constant*> Elts;
8911 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008912 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008913 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008914 else {
8915 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8916 (Mask[i] < e && isa<UndefValue>(LHS)))
8917 Mask[i] = 2*e; // Turn into undef.
8918 else
8919 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008920 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008921 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008922 }
Chris Lattner12249be2006-05-25 23:48:38 +00008923 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008924 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008925 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008926 LHS = SVI.getOperand(0);
8927 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008928 MadeChange = true;
8929 }
8930
Chris Lattner0e477162006-05-26 00:29:06 +00008931 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008932 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008933
Chris Lattner12249be2006-05-25 23:48:38 +00008934 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8935 if (Mask[i] >= e*2) continue; // Ignore undef values.
8936 // Is this an identity shuffle of the LHS value?
8937 isLHSID &= (Mask[i] == i);
8938
8939 // Is this an identity shuffle of the RHS value?
8940 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008941 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008942
Chris Lattner12249be2006-05-25 23:48:38 +00008943 // Eliminate identity shuffles.
8944 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8945 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008946
Chris Lattner0e477162006-05-26 00:29:06 +00008947 // If the LHS is a shufflevector itself, see if we can combine it with this
8948 // one without producing an unusual shuffle. Here we are really conservative:
8949 // we are absolutely afraid of producing a shuffle mask not in the input
8950 // program, because the code gen may not be smart enough to turn a merged
8951 // shuffle into two specific shuffles: it may produce worse code. As such,
8952 // we only merge two shuffles if the result is one of the two input shuffle
8953 // masks. In this case, merging the shuffles just removes one instruction,
8954 // which we know is safe. This is good for things like turning:
8955 // (splat(splat)) -> splat.
8956 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8957 if (isa<UndefValue>(RHS)) {
8958 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8959
8960 std::vector<unsigned> NewMask;
8961 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8962 if (Mask[i] >= 2*e)
8963 NewMask.push_back(2*e);
8964 else
8965 NewMask.push_back(LHSMask[Mask[i]]);
8966
8967 // If the result mask is equal to the src shuffle or this shuffle mask, do
8968 // the replacement.
8969 if (NewMask == LHSMask || NewMask == Mask) {
8970 std::vector<Constant*> Elts;
8971 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8972 if (NewMask[i] >= e*2) {
8973 Elts.push_back(UndefValue::get(Type::UIntTy));
8974 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008975 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008976 }
8977 }
8978 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8979 LHSSVI->getOperand(1),
8980 ConstantPacked::get(Elts));
8981 }
8982 }
8983 }
8984
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008985 return MadeChange ? &SVI : 0;
8986}
8987
8988
Robert Bocchinoa8352962006-01-13 22:48:06 +00008989
Chris Lattner99f48c62002-09-02 04:59:56 +00008990void InstCombiner::removeFromWorkList(Instruction *I) {
8991 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8992 WorkList.end());
8993}
8994
Chris Lattner39c98bb2004-12-08 23:43:58 +00008995
8996/// TryToSinkInstruction - Try to move the specified instruction from its
8997/// current block into the beginning of DestBlock, which can only happen if it's
8998/// safe to move the instruction past all of the instructions between it and the
8999/// end of its block.
9000static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9001 assert(I->hasOneUse() && "Invariants didn't hold!");
9002
Chris Lattnerc4f67e62005-10-27 17:13:11 +00009003 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9004 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00009005
Chris Lattner39c98bb2004-12-08 23:43:58 +00009006 // Do not sink alloca instructions out of the entry block.
9007 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9008 return false;
9009
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009010 // We can only sink load instructions if there is nothing between the load and
9011 // the end of block that could change the value.
9012 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009013 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9014 Scan != E; ++Scan)
9015 if (Scan->mayWriteToMemory())
9016 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00009017 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00009018
9019 BasicBlock::iterator InsertPos = DestBlock->begin();
9020 while (isa<PHINode>(InsertPos)) ++InsertPos;
9021
Chris Lattner9f269e42005-08-08 19:11:57 +00009022 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00009023 ++NumSunkInst;
9024 return true;
9025}
9026
Chris Lattner1443bc52006-05-11 17:11:52 +00009027/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00009028/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00009029/// if possible.
9030static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9031 if (!TD) return CE;
9032
9033 Constant *Ptr = CE->getOperand(0);
9034 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9035 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9036 // If this is a constant expr gep that is effectively computing an
9037 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9038 bool isFoldableGEP = true;
9039 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9040 if (!isa<ConstantInt>(CE->getOperand(i)))
9041 isFoldableGEP = false;
9042 if (isFoldableGEP) {
9043 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9044 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009045 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009046 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009047 }
9048 }
9049
9050 return CE;
9051}
9052
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009053
9054/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9055/// all reachable code to the worklist.
9056///
9057/// This has a couple of tricks to make the code faster and more powerful. In
9058/// particular, we constant fold and DCE instructions as we go, to avoid adding
9059/// them to the worklist (this significantly speeds up instcombine on code where
9060/// many instructions are dead or constant). Additionally, if we find a branch
9061/// whose condition is a known constant, we only visit the reachable successors.
9062///
9063static void AddReachableCodeToWorklist(BasicBlock *BB,
9064 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009065 std::vector<Instruction*> &WorkList,
9066 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009067 // We have now visited this block! If we've already been here, bail out.
9068 if (!Visited.insert(BB).second) return;
9069
9070 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9071 Instruction *Inst = BBI++;
9072
9073 // DCE instruction if trivially dead.
9074 if (isInstructionTriviallyDead(Inst)) {
9075 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009076 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009077 Inst->eraseFromParent();
9078 continue;
9079 }
9080
9081 // ConstantProp instruction if trivially constant.
9082 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9084 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009085 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009086 Inst->replaceAllUsesWith(C);
9087 ++NumConstProp;
9088 Inst->eraseFromParent();
9089 continue;
9090 }
9091
9092 WorkList.push_back(Inst);
9093 }
9094
9095 // Recursively visit successors. If this is a branch or switch on a constant,
9096 // only visit the reachable successor.
9097 TerminatorInst *TI = BB->getTerminator();
9098 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9099 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9100 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009101 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9102 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009103 return;
9104 }
9105 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9106 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9107 // See if this is an explicit destination.
9108 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9109 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009110 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009111 return;
9112 }
9113
9114 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009115 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009116 return;
9117 }
9118 }
9119
9120 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009121 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009122}
9123
Chris Lattner113f4f42002-06-25 16:13:24 +00009124bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009125 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009126 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009127
Chris Lattner4ed40f72005-07-07 20:40:38 +00009128 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009129 // Do a depth-first traversal of the function, populate the worklist with
9130 // the reachable instructions. Ignore blocks that are not reachable. Keep
9131 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009132 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009133 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009134
Chris Lattner4ed40f72005-07-07 20:40:38 +00009135 // Do a quick scan over the function. If we find any blocks that are
9136 // unreachable, remove any instructions inside of them. This prevents
9137 // the instcombine code from having to deal with some bad special cases.
9138 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9139 if (!Visited.count(BB)) {
9140 Instruction *Term = BB->getTerminator();
9141 while (Term != BB->begin()) { // Remove instrs bottom-up
9142 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009143
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009144 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009145 ++NumDeadInst;
9146
9147 if (!I->use_empty())
9148 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9149 I->eraseFromParent();
9150 }
9151 }
9152 }
Chris Lattnerca081252001-12-14 16:52:21 +00009153
9154 while (!WorkList.empty()) {
9155 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9156 WorkList.pop_back();
9157
Chris Lattner1443bc52006-05-11 17:11:52 +00009158 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009159 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009160 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009161 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009162 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009163 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009164
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009165 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009166
9167 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009168 removeFromWorkList(I);
9169 continue;
9170 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009171
Chris Lattner1443bc52006-05-11 17:11:52 +00009172 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009173 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009174 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9175 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009176 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009177
Chris Lattner1443bc52006-05-11 17:11:52 +00009178 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009179 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009180 ReplaceInstUsesWith(*I, C);
9181
Chris Lattner99f48c62002-09-02 04:59:56 +00009182 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009183 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009184 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009185 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009186 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009187
Chris Lattner39c98bb2004-12-08 23:43:58 +00009188 // See if we can trivially sink this instruction to a successor basic block.
9189 if (I->hasOneUse()) {
9190 BasicBlock *BB = I->getParent();
9191 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9192 if (UserParent != BB) {
9193 bool UserIsSuccessor = false;
9194 // See if the user is one of our successors.
9195 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9196 if (*SI == UserParent) {
9197 UserIsSuccessor = true;
9198 break;
9199 }
9200
9201 // If the user is one of our immediate successors, and if that successor
9202 // only has us as a predecessors (we'd have to split the critical edge
9203 // otherwise), we can keep going.
9204 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9205 next(pred_begin(UserParent)) == pred_end(UserParent))
9206 // Okay, the CFG is simple enough, try to sink this instruction.
9207 Changed |= TryToSinkInstruction(I, UserParent);
9208 }
9209 }
9210
Chris Lattnerca081252001-12-14 16:52:21 +00009211 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009212 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009213 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009214 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009215 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009216 DOUT << "IC: Old = " << *I
9217 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009218
Chris Lattner396dbfe2004-06-09 05:08:07 +00009219 // Everything uses the new instruction now.
9220 I->replaceAllUsesWith(Result);
9221
9222 // Push the new instruction and any users onto the worklist.
9223 WorkList.push_back(Result);
9224 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009225
9226 // Move the name to the new instruction first...
9227 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009228 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009229
9230 // Insert the new instruction into the basic block...
9231 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009232 BasicBlock::iterator InsertPos = I;
9233
9234 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9235 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9236 ++InsertPos;
9237
9238 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009239
Chris Lattner63d75af2004-05-01 23:27:23 +00009240 // Make sure that we reprocess all operands now that we reduced their
9241 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009242 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9243 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9244 WorkList.push_back(OpI);
9245
Chris Lattner396dbfe2004-06-09 05:08:07 +00009246 // Instructions can end up on the worklist more than once. Make sure
9247 // we do not process an instruction that has been deleted.
9248 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009249
9250 // Erase the old instruction.
9251 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009252 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009253 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009254
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009255 // If the instruction was modified, it's possible that it is now dead.
9256 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009257 if (isInstructionTriviallyDead(I)) {
9258 // Make sure we process all operands now that we are reducing their
9259 // use counts.
9260 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9261 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9262 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009263
Chris Lattner63d75af2004-05-01 23:27:23 +00009264 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009265 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009266 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009267 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009268 } else {
9269 WorkList.push_back(Result);
9270 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009271 }
Chris Lattner053c0932002-05-14 15:24:07 +00009272 }
Chris Lattner260ab202002-04-18 17:39:14 +00009273 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009274 }
9275 }
9276
Chris Lattner260ab202002-04-18 17:39:14 +00009277 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009278}
9279
Brian Gaeke38b79e82004-07-27 17:43:21 +00009280FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009281 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009282}
Brian Gaeke960707c2003-11-11 22:41:34 +00009283